
--BEFORE CODE 31.12.2015
--Добавление колонки MAIN таблицы S_ACCOUNTS_NASTR
IF COLUMNPROPERTY(object_id('[dbo].[S_ACCOUNTS_NASTR]'), 'MAIN', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[S_ACCOUNTS_NASTR] ADD [MAIN] int NOT NULL CONSTRAINT [DF_S_ACCOUNTS_NASTR_MAIN] DEFAULT ((0))
GO


GO
--Таблица OBJECT_VAR_OTHER_REC
IF not exists(select * from sysobjects where id = object_id('[dbo].[OBJECT_VAR_OTHER_REC]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[OBJECT_VAR_OTHER_REC] (
	[LINK_UP] int NOT NULL ,
	[RECORD] int NOT NULL ,
	[SECOND_DICT] bit NULL )
GO

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_OBJECT_VAR_OTHER_REC_LINK_UP')
CREATE INDEX [IX_OBJECT_VAR_OTHER_REC_LINK_UP] ON [dbo].[OBJECT_VAR_OTHER_REC] ([LINK_UP]) ON [INDEX]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_OBJECT_VAR_OTHER_REC_RECORD')
CREATE INDEX [IX_OBJECT_VAR_OTHER_REC_RECORD] ON [dbo].[OBJECT_VAR_OTHER_REC] ([RECORD]) ON [INDEX]
GO
--Констрэйнты

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_OBJECT_VAR_OTHER_REC_OBJECT_VAR]'))
ALTER TABLE [dbo].[OBJECT_VAR_OTHER_REC] WITH NOCHECK 
ADD CONSTRAINT [FK_OBJECT_VAR_OTHER_REC_OBJECT_VAR] FOREIGN KEY ([LINK_UP]) REFERENCES [dbo].[OBJECT_VAR] ([LINK])
ALTER TABLE [dbo].[OBJECT_VAR_OTHER_REC] NOCHECK CONSTRAINT [FK_OBJECT_VAR_OTHER_REC_OBJECT_VAR]
GO
--Триггеры


GO
-- Загрузка изменений ПС --
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='04' AND ANALITH_NEW = '' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '04', '', '04', '', 'Задолженность неплатежеспособных дебиторов', 0, '157N_CHANGE_124N_2015', 1, 1, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='07' AND ANALITH_NEW = '' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '07', '', '07', '', 'Награды, призы, кубки и ценные подарки, сувениры', 0, '157N_CHANGE_124N_2015', 1, 1, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='107' AND ANALITH_NEW = '11' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '107', '11', '107', '11', 'Основные средства - недвижимое имущество учреждения в пути', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='108' AND ANALITH_NEW = '53' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '108', '53', '108', '53', 'Драгоценные металлы и драгоценные камни', 0, '157N_CHANGE_124N_2015', 1, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='109' AND ANALITH_NEW = '60' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '109', '61', '109', '60', 'Затраты на заработную плату в себестоимости готовой продукции, работ, услуг', 0, '157N_CHANGE_124N_2015', 2, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='109' AND ANALITH_NEW = '70' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '109', '71', '109', '70', 'Накладные расходы производства готовой продукции, работ, услуг', 0, '157N_CHANGE_124N_2015', 2, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='109' AND ANALITH_NEW = '80' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '109', '81', '109', '80', 'Общехозяйственные расходы', 0, '157N_CHANGE_124N_2015', 2, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='109' AND ANALITH_NEW = '90' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '109', '91', '109', '90', 'Издержки обращения в части прочих расходов', 0, '157N_CHANGE_124N_2015', 2, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='20' AND ANALITH_NEW = '' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '20', '', '20', '', 'Задолженность, невостребованная кредиторами', 0, '157N_CHANGE_124N_2015', 1, 1, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='201' AND ANALITH_NEW = '06' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '201', '06', '201', '06', 'Денежные средства учреждения на специальных счетах в кредитной организации', 0, '157N_CHANGE_124N_2015', 1, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='201' AND ANALITH_NEW = '13' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '201', '13', '201', '13', 'Денежные средства учреждения в пути в органе казначейства', 0, '157N_CHANGE_124N_2015', 4, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='201' AND ANALITH_NEW = '20' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '201', '20', '201', '20', 'Денежные средства учреждения в кредитной организации', 0, '157N_CHANGE_124N_2015', 1, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='203' AND ANALITH_NEW = '23' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '203', '23', '203', '23', 'Средства бюджетных учреждений на счетах органа, осуществляющего кассовое обслуживание, в пути', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='203' AND ANALITH_NEW = '24' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '203', '24', '203', '24', 'Средства автономных учреждений на счетах органа, осуществляющего кассовое обслуживание, в пути', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='203' AND ANALITH_NEW = '25' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '203', '25', '203', '25', 'Средства иных организаций на счетах органа, осуществляющего кассовое обслуживание, в пути', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='204' AND ANALITH_NEW = '32' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '204', '32', '204', '32', 'Участие в уставном фонде государственных (муниципальных) предприятий', 0, '157N_CHANGE_124N_2015', 1, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='205' AND ANALITH_NEW = '82' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '205', '82', '205', '82', 'Расчеты по невыясненным поступлениям', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='206' AND ANALITH_NEW = '11' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '206', '11', '206', '11', 'Расчеты по оплате труда', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='206' AND ANALITH_NEW = '72' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '206', '72', '206', '72', 'Расчеты по авансам на приобретение ценных бумаг, кроме акций', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='206' AND ANALITH_NEW = '73' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '206', '73', '206', '73', 'Расчеты по авансам на приобретение акций и по иным формам участия в капитале', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='206' AND ANALITH_NEW = '75' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '206', '75', '206', '75', 'Расчеты по авансам на приобретение иных финансовых активов', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='207' AND ANALITH_NEW = '24' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '207', '24', '207', '24', 'Расчеты по предоставленным займам (ссудам) в рамках целевых иностранных кредитов (заимствований)', 0, '157N_CHANGE_124N_2015', 4, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='209' AND ANALITH_NEW = '00' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '209', '00', '209', '00', 'Расчеты по ущербу и иным доходам', 0, '157N_CHANGE_124N_2015', 1, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='209' AND ANALITH_NEW = '30' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '209', '30', '209', '30', 'Расчеты по компенсации затрат', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='209' AND ANALITH_NEW = '40' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '209', '40', '209', '40', 'Расчеты по суммам принудительного изъятия', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='209' AND ANALITH_NEW = '80' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '209', '80', '209', '80', 'Расчеты по иным доходам', 0, '157N_CHANGE_124N_2015', 1, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='209' AND ANALITH_NEW = '83' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '209', '83', '209', '83', 'Расчеты по иным доходам', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='27' AND ANALITH_NEW = '' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '27', '', '27', '', 'Материальные ценности, выданные в личное пользование работникам (сотрудникам)', 0, '157N_CHANGE_124N_2015', 3, 1, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='30' AND ANALITH_NEW = '' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '30', '', '30', '', 'Расчеты по исполнению денежных обязательств через третьих лиц', 0, '157N_CHANGE_124N_2015', 3, 1, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='301' AND ANALITH_NEW = '14' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '301', '14', '301', '14', 'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом', 0, '157N_CHANGE_124N_2015', 4, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='301' AND ANALITH_NEW = '24' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '301', '24', '301', '24', 'Расчеты по заимствованиям, не являющимся государственным (муниципальным) долгом, в рамках целевых иностранных кредитов (заимствований)', 0, '157N_CHANGE_124N_2015', 4, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='301' AND ANALITH_NEW = '44' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '301', '44', '301', '44', 'Расчеты по заимствованиям в иностранной валюте, не являющимся государственным (муниципальным) долгом', 0, '157N_CHANGE_124N_2015', 4, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='31' AND ANALITH_NEW = '' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '31', '', '31', '', 'Акции по номинальной стоимости', 0, '157N_CHANGE_124N_2015', 3, 1, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='401' AND ANALITH_NEW = '00' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '401', '00', '401', '00', 'Финансовый результат экономического субъекта', 0, '157N_CHANGE_124N_2015', 1, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='401' AND ANALITH_NEW = '10' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '401', '10', '401', '10', 'Доходы экономического субъекта', 0, '157N_CHANGE_124N_2015', 1, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='401' AND ANALITH_NEW = '20' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '401', '20', '401', '20', 'Расходы экономического субъекта', 0, '157N_CHANGE_124N_2015', 1, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='401' AND ANALITH_NEW = '60' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '401', '60', '401', '60', 'Резервы предстоящих расходов', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='502' AND ANALITH_NEW = '07' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '502', '07', '502', '07', 'Принимаемые обязательства*', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='502' AND ANALITH_NEW = '09' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '502', '09', '502', '09', 'Отложенные обязательства*', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='504' AND ANALITH_NEW = '00' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '504', '00', '504', '00', 'Сметные (плановые) назначения', 0, '157N_CHANGE_124N_2015', 4, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='504' AND ANALITH_NEW = '00' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '504', '00', '504', '00', 'Сметные (плановые, прогнозные) назначения*', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='506' AND ANALITH_NEW = '00' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '506', '00', '506', '00', 'Право на принятие обязательств по приобретению материальных запасов', 0, '157N_CHANGE_124N_2015', 4, 0, USER_SID ()
IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NEW_CONV WHERE SINTH_NEW ='507' AND ANALITH_NEW = '00' AND BUF_NAME = '157N_CHANGE_124N_2015')
	INSERT INTO dbo.S_ACCOUNTS_NEW_CONV (LINK, LINK_SA, SINTH_OLD, ANALITH_OLD, SINTH_NEW, ANALITH_NEW, NAME_NEW, ORDERS, BUF_NAME, TYPE_ACCT, ZABALANCE, [SID])
	SELECT 0, 0, '507', '00', '507', '00', 'Утвержденный объем финансового обеспечения*', 0, '157N_CHANGE_124N_2015', 3, 0, USER_SID ()
GO





GO
-- Справочник ставки налога для налога на имущество (DIC_IMU_TAX_RATE) --
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_IMU_TAX_RATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_IMU_TAX_RATE', 'Справочник ставки налога для налога на имущество', 26, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICTION_REPORT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'),1,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_IMU_TAX_RATE', NAME = 'Справочник ставки налога для налога на имущество', ORDERS = '26', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICTION_REPORT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DIC_IMU_TAX_RATE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_IMU_TAX_RATE_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_IMU_TAX_RATE_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DIC_IMU_TAX_RATE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_IMU_TAX_RATE_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DIC_IMU_TAX_RATE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_IMU_TAX_RATE_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_IMU_TAX_RATE_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_IMU_TAX_RATE_CODE', 'Номенклатурный номер', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DIC_IMU_TAX_RATE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_IMU_TAX_RATE_CODE', NAME = 'Номенклатурный номер', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DIC_IMU_TAX_RATE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_IMU_TAX_RATE_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DIC_IMU_TAX_RATE_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DIC_IMU_TAX_RATE_NAME', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DIC_IMU_TAX_RATE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DIC_IMU_TAX_RATE_NAME', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DIC_IMU_TAX_RATE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DIC_IMU_TAX_RATE_NAME'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE', 'TITLE', 'Ставки налога для налога на имущество'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE', 'INIT_OBJECT_PROG', 'A_SPISOK_MENU(oForm)

A_SPISOK_UPD(oForm,0,.T.)'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''DIC_IMU_TAX_RATE'')'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE', 'LIMIT_LIST_SPR', '0'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE', 'TITLE_COLUMN_PROP', 'Ставки налога для налога на имущество'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(''DIC_IMU_TAX_RATE'')'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE', 'OPEN_CODE', 'CODE'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE', 'SERVER_TABLE_NAME', 'OTHER_REC'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE_MARKER', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE_MARKER', 'CONTROLSOURCE', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE_MARKER', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE_CODE', 'TITLE', 'Ставка'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE_CODE', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE_CODE', 'CONTROLSOURCE', 'm.cAlias+".CODE"'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE_CODE', 'SHORT_CODE_OBJ', 'CODE'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE_NAME', 'CONTROLSOURCE', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DIC_IMU_TAX_RATE_NAME', 'SHORT_CODE_OBJ', 'NAME'
GO


GO
-- Обновление настроечной таблицы счетов (S_ACCOUNTS_NASTR) --
DECLARE
	@BUF_NAME	VARCHAR (100)

SET @BUF_NAME = '157N_CHANGE_124N_2015'

-- 1. Наименование --
UPDATE T2
SET NAME = T1.NAME_NEW
FROM dbo.S_ACCOUNTS_NEW_CONV T1
INNER JOIN dbo.S_ACCOUNTS_NASTR T2 ON (T2.SINTH = T1.SINTH_NEW
	AND T2.ANALITH = T1.ANALITH_NEW)
WHERE T1.BUF_NAME = @BUF_NAME
	AND T1.TYPE_ACCT = 1

-- 2. Код счета --
UPDATE T2
SET
	SINTH = T1.SINTH_NEW,
	ANALITH = T1.ANALITH_NEW
FROM dbo.S_ACCOUNTS_NEW_CONV T1
INNER JOIN dbo.S_ACCOUNTS_NASTR T2 ON (T2.SINTH = T1.SINTH_OLD
	AND T2.ANALITH = T1.ANALITH_OLD)
WHERE T1.BUF_NAME = @BUF_NAME
	AND T1.TYPE_ACCT = 2
	AND NOT EXISTS (
					SELECT * FROM dbo.S_ACCOUNTS_NASTR T2 
					WHERE T2.SINTH = T1.SINTH_NEW
						AND T2.ANALITH = T1.ANALITH_NEW
					)

-- 3. Добавление новых счетов --
INSERT INTO dbo.S_ACCOUNTS_NASTR (
	[NAME],
	[SINTH],
	[ANALITH],
	[BUH_TYPE],
	[DOUBLE_REC],
	[KBK_TYPE],
	[S_ACTIVE],
	[KSU],
	[KBK],
	[P_KASSA],
	[EKR0],
	[AP_EKR],
	[AP_NOMEN],
	[AP_INV],
	[AP_EMP],
	[AP_DEP],
	[AP_DOP],
	[AP_DEP_ACC],
	[AP_DOC],
	[AP_SUB],
	[P_NOCONTROL],
	[AP_TMC],
	[AP_INDATE],
	[AP_KAU],
	[JONUM],
	[P_DATE],
	[NOMEN_TYPE],
	[ZABALANCE],
	[MAIN])
	
SELECT
	[NAME]	=	T1.NAME_NEW,
	[SINTH]	=	T1.SINTH_NEW,
	[ANALITH]	=	T1.ANALITH_NEW,
	[BUH_TYPE]	=	7,
	[DOUBLE_REC]	=	0,
	[KBK_TYPE]	=	0,
	[S_ACTIVE]	=	CASE
						WHEN T1.ZABALANCE = 1 OR T1.ZABALANCE = 0 AND LEFT (T1.SINTH_NEW, 1) LIKE '[1,2]' THEN 1
						ELSE 0
					END,
	[KSU]	=	CASE
						WHEN T1.ZABALANCE = 1 AND T1.SINTH_NEW = '27' OR T1.ZABALANCE = 0 AND LEFT (T1.SINTH_NEW, 1) LIKE '[1]' THEN 1
						ELSE 0
					END,
	[KBK]	=	CASE
					WHEN T1.SINTH_NEW = '107' THEN 'КРБ'
					WHEN T1.SINTH_NEW = '203' THEN 'КРБ'
					WHEN T1.SINTH_NEW = '206' THEN 'КРБ'
					WHEN T1.SINTH_NEW = '210' THEN 'КРБ, КДБ'
					WHEN T1.SINTH_NEW = '205' THEN 'КДБ'
					WHEN T1.SINTH_NEW = '209' THEN 'КИФ'
					WHEN T1.SINTH_NEW = '401' THEN 'КРБ'
					WHEN T1.SINTH_NEW = '502' THEN 'КРБ, КИФ'
					ELSE ''
				END,
	[P_KASSA]	=	CASE
						WHEN T1.SINTH_NEW = '401' OR T1.SINTH_NEW LIKE '50[1-9]' THEN 1
						ELSE 0
					END,
	[EKR0]	=	CASE
					WHEN T1.SINTH_NEW = '205'AND T1.ANALITH_NEW = '82' THEN '180'
					WHEN T1.SINTH_NEW = '206'AND T1.ANALITH_NEW = '11' THEN '211'
					WHEN T1.SINTH_NEW = '206'AND T1.ANALITH_NEW = '72' THEN '520'
					WHEN T1.SINTH_NEW = '206'AND T1.ANALITH_NEW = '73' THEN '530'
					WHEN T1.SINTH_NEW = '206'AND T1.ANALITH_NEW = '75' THEN '550'
					ELSE ''
				END,
	[AP_EKR]	=	CASE
						WHEN T1.SINTH_NEW = '401' OR T1.SINTH_NEW LIKE '50[1-9]'
							OR T1.SINTH_NEW LIKE '20[5,6,8]' THEN 1
						ELSE 0
					END,
	[AP_NOMEN]	=	0,
	[AP_INV]	=	CASE
						WHEN T1.SINTH_NEW LIKE '10[1-8]' THEN 1
						ELSE 0
					END,
	[AP_EMP]	=	CASE
						WHEN T1.SINTH_NEW LIKE '10[1-8]' OR T1.SINTH_NEW = '27' THEN 1
						ELSE 0
					END,
	[AP_DEP]	=	CASE
						WHEN T1.SINTH_NEW = '205' OR T1.SINTH_NEW = '206' AND T1.ANALITH_NEW NOT LIKE '1[1-3]' THEN 1
						ELSE 0
					END,
	[AP_DOP]	=	0,
	[AP_DEP_ACC]	=	0,
	[AP_DOC]	=	0,
	[AP_SUB]	=	0,
	[P_NOCONTROL]	=	0,
	[AP_TMC]	=	CASE
						WHEN T1.SINTH_NEW = '27' OR T1.SINTH_NEW = '31' THEN 1
						ELSE 0
					END,
	[AP_INDATE]	=	0,
	[AP_KAU]	=	0,
	[JONUM]	=	CASE
					WHEN T1.ZABALANCE = 1 THEN 'ЗБ'
					WHEN T1.SINTH_NEW = '205' THEN '05'
					WHEN T1.SINTH_NEW = '206' AND T1.ANALITH_NEW = '11' THEN '06'					
					WHEN T1.SINTH_NEW = '206' AND T1.ANALITH_NEW LIKE '7[2-5]' THEN '04'					
					WHEN T1.SINTH_NEW = '401' THEN ''
					ELSE '08'
				END,
	[P_DATE]	=	0,
	[NOMEN_TYPE]	=	0,
	[ZABALANCE]	=	T1.ZABALANCE,
	[MAIN]	=	0
FROM dbo.S_ACCOUNTS_NEW_CONV T1
WHERE T1.BUF_NAME = @BUF_NAME
	AND T1.TYPE_ACCT = 3
	AND NOT EXISTS (
					SELECT * FROM dbo.S_ACCOUNTS_NASTR T2 
					WHERE T2.SINTH = T1.SINTH_NEW
						AND T2.ANALITH = T1.ANALITH_NEW
					)
-- 4. Удаление --
DELETE T2
FROM dbo.S_ACCOUNTS_NEW_CONV T1
INNER JOIN dbo.S_ACCOUNTS_NASTR T2 ON (T2.SINTH = T1.SINTH_NEW
	AND T2.ANALITH = T1.ANALITH_NEW)
WHERE T1.BUF_NAME = @BUF_NAME
	AND T1.TYPE_ACCT = 4

--
GO


GO
-- Отбор ставок налога для налога на имущество (OTBOR_QUERY_DIC_IMU_TAX_RATE) --
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='OTBOR_QUERY_DIC_IMU_TAX_RATE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'OTBOR_QUERY_DIC_IMU_TAX_RATE', 'Отбор ставок налога для налога на имущество', 85, (SELECT LINK FROM S_OBJECTS WHERE CODE='QUERY_OTBOR_CATALOG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='QUERY_OTBOR_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'OTBOR_QUERY_DIC_IMU_TAX_RATE', NAME = 'Отбор ставок налога для налога на имущество', ORDERS = '85', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='QUERY_OTBOR_CATALOG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='QUERY_OTBOR_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='OTBOR_QUERY_DIC_IMU_TAX_RATE'
GO
EXEC X_SET_PROP 'OTBOR_QUERY_DIC_IMU_TAX_RATE', 'QUERY_OTBOR_DICTIONARY_CODE', 'DIC_IMU_TAX_RATE'
GO


GO
-- Обновление настроечной таблицы счетов на СГУ (S_ACCOUNTS_NASTR_KOSGU) -- 
IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '108' AND ANALITH = '53' AND SGU = '310')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Увеличение стоимости драгоценных металлов и драгоценных камней', DB_KR = 0
	WHERE SINTH = '108' AND ANALITH = '53' AND SGU = '310'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('108', '53', '310', 'Увеличение стоимости драгоценных металлов и драгоценных камней', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '108' AND ANALITH = '53' AND SGU = '410')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Уменьшение стоимости драгоценных металлов и драгоценных камней', DB_KR = 1
	WHERE SINTH = '108' AND ANALITH = '53' AND SGU = '410'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('108', '53', '410', 'Уменьшение стоимости драгоценных металлов и драгоценных камней', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '203' AND ANALITH = '22' AND SGU = '510')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание, в пути', DB_KR = 0
	WHERE SINTH = '203' AND ANALITH = '22' AND SGU = '510'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('203', '22', '510', 'Поступления средств бюджета на счета органа, осуществляющего кассовое обслуживание, в пути', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '203' AND ANALITH = '22' AND SGU = '610')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание, в пути', DB_KR = 1
	WHERE SINTH = '203' AND ANALITH = '22' AND SGU = '610'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('203', '22', '610', 'Выбытия средств бюджета со счетов органа, осуществляющего кассовое обслуживание, в пути', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '203' AND ANALITH = '23' AND SGU = '510')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание, в пути', DB_KR = 0
	WHERE SINTH = '203' AND ANALITH = '23' AND SGU = '510'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('203', '23', '510', 'Поступления средств бюджетных учреждений на счета органа, осуществляющего кассовое обслуживание, в пути', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '203' AND ANALITH = '23' AND SGU = '610')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание, в пути', DB_KR = 1
	WHERE SINTH = '203' AND ANALITH = '23' AND SGU = '610'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('203', '23', '610', 'Выбытия средств бюджетных учреждений со счетов органа, осуществляющего кассовое обслуживание, в пути', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '203' AND ANALITH = '24' AND SGU = '510')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание, в пути', DB_KR = 0
	WHERE SINTH = '203' AND ANALITH = '24' AND SGU = '510'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('203', '24', '510', 'Поступления средств автономных учреждений на счета органа, осуществляющего кассовое обслуживание, в пути', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '203' AND ANALITH = '24' AND SGU = '610')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание, в пути', DB_KR = 1
	WHERE SINTH = '203' AND ANALITH = '24' AND SGU = '610'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('203', '24', '610', 'Выбытия средств автономных учреждений со счетов органа, осуществляющего кассовое обслуживание, в пути', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '203' AND ANALITH = '25' AND SGU = '510')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание, в пути', DB_KR = 0
	WHERE SINTH = '203' AND ANALITH = '25' AND SGU = '510'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('203', '25', '510', 'Поступления средств иных организаций на счета органа, осуществляющего кассовое обслуживание, в пути', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '203' AND ANALITH = '25' AND SGU = '610')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание, в пути', DB_KR = 1
	WHERE SINTH = '203' AND ANALITH = '25' AND SGU = '610'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('203', '25', '610', 'Выбытия средств иных организаций со счетов органа, осуществляющего кассовое обслуживание, в пути', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '206' AND ANALITH = '72' AND SGU = '560')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Увеличение дебиторской задолженности по авансам на приобретение ценных бумаг, кроме акций', DB_KR = 0
	WHERE SINTH = '206' AND ANALITH = '72' AND SGU = '560'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('206', '72', '560', 'Увеличение дебиторской задолженности по авансам на приобретение ценных бумаг, кроме акций', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '206' AND ANALITH = '72' AND SGU = '660')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Уменьшение дебиторской задолженности по авансам на приобретение ценных бумаг, кроме акций', DB_KR = 1
	WHERE SINTH = '206' AND ANALITH = '72' AND SGU = '660'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('206', '72', '660', 'Уменьшение дебиторской задолженности по авансам на приобретение ценных бумаг, кроме акций', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '206' AND ANALITH = '73' AND SGU = '560')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Увеличение дебиторской задолженности по авансам на приобретение акций и по иным формам участия в капитале', DB_KR = 0
	WHERE SINTH = '206' AND ANALITH = '73' AND SGU = '560'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('206', '73', '560', 'Увеличение дебиторской задолженности по авансам на приобретение акций и по иным формам участия в капитале', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '206' AND ANALITH = '73' AND SGU = '660')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Уменьшение дебиторской задолженности по авансам на приобретение акций и по иным формам участия в капитале', DB_KR = 1
	WHERE SINTH = '206' AND ANALITH = '73' AND SGU = '660'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('206', '73', '660', 'Уменьшение дебиторской задолженности по авансам на приобретение акций и по иным формам участия в капитале', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '206' AND ANALITH = '75' AND SGU = '560')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Увеличение дебиторской задолженности по авансам на приобретение иных финансовых активов', DB_KR = 0
	WHERE SINTH = '206' AND ANALITH = '75' AND SGU = '560'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('206', '75', '560', 'Увеличение дебиторской задолженности по авансам на приобретение иных финансовых активов', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '206' AND ANALITH = '75' AND SGU = '660')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Уменьшение дебиторской задолженности по авансам на приобретение иных финансовых активов', DB_KR = 1
	WHERE SINTH = '206' AND ANALITH = '75' AND SGU = '660'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('206', '75', '660', 'Уменьшение дебиторской задолженности по авансам на приобретение иных финансовых активов', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '107' AND ANALITH = '11' AND SGU = '310')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Увеличение стоимости основных средств - недвижимого имущества учреждения в пути', DB_KR = 0
	WHERE SINTH = '107' AND ANALITH = '11' AND SGU = '310'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('107', '11', '310', 'Увеличение стоимости основных средств - недвижимого имущества учреждения в пути', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '107' AND ANALITH = '11' AND SGU = '410')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Уменьшение стоимости основных средств - недвижимого имущества учреждения в пути', DB_KR = 1
	WHERE SINTH = '107' AND ANALITH = '11' AND SGU = '410'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('107', '11', '410', 'Уменьшение стоимости основных средств - недвижимого имущества учреждения в пути', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '109' AND ANALITH = '60' AND SGU = '200')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Прямые затраты на изготовление готовой продукции, выполнение работ, оказание услуг', DB_KR = 1
	WHERE SINTH = '109' AND ANALITH = '60' AND SGU = '200'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('109', '60', '200', 'Прямые затраты на изготовление готовой продукции, выполнение работ, оказание услуг', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '109' AND ANALITH = '60' AND SGU = '271')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Затраты по амортизации основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг', DB_KR = 1
	WHERE SINTH = '109' AND ANALITH = '60' AND SGU = '271'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('109', '60', '271', 'Затраты по амортизации основных средств и нематериальных активов в себестоимости готовой продукции, работ, услуг', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '109' AND ANALITH = '60' AND SGU = '272')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Затраты по расходованию материальных запасов в себестоимости готовой продукции, работ, услуг', DB_KR = 1
	WHERE SINTH = '109' AND ANALITH = '60' AND SGU = '272'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('109', '60', '272', 'Затраты по расходованию материальных запасов в себестоимости готовой продукции, работ, услуг', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '204' AND ANALITH = '32' AND SGU = '530')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Увеличение участия в уставном фонде государственных (муниципальных) предприятий', DB_KR = 0
	WHERE SINTH = '204' AND ANALITH = '32' AND SGU = '530'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('204', '32', '530', 'Увеличение участия в уставном фонде государственных (муниципальных) предприятий', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '204' AND ANALITH = '32' AND SGU = '630')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Уменьшение участия в уставном фонде государственных (муниципальных) предприятий', DB_KR = 1
	WHERE SINTH = '204' AND ANALITH = '32' AND SGU = '630'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('204', '32', '630', 'Уменьшение участия в уставном фонде государственных (муниципальных) предприятий', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '205' AND ANALITH = '82' AND SGU = '560')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Увеличение дебиторской задолженности по невыясненным поступлениям', DB_KR = 0
	WHERE SINTH = '205' AND ANALITH = '82' AND SGU = '560'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('205', '82', '560', 'Увеличение дебиторской задолженности по невыясненным поступлениям', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '205' AND ANALITH = '82' AND SGU = '660')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Уменьшение дебиторской задолженности по невыясненным поступлениям', DB_KR = 1
	WHERE SINTH = '205' AND ANALITH = '82' AND SGU = '660'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('205', '82', '660', 'Уменьшение дебиторской задолженности по невыясненным поступлениям', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '206' AND ANALITH = '11' AND SGU = '560')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Увеличение дебиторской задолженности по оплате труда', DB_KR = 0
	WHERE SINTH = '206' AND ANALITH = '11' AND SGU = '560'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('206', '11', '560', 'Увеличение дебиторской задолженности по оплате труда', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '206' AND ANALITH = '11' AND SGU = '660')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Уменьшение дебиторской задолженности по оплате труда', DB_KR = 1
	WHERE SINTH = '206' AND ANALITH = '11' AND SGU = '660'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('206', '11', '660', 'Уменьшение дебиторской задолженности по оплате труда', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '209' AND ANALITH = '30' AND SGU = '560')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Увеличение дебиторской задолженности по компенсации затрат', DB_KR = 0
	WHERE SINTH = '209' AND ANALITH = '30' AND SGU = '560'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('209', '30', '560', 'Увеличение дебиторской задолженности по компенсации затрат', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '209' AND ANALITH = '30' AND SGU = '660')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Уменьшение дебиторской задолженности по компенсации затрат', DB_KR = 1
	WHERE SINTH = '209' AND ANALITH = '30' AND SGU = '660'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('209', '30', '660', 'Уменьшение дебиторской задолженности по компенсации затрат', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '209' AND ANALITH = '40' AND SGU = '560')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Увеличение дебиторской задолженности по суммам принудительного изъятия', DB_KR = 0
	WHERE SINTH = '209' AND ANALITH = '40' AND SGU = '560'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('209', '40', '560', 'Увеличение дебиторской задолженности по суммам принудительного изъятия', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '209' AND ANALITH = '40' AND SGU = '660')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Уменьшение дебиторской задолженности по суммам принудительного изъятия', DB_KR = 1
	WHERE SINTH = '209' AND ANALITH = '40' AND SGU = '660'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('209', '40', '660', 'Уменьшение дебиторской задолженности по суммам принудительного изъятия', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '209' AND ANALITH = '83' AND SGU = '560')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Увеличение дебиторской задолженности по расчетам по иным доходам', DB_KR = 0
	WHERE SINTH = '209' AND ANALITH = '83' AND SGU = '560'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('209', '83', '560', 'Увеличение дебиторской задолженности по расчетам по иным доходам', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '209' AND ANALITH = '83' AND SGU = '660')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Уменьшение дебиторской задолженности по расчетам по иным доходам', DB_KR = 1
	WHERE SINTH = '209' AND ANALITH = '83' AND SGU = '660'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('209', '83', '660', 'Уменьшение дебиторской задолженности по расчетам по иным доходам', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '210' AND ANALITH = '11' AND SGU = '560')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Увеличение дебиторской задолженности по НДС по авансам полученным', DB_KR = 0
	WHERE SINTH = '210' AND ANALITH = '11' AND SGU = '560'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('210', '11', '560', 'Увеличение дебиторской задолженности по НДС по авансам полученным', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '210' AND ANALITH = '11' AND SGU = '660')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Уменьшение дебиторской задолженности по НДС по авансам полученным', DB_KR = 1
	WHERE SINTH = '210' AND ANALITH = '11' AND SGU = '660'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('210', '11', '660', 'Уменьшение дебиторской задолженности по НДС по авансам полученным', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '210' AND ANALITH = '12' AND SGU = '560')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Увеличение дебиторской задолженности по приобретенным материальным ценностям, работам, услугам', DB_KR = 0
	WHERE SINTH = '210' AND ANALITH = '12' AND SGU = '560'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('210', '12', '560', 'Увеличение дебиторской задолженности по приобретенным материальным ценностям, работам, услугам', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '210' AND ANALITH = '12' AND SGU = '660')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Уменьшение дебиторской задолженности по приобретенным материальным ценностям, работам, услугам', DB_KR = 1
	WHERE SINTH = '210' AND ANALITH = '12' AND SGU = '660'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('210', '12', '660', 'Уменьшение дебиторской задолженности по приобретенным материальным ценностям, работам, услугам', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '304' AND ANALITH = '06' AND SGU = '730')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Увеличение расчетов с прочими кредиторами', DB_KR = 0
	WHERE SINTH = '304' AND ANALITH = '06' AND SGU = '730'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('304', '06', '730', 'Увеличение расчетов с прочими кредиторами', 0)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '304' AND ANALITH = '06' AND SGU = '830')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Уменьшение расчетов с прочими кредиторами', DB_KR = 1
	WHERE SINTH = '304' AND ANALITH = '06' AND SGU = '830'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('304', '06', '830', 'Уменьшение расчетов с прочими кредиторами', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '307' AND ANALITH = '12' AND SGU = '600')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов', DB_KR = 1
	WHERE SINTH = '307' AND ANALITH = '12' AND SGU = '600'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('307', '12', '600', 'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по выбытию финансовых активов', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '307' AND ANALITH = '12' AND SGU = '610')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (уменьшению) остатков денежных средств', DB_KR = 1
	WHERE SINTH = '307' AND ANALITH = '12' AND SGU = '610'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('307', '12', '610', 'Расчеты по операциям бюджета на счетах органа, осуществляющего кассовое обслуживание, по изменению (уменьшению) остатков денежных средств', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '401' AND ANALITH = '40' AND SGU = '110')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Налоговые доходы будущих периодов', DB_KR = 1
	WHERE SINTH = '401' AND ANALITH = '40' AND SGU = '110'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('401', '40', '110', 'Налоговые доходы будущих периодов', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '401' AND ANALITH = '40' AND SGU = '130')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Доходы будущих периодов от оказания платных услуг', DB_KR = 1
	WHERE SINTH = '401' AND ANALITH = '40' AND SGU = '130'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('401', '40', '130', 'Доходы будущих периодов от оказания платных услуг', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '401' AND ANALITH = '40' AND SGU = '140')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Доходы будущих периодов от сумм принудительного изъятия', DB_KR = 1
	WHERE SINTH = '401' AND ANALITH = '40' AND SGU = '140'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('401', '40', '140', 'Доходы будущих периодов от сумм принудительного изъятия', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '401' AND ANALITH = '40' AND SGU = '172')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Доходы будущих периодов от операций с активами', DB_KR = 1
	WHERE SINTH = '401' AND ANALITH = '40' AND SGU = '172'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('401', '40', '172', 'Доходы будущих периодов от операций с активами', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '401' AND ANALITH = '40' AND SGU = '180')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Прочие доходы будущих периодов', DB_KR = 1
	WHERE SINTH = '401' AND ANALITH = '40' AND SGU = '180'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('401', '40', '180', 'Прочие доходы будущих периодов', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '401' AND ANALITH = '50' AND SGU = '211')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Расходы будущих периодов по заработной плате', DB_KR = 1
	WHERE SINTH = '401' AND ANALITH = '50' AND SGU = '211'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('401', '50', '211', 'Расходы будущих периодов по заработной плате', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '401' AND ANALITH = '50' AND SGU = '212')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Расходы будущих периодов по прочим выплатам', DB_KR = 1
	WHERE SINTH = '401' AND ANALITH = '50' AND SGU = '212'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('401', '50', '212', 'Расходы будущих периодов по прочим выплатам', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '401' AND ANALITH = '50' AND SGU = '213')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Расходы на начисление на выплаты по оплате труда', DB_KR = 1
	WHERE SINTH = '401' AND ANALITH = '50' AND SGU = '213'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('401', '50', '213', 'Расходы на начисление на выплаты по оплате труда', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '401' AND ANALITH = '50' AND SGU = '221')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Расходы будущих периодов на оплату услуг связи', DB_KR = 1
	WHERE SINTH = '401' AND ANALITH = '50' AND SGU = '221'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('401', '50', '221', 'Расходы будущих периодов на оплату услуг связи', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '401' AND ANALITH = '50' AND SGU = '225')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Расходы будущих периодов на работы, услуги по содержанию имущества', DB_KR = 1
	WHERE SINTH = '401' AND ANALITH = '50' AND SGU = '225'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('401', '50', '225', 'Расходы будущих периодов на работы, услуги по содержанию имущества', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '401' AND ANALITH = '50' AND SGU = '226')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Расходы будущих периодов на прочие работы, услуг', DB_KR = 1
	WHERE SINTH = '401' AND ANALITH = '50' AND SGU = '226'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('401', '50', '226', 'Расходы будущих периодов на прочие работы, услуг', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '401' AND ANALITH = '50' AND SGU = '262')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Расходы будущих периодов на пособия по социальной помощи населению', DB_KR = 1
	WHERE SINTH = '401' AND ANALITH = '50' AND SGU = '262'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('401', '50', '262', 'Расходы будущих периодов на пособия по социальной помощи населению', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '402' AND ANALITH = '10' AND SGU = '510')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Поступление на счет средств во временное распоряжение получателей средств бюджета', DB_KR = 1
	WHERE SINTH = '402' AND ANALITH = '10' AND SGU = '510'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('402', '10', '510', 'Поступление на счет средств во временное распоряжение получателей средств бюджета', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '402' AND ANALITH = '20' AND SGU = '610')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Выбытие со счета средств во временном распоряжении получателей средств бюджета', DB_KR = 1
	WHERE SINTH = '402' AND ANALITH = '20' AND SGU = '610'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('402', '20', '610', 'Выбытие со счета средств во временном распоряжении получателей средств бюджета', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '502' AND ANALITH = '02' AND SGU = '230')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Принятые денежные обязательства по обслуживанию государственного (муниципального) долга', DB_KR = 1
	WHERE SINTH = '502' AND ANALITH = '02' AND SGU = '230'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('502', '02', '230', 'Принятые денежные обязательства по обслуживанию государственного (муниципального) долга', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '502' AND ANALITH = '02' AND SGU = '231')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Принятые денежные обязательства по обслуживанию внутреннего долга', DB_KR = 1
	WHERE SINTH = '502' AND ANALITH = '02' AND SGU = '231'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('502', '02', '231', 'Принятые денежные обязательства по обслуживанию внутреннего долга', 1)

IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS_NASTR_KOSGU WHERE SINTH = '502' AND ANALITH = '02' AND SGU = '232')
	UPDATE dbo.S_ACCOUNTS_NASTR_KOSGU  SET NAME = 'Принятые денежные обязательства по обслуживанию внешнего государственного долга', DB_KR = 1
	WHERE SINTH = '502' AND ANALITH = '02' AND SGU = '232'
ELSE
	INSERT INTO dbo.S_ACCOUNTS_NASTR_KOSGU (SINTH, ANALITH, SGU, NAME, DB_KR )
	VALUES ('502', '02', '232', 'Принятые денежные обязательства по обслуживанию внешнего государственного долга', 1)

GO




GO
-- Удаляем из буфера счета, у которых новый есть плане счетов --
-- Измение плана счетов по 124Н --
--- ЗНАЧЕНИЯ ДЛЯ S_ACCOUNTS_NEW_CONV ---
--- TYPE_ACCT = 1	МЕНЯЕТСЯ НАИМЕНОВАНИЕ СЧЕТА ---
--- TYPE_ACCT = 2	МЕНЯЕТСЯ КОД СЧЕТА ---
--- TYPE_ACCT = 3	ДОБАВЛЯЕМ НОВЫЕ СЧЕТА ---
DECLARE
	@BUF_NAME	VARCHAR (100)

SET @BUF_NAME = '157N_CHANGE_124N_2015'

DELETE T1
FROM dbo.S_ACCOUNTS_NEW_CONV T1
WHERE T1.BUF_NAME = @BUF_NAME
	AND (TYPE_ACCT = 2	OR TYPE_ACCT = 3)
	AND EXISTS (SELECT *
				FROM dbo.S_ACCOUNTS TTT
				WHERE TTT.ZABALANS = T1.ZABALANCE
					AND TTT.cSINTH = T1.SINTH_NEW
					AND TTT.cANALIT = T1.ANALITH_NEW)
GO


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

GO

CREATE FUNCTION dbo.BK_DOC_TAB_MX3_INV_FN
	(@intLINK_DOC	INT =	NULL)
RETURNS TABLE
AS
RETURN
	SELECT 
		OTR.LINK,
		OTR.LINK_UP,
		OTR.[OBJECT],
		OTR.ORDERS,
		OTR.LINK_OPER,
		OT1.INV_TYPE,
		INV = T2.LINK,
		T2.INV_CODE,
		T2.INV_NAME,
		UM	=	DG.LINK,
		UM_CODE	=	DG.CODE,
		UM_SNAME	=	DG.SNAME,
		OTMC.QTY,
		OTMC.SUMMA,
		OTMC.PRICE,
		COMMENT = (SELECT CONVERT (VARCHAR (254), OTS.STRING)
					FROM dbo.OUT_TABLE_STRING OTS
					WHERE OTS.LINK_UP = OTR.LINK
						AND OTS.[OBJECT] = dbo.GetObjLink ('DOC_MX3_INV_T_COMMENT')
					),
		INV_CHAR = (SELECT CONVERT (VARCHAR (254), OTS.STRING)
					FROM dbo.OUT_TABLE_STRING OTS
					WHERE OTS.LINK_UP = OTR.LINK
						AND OTS.[OBJECT] = dbo.GetObjLink ('DOC_MX3_INV_T_INV_CHAR')
					)
	FROM dbo.OUT_TABLE_ROW OTR
	LEFT JOIN dbo.OUT_TABLE_INV_TYPE OT1 ON (OT1.LINK_UP = OTR.LINK)
	LEFT JOIN dbo.SELECT_MZ_WITH_TYPE T2 ON (T2.INV_TYPE = OT1.INV_TYPE
		AND (OT1.INV_TYPE = 'INVENTORY_CARD' AND T2.LINK = OT1.INV
			OR (OT1.INV_TYPE = 'BV_NOMENCLATURE' OR OT1.INV_TYPE = 'DICTIONARY_SERV') AND T2.LINK = OT1.NOMEN
			OR OT1.INV_TYPE = 'DICTIONARY_TMC' AND T2.LINK = OT1.TMC)
			)
	LEFT JOIN dbo.DICTIONARY_DIGIT DG ON (DG.LINK = T2.UM_LINK)
	LEFT JOIN dbo.OUT_TABLE_MZ_CHARGE OTMC ON (OTMC.LINK_UP = OTR.LINK)
	WHERE OTR.[OBJECT] = dbo.GetObjLink ('DOC_MX3_INV_TABLE')
		AND (@intLINK_DOC IS NULL
			OR OTR.LINK_UP = @intLINK_DOC
			)	

GO


GRANT SELECT ON dbo.[BK_DOC_TAB_MX3_INV_FN] TO PUBLIC

GO


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


GO
--Таблица G_PROV_EXCH_STATUS
IF not exists(select * from sysobjects where id = object_id('[dbo].[GP_EXCH_STATUS]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[GP_EXCH_STATUS] (
	[link_GP] INT NOT NULL,
	[STATUS] int NOT NULL DEFAULT (0),
	[DATE] DATETIME NULL,
	COMMENT VARCHAR(800) NULL)
GO

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_link_GP]'))
ALTER TABLE [dbo].[GP_EXCH_STATUS] WITH NOCHECK 
ADD CONSTRAINT [FK_link_GP] FOREIGN KEY ([link_GP]) REFERENCES [dbo].[G_PROV] ([LINK])
ALTER TABLE [dbo].[GP_EXCH_STATUS] NOCHECK CONSTRAINT [FK_link_GP]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[UN_GP_EXCH_STATUS_UNIQ]'))
ALTER TABLE [dbo].[GP_EXCH_STATUS] 
ADD CONSTRAINT [UN_GP_EXCH_STATUS_UNIQ] UNIQUE NONCLUSTERED ([link_GP]) ON [INDEX]
GO

--Триггеры

GO
--Добавление колонки [year] в таблицу HOLIDAYS
IF COLUMNPROPERTY(object_id('[dbo].[HOLIDAYS]'), 'year', 'AllowsNull') is null
	ALTER TABLE [dbo].[HOLIDAYS] ADD [year] int NOT NULL  CONSTRAINT [DF_HOLIDAYS_YAER] default (1900) 
GO


GO

/****** Изменение размерности поля REF_ATT в таблице [dbo].[ITEM_MOVE]  ******/
IF COLUMNPROPERTY(object_id('[dbo].[ITEM_MOVE]'), 'REF_ATT', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[ITEM_MOVE] ADD [REF_ATT] int NULL 
GO


IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_ITEM_MOVE_EMPL_ATTEST]'))
ALTER TABLE [dbo].[ITEM_MOVE] 
ADD CONSTRAINT [FK_ITEM_MOVE_EMPL_ATTEST] FOREIGN KEY ([REF_ATT]) REFERENCES [dbo].[EMPL_ATTEST] ([LINK])
GO


/****** Изменение размерности поля SHORT_COMM в таблице [dbo].[EMPL_ATTEST]  ******/
IF COLUMNPROPERTY(object_id('[dbo].[EMPL_ATTEST]'), 'SHORT_COMM', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[EMPL_ATTEST] ADD [SHORT_COMM] VARCHAR(256) NULL 
GO

/****** Изменение размерности поля COMMENT в таблице [dbo].[EMPL_ATTEST]  ******/
IF COLUMNPROPERTY(object_id('[dbo].[EMPL_ATTEST]'), 'COMMENT', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[EMPL_ATTEST] ADD [COMMENT] VARCHAR(4000) NULL 
GO

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

GO

/****** добавление колонки LINK_SGU в таблицу [dbo].[KL_KBK_IVF]  ******/
IF COLUMNPROPERTY(object_id('[dbo].[KL_KBK_IVF]'), 'LINK_SGU', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[KL_KBK_IVF] ADD [LINK_SGU] int NULL 
GO

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

/****** добавление колонки LINK_SGU в таблицу [dbo].[KL_KBK_KD]  ******/
IF COLUMNPROPERTY(object_id('[dbo].[KL_KBK_KD]'), 'LINK_SGU', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[KL_KBK_KD] ADD [LINK_SGU] int NULL 
GO

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

GO

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


--Обновление колонки CODE таблицы KL_KBK
IF COLUMNPROPERTY(object_id('[dbo].[KL_KBK]'), 'CODE', 'Precision') = 20
	ALTER TABLE [dbo].[KL_KBK] ALTER COLUMN  [CODE] CHAR(30) NOT NULL 
GO



IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_KL_KBK')
CREATE INDEX [IX_KL_KBK] ON [dbo].[KL_KBK] ([TYPE], [CODE]) ON [INDEX]
GO
GO

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


--Обновление колонки CODE таблицы KL_TARGET_ITEM
IF COLUMNPROPERTY(object_id('[dbo].[KL_TARGET_ITEM]'), 'CODE', 'Precision') = 7
	ALTER TABLE [dbo].[KL_TARGET_ITEM] ALTER COLUMN  [CODE] CHAR(10) NOT NULL 
GO


IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[IX_KL_TARGET_ITEM]'))
ALTER TABLE [dbo].[KL_TARGET_ITEM] 
ADD CONSTRAINT [IX_KL_TARGET_ITEM] UNIQUE CLUSTERED ([CODE])
GO

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


GO
--Таблица rms_contacts
IF not exists(select * from sysobjects where id = object_id('[dbo].[rms_CONTACTS]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
begin
CREATE TABLE [dbo].[rms_CONTACTS] (
	[LINK] int NOT NULL IDENTITY(1,1) ,
	[CONTACT_ID] int NOT NULL ,
	[TYPE] nvarchar(50) NULL ,
	[NAME] nvarchar(255) NULL ,
	[ADDRESS] nvarchar(255) NOT NULL ,
	[ENABLED] bit NULL ,
	[SERVICE] bit NULL ,
	[MYSELF] bit NULL ,
	[OPENED] bit NULL ,
	[ON_LINE] bit NULL ,
	[ACCESS_MODE] nvarchar(50) NULL ,
	[COMMENTS] nvarchar(1024) NULL )

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


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

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[PK__rms_CONTACTS__45CAD6F1]'))
ALTER TABLE [dbo].[rms_CONTACTS] 
ADD CONSTRAINT [PK__rms_CONTACTS__45CAD6F1] PRIMARY KEY CLUSTERED ([LINK])


IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[UQ__rms_CONTACTS__46BEFB2A]'))
ALTER TABLE [dbo].[rms_CONTACTS] 
ADD CONSTRAINT [UQ__rms_CONTACTS__46BEFB2A] UNIQUE NONCLUSTERED ([ADDRESS]) ON [INDEX]


IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[UQ__rms_CONTACTS__47B31F63]'))
ALTER TABLE [dbo].[rms_CONTACTS] 
ADD CONSTRAINT [UQ__rms_CONTACTS__47B31F63] UNIQUE NONCLUSTERED ([CONTACT_ID]) ON [INDEX]

END
GO

--Триггеры


GO

--Обновление колонки CODE таблицы SAL_SFIN
IF COLUMNPROPERTY(object_id('[dbo].[SAL_SFIN]'), 'CODE', 'Precision') = 20
	ALTER TABLE [dbo].[SAL_SFIN] ALTER COLUMN  [CODE] CHAR(30) NOT NULL 
GO


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


ALTER TABLE [dbo].[KOSGU] ALTER COLUMN [CODE] char(4) NOT NULL 
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_KOSGU')
CREATE UNIQUE INDEX [IX_KOSGU] ON [dbo].[KOSGU] ([CODE]) ON [INDEX]
GO

IF NOT EXISTS (SELECT * FROM dbo.[KOSGU] WHERE CODE = 'R211')
	INSERT INTO dbo.[KOSGU]([CODE], [NAME], [DB_KR], [Is_Ekr])  
	VALUES ('R211', 'Заработная плата за счет резерва', 1, 1)
GO



GO
--Таблица SDOC_RESERV
IF not exists(select * from sysobjects where id = object_id('[dbo].[SDOC_RESERV]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[SDOC_RESERV] (
	[LINK_UP] int NOT NULL ,
	[DATE] datetime NOT NULL ,
	[PERIOD] datetime NOT NULL )
GO

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_SDOC_RESERV')
CREATE INDEX [IX_SDOC_ASEV] ON [dbo].[SDOC_RESERV] ([LINK_UP]) ON [INDEX]
GO

--Констрэйнты
IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SDOC_RESERV_SDOC]'))
ALTER TABLE [dbo].[SDOC_RESERV] 
ADD CONSTRAINT [FK_SDOC_RESERV_SDOC] FOREIGN KEY ([LINK_UP]) REFERENCES [dbo].[SDOC] ([LINK])
 ON DELETE CASCADE
GO

--Триггеры

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

GO
/*
© Кейсистемс (Keysystems), 2005
*/
CREATE TRIGGER [dbo].[SDOC_RESERV_KIRDELETE] ON dbo.SDOC_RESERV 
FOR DELETE 
AS
	IF EXISTS(SELECT * FROM DELETED DEL, SDOC SD WHERE SD.LINK = DEL.LINK_UP AND SD.FLAG_JC = 1) BEGIN
		RAISERROR('Невозможно удалить проведенный документ', 11, 1)
		ROLLBACK
	END

GO


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

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

CREATE TRIGGER [dbo].[SDOC_RESERV_KIRINSERT] ON dbo.SDOC_RESERV
FOR INSERT, UPDATE
AS
	IF EXISTS(
		SELECT * 
		FROM INSERTED INS, SDOC SD 
		WHERE SD.LINK = INS.LINK_UP AND SD.FLAG_JC = 1
	) BEGIN
		RAISERROR('Невозможно изменить проведенный документ', 11, 1)
		ROLLBACK
	END

GO


GO
--Таблица SDOC_RESERV_TABLE
IF not exists(select * from sysobjects where id = object_id('[dbo].[SDOC_RESERV_TABLE]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[SDOC_RESERV_TABLE] (
	[LINK_UP] int NOT NULL ,
	[ORDERS] int NOT NULL ,
	[LINK_EMPL] int NOT NULL ,
	[SUMMA_BASE] numeric(20, 2) NOT NULL ,
	[AMOUNT_DED] numeric(20, 2) NOT NULL ,
	[SUMMA_DED] numeric(20, 2) NOT NULL ,
	[AMOUNT_TR] numeric(20, 2) NOT NULL ,
	[SUMMA_TR] numeric(20, 2) NOT NULL ,
	[OST_VAC_D] numeric(10, 2) NOT NULL ,
	[SUMMA_RESERV] numeric(20, 2) NOT NULL )
GO

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

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

IF  NOT EXISTS (SELECT * FROM dbo.sysindexes WHERE [name] = 'IX_SDOC_RESERV_TABLE')
CREATE INDEX [IX_SDOC_RESERV_TABLE] ON [dbo].[SDOC_RESERV_TABLE] ([LINK_UP], [LINK_EMPL], [ORDERS]) ON [INDEX]
GO

--Констрэйнты

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SDOC_RESERV_TABLE_SDOC]'))
ALTER TABLE [dbo].[SDOC_RESERV_TABLE] 
ADD CONSTRAINT [FK_SDOC_RESERV_TABLE_SDOC] FOREIGN KEY ([LINK_UP]) REFERENCES [dbo].[SDOC] ([LINK])
 ON DELETE CASCADE
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[FK_SDOC_RESERV_TABLE_EMPL]'))
ALTER TABLE [dbo].[SDOC_RESERV_TABLE] 
ADD CONSTRAINT [FK_SDOC_RESERV_TABLE_EMPL] FOREIGN KEY ([LINK_EMPL]) REFERENCES [dbo].[EMPL] ([LINK])
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[DF_SDOC_RESERV_TABLE_SUMMA_BASE]'))
ALTER TABLE [dbo].[SDOC_RESERV_TABLE] 
ADD CONSTRAINT [DF_SDOC_RESERV_TABLE_SUMMA_BASE] DEFAULT (0) FOR [SUMMA_BASE]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[DF_SDOC_RESERV_TABLE_AMOUNT_DED]'))
ALTER TABLE [dbo].[SDOC_RESERV_TABLE] 
ADD CONSTRAINT [DF_SDOC_RESERV_TABLE_AMOUNT_DED] DEFAULT (0) FOR [AMOUNT_DED]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[DF_SDOC_RESERV_TABLE_SUMMA_DED]'))
ALTER TABLE [dbo].[SDOC_RESERV_TABLE] 
ADD CONSTRAINT [DF_SDOC_RESERV_TABLE_SUMMA_DED] DEFAULT (0) FOR [SUMMA_DED]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[DF_SDOC_RESERV_TABLE_AMOUNT_TR]'))
ALTER TABLE [dbo].[SDOC_RESERV_TABLE] 
ADD CONSTRAINT [DF_SDOC_RESERV_TABLE_AMOUNT_TR] DEFAULT (0) FOR [AMOUNT_TR]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[DF_SDOC_RESERV_TABLE_SUMMA_TR]'))
ALTER TABLE [dbo].[SDOC_RESERV_TABLE] 
ADD CONSTRAINT [DF_SDOC_RESERV_TABLE_SUMMA_TR] DEFAULT (0) FOR [SUMMA_TR]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[DF_SDOC_RESERV_TABLE_OST_VAC_D]'))
ALTER TABLE [dbo].[SDOC_RESERV_TABLE]
ADD CONSTRAINT [DF_SDOC_RESERV_TABLE_OST_VAC_D] DEFAULT (0) FOR [OST_VAC_D]
GO

IF  NOT EXISTS (SELECT * FROM dbo.sysconstraints WHERE constid =  object_id('dbo.[DF_SDOC_RESERV_TABLE_SUMMA_RESERV]'))
ALTER TABLE [dbo].[SDOC_RESERV_TABLE]
ADD CONSTRAINT [DF_SDOC_RESERV_TABLE_SUMMA_RESERV] DEFAULT (0) FOR [SUMMA_RESERV]
GO
--Триггеры

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

GO



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

CREATE TRIGGER [dbo].[SDOC_RESERV_TABLE_KIRDELETE] ON [dbo].[SDOC_RESERV_TABLE]
FOR DELETE
AS
	IF EXISTS(
		SELECT * 
		FROM DELETED DEL, SDOC SD 
		WHERE SD.LINK = DEL.LINK_UP AND SD.FLAG_JC = 1
	) BEGIN
		RAISERROR('Невозможно удалить проведенный документ', 11, 1)
		ROLLBACK
	END



GO


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

GO



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

CREATE TRIGGER [dbo].[SDOC_RESERV_TABLE_KIRINSERT] ON [dbo].[SDOC_RESERV_TABLE]
FOR INSERT, UPDATE
AS
	IF EXISTS(
		SELECT * 
		FROM INSERTED INS, SDOC SD 
		WHERE SD.LINK = INS.LINK_UP AND SD.FLAG_JC = 1
	) BEGIN
		RAISERROR('Невозможно изменить проведенный документ', 11, 1)
		ROLLBACK
	END



GO



GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_M15', 'Накладная по НФА', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOC_MAT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_M15', NAME = 'Накладная по НФА', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOC_MAT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DOCUMENTS_M15'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_PRINT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_PRINT', 'Печатная форма документа', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_PRINT', NAME = 'Печатная форма документа', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_PRINT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_TAX')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_TAX', 'НДС', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_TAX', NAME = 'НДС', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_TAX'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_DEP_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_DEP_LINK', 'Ссылка на организацию', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_DEP_LINK', NAME = 'Ссылка на организацию', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_DEP_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_DEP_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_DEP_CODE', 'Код организации', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_DEP_CODE', NAME = 'Код организации', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_DEP_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_DEP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_DEP_NAME', 'Наименование организации', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_DEP_NAME', NAME = 'Наименование организации', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_DEP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_MIDDLEMAN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_MIDDLEMAN', 'Через кого', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_MIDDLEMAN', NAME = 'Через кого', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_MIDDLEMAN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_REQUEST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_REQUEST', 'Затребовал(сотрудник)', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_REQUEST', NAME = 'Затребовал(сотрудник)', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_REQUEST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_REQUEST_POST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_REQUEST_POST', 'Затребовал(должность)', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_REQUEST_POST', NAME = 'Затребовал(должность)', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_REQUEST_POST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_ALLOW')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_ALLOW', 'Разрешил', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_ALLOW', NAME = 'Разрешил', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_ALLOW'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_ALLOW_POST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_ALLOW_POST', 'Разрешил(должность)', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_ALLOW_POST', NAME = 'Разрешил(должность)', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_ALLOW_POST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_BASE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_BASE', 'Основание для составления акта', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_BASE', NAME = 'Основание для составления акта', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_BASE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_COMMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_COMMENT', 'Примечание', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_COMMENT', NAME = 'Примечание', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_COMMENT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_K_DEP_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_K_DEP_LINK', 'Кому ссылка', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_K_DEP_LINK', NAME = 'Кому ссылка', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_K_DEP_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_K_DEP_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_K_DEP_CODE', 'Кому код', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_K_DEP_CODE', NAME = 'Кому код', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_K_DEP_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_K_DEP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_K_DEP_NAME', 'Кому наименование', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_K_DEP_NAME', NAME = 'Кому наименование', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_K_DEP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_K_DEP_FNAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_K_DEP_FNAME', 'Кому наименование', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_K_DEP_FNAME', NAME = 'Кому наименование', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_K_DEP_FNAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_MOVE_REST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_MOVE_REST', 'Внутреннее перемещение', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_MOVE_REST', NAME = 'Внутреннее перемещение', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_MOVE_REST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INVENT_TABLE', 'Таблица материальных ценностей', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INVENT_TABLE', NAME = 'Таблица материальных ценностей', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DOC_M15_INVENT_TABLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_OPTIONS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_OPTIONS', 'Настройки накладной', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_OPTIONS', NAME = 'Настройки накладной', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_OPTIONS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_OPT_TYP_LINK_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_OPT_TYP_LINK_1', 'Ссылка на операцию', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_OPT_TYP_LINK_1', NAME = 'Ссылка на операцию', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_OPT_TYP_LINK_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_OPT_TYP_NAME_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_OPT_TYP_NAME_1', 'Наим тип. опер.', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_OPT_TYP_NAME_1', NAME = 'Наим тип. опер.', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_OPT_TYP_NAME_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_OPT_TYP_LINK_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_OPT_TYP_LINK_2', 'Ссылка на операцию', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_OPT_TYP_LINK_2', NAME = 'Ссылка на операцию', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_OPT_TYP_LINK_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_OPT_TYP_NAME_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_OPT_TYP_NAME_2', 'Наим тип. опер.', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_OPT_TYP_NAME_2', NAME = 'Наим тип. опер.', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_OPT_TYP_NAME_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_OPT_TYP_LINK_3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_OPT_TYP_LINK_3', 'Ссылка на операцию', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_OPT_TYP_LINK_3', NAME = 'Ссылка на операцию', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_OPT_TYP_LINK_3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_OPT_TYP_NAME_3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_OPT_TYP_NAME_3', 'Наим тип. опер.', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_OPT_TYP_NAME_3', NAME = 'Наим тип. опер.', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_OPT_TYP_NAME_3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_TYPE_INV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_TYPE_INV', 'Тип МЗ', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_TYPE_INV', NAME = 'Тип МЗ', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_TYPE_INV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_INV_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_INV_LINK', 'Ссылка на ОС', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_INV_LINK', NAME = 'Ссылка на ОС', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_INV_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_INV_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_INV_CODE', 'Код ОС', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_INV_CODE', NAME = 'Код ОС', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_INV_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_INV_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_INV_NAME', 'Наименование ОС', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_INV_NAME', NAME = 'Наименование ОС', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_INV_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_GRP_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_GRP_CODE', 'Группа нефинансовых активов', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_GRP_CODE', NAME = 'Группа нефинансовых активов', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_GRP_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_LINK_SOU')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_LINK_SOU', 'Ссылка на источник финансирования', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_LINK_SOU', NAME = 'Ссылка на источник финансирования', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_LINK_SOU'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_CODE_SOU')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_CODE_SOU', 'Код источника финансирования', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_CODE_SOU', NAME = 'Код источника финансирования', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_CODE_SOU'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_NAME_SOU')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_NAME_SOU', 'Наименование источника финансирования', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_NAME_SOU', NAME = 'Наименование источника финансирования', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_NAME_SOU'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_QTY_REQUEST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_QTY_REQUEST', 'Количество затребовано', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_QTY_REQUEST', NAME = 'Количество затребовано', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_QTY_REQUEST'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_QTY_GIVEN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_QTY_GIVEN', 'Количество отпущено', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_QTY_GIVEN', NAME = 'Количество отпущено', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_QTY_GIVEN'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_INV_PRICE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_INV_PRICE', 'Цена без НДС', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_INV_PRICE', NAME = 'Цена без НДС', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_INV_PRICE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_INV_TAX_PRICE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_INV_TAX_PRICE', 'Цена с НДС', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_INV_TAX_PRICE', NAME = 'Цена с НДС', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_INV_TAX_PRICE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_SUMMA_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_SUMMA_1', 'Сумма без учета НДС', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_SUMMA_1', NAME = 'Сумма без учета НДС', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_SUMMA_1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_TAX_SUM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_TAX_SUM', 'Сумма НДС', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_TAX_SUM', NAME = 'Сумма НДС', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_TAX_SUM'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_SUMMA_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_SUMMA_2', 'Всего с учетом НДС', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_SUMMA_2', NAME = 'Всего с учетом НДС', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_SUMMA_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_ACC_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_ACC_CODE', 'Счет материала', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_ACC_CODE', NAME = 'Счет материала', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_ACC_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_INV_TAB_NOTICE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_INV_TAB_NOTICE', 'Примечание', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_INV_TAB_NOTICE', NAME = 'Примечание', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_M15_INVENT_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_INV_TAB_NOTICE'
GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'TITLE', 'Накладная по НФА'
GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS (m.cAlias,"DOCUMENTS_M15", "BV_DELETE_DOCUMENTS", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_DOCUMENTS_M15'', m.cAlias,"NUMBER, SQLNULL(DATE), SQLNULL(DATE_PROV), SUMMA, COMMENT, SQLNULL (DEP_LINK), SQLNULL (ACC_LINK), TYPE_PRINT, TAX, MIDDLEMAN, REQUEST,REQ_POST, ALLOW, ALLOW_POST, BASE, SQLNULL(K_DEP_LINK), MOVE_REST","DOCUMENTS_M15")'
GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'PRINT_OBJECT_METHOD', 'KM_PRINT_F0315006_M11()'
GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''bv_doc_m15'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_LIST_ZB("DOCUMENTS_M15")'
GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST("DOCUMENTS_M15")'
GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'SNAME', 'Накладная по НФА'
GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'QUERY_REPMAKER', 'KirRepMaker.xls#KirRepMaker.xls'
GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'QUERY_REPORT', 'F0504204_M11.XLT#F0504205_M15.XLT'
GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'OPTIONS_OBJECT_CODE', 'DOC_M15_OPTIONS'
GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'HELP_TOPIC', '23'
GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'QUERY_ADD_MODULE', 'KirRepCommon.bas#KirRepCommon.bas'
GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'CREATE_PROV_SQL', 'BV_SAVE_G_PROV1_M15_OS'
GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'REPORT_EXTERNAL_GENERATOR', '1'
GO
EXEC X_SET_PROP 'DOC_M15_PRINT', 'TITLE', 'Печатная форма'
GO
EXEC X_SET_PROP 'DOC_M15_PRINT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_M15_PRINT', 'CONTROLSOURCE', 'm.cAlias+".TYPE_PRINT"'
GO
EXEC X_SET_PROP 'DOC_M15_PRINT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_PRINT', 'ROWSOURCE', '"M-11,M-15"'
GO
EXEC X_SET_PROP 'DOC_M15_PRINT', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_M15_PRINT', 'TYPE_FIELD_DICT', 'char(10)'
GO
EXEC X_SET_PROP 'DOC_M15_PRINT', 'SHORT_CODE_OBJ', 'TYPE_PRINT'
GO
EXEC X_SET_PROP 'DOC_M15_PRINT', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TYPE_PRINT"'
GO
EXEC X_SET_PROP 'DOC_M15_PRINT', 'CONTROL_NAME_EDIT', 'Acombobox1'
GO
EXEC X_SET_PROP 'DOC_M15_TAX', 'TITLE', 'НДС (%)'
GO
EXEC X_SET_PROP 'DOC_M15_TAX', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_M15_TAX', 'CONTROLSOURCE', 'm.cAlias + ".TAX"'
GO
EXEC X_SET_PROP 'DOC_M15_TAX', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_TAX', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_M15_TAX', 'TYPE_FIELD_DICT', 'NUMERIC(4,2)'
GO
EXEC X_SET_PROP 'DOC_M15_TAX', 'SHORT_CODE_OBJ', 'TAX'
GO
EXEC X_SET_PROP 'DOC_M15_TAX', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TAX"'
GO
EXEC X_SET_PROP 'DOC_M15_TAX', 'CONTROL_NAME_EDIT', 'ATxt2'
GO
EXEC X_SET_PROP 'DOC_M15_TAX', 'INPUT_MASK', '99.99'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_LINK', 'TITLE', 'Собственная организация'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_LINK', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_LINK', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_LINK', 'SHORT_CODE_OBJ', 'DEP_LINK'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_CODE', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_CODE', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME", "DEP_LINK, DEP_CODE, DEP_NAME", "", "", "", .T., 1, oForm, oObj,"",.T.,"DEPARTMENT_GROUPS")'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_CODE', 'CONTROLSOURCE', 'm.cAlias+".DEP_CODE"'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_CODE', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_CODE', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_CODE', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_CODE', 'REFERENCE_TO_DICT', 'DOC_M15_DEP_LINK'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_CODE', 'TYPE_FIELD_DICT', 'CHAR(10)'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_CODE', 'SHORT_CODE_OBJ', 'DEP_CODE'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DEP_CODE"'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_CODE', 'WHEN_FUNC', 'V_GET_OWN_DEP_LCN(oform.alias, ''DEP_LINK'', ''DEP_CODE'', ''DEP_NAME'')'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_NAME', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_NAME', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_NAME', 'CONTROLSOURCE', 'm.cAlias+".DEP_NAME"'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_NAME', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_NAME', 'REFERENCE_TO_DICT', 'DOC_M15_DEP_LINK'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_NAME', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_NAME', 'SHORT_CODE_OBJ', 'DEP_NAME'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DEP_NAME"'
GO
EXEC X_SET_PROP 'DOC_M15_DEP_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DOC_M15_MIDDLEMAN', 'TITLE', 'Через кого'
GO
EXEC X_SET_PROP 'DOC_M15_MIDDLEMAN', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''KU_EMPL_PLACING'', oForm.ALIAS, ''NAME_EMPL'', ''MIDDLEMAN'', "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_M15_MIDDLEMAN', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_M15_MIDDLEMAN', 'CONTROLSOURCE', 'm.cAlias + ".MIDDLEMAN"'
GO
EXEC X_SET_PROP 'DOC_M15_MIDDLEMAN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_MIDDLEMAN', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_M15_MIDDLEMAN', 'TYPE_FIELD_DICT', 'VARCHAR (60)'
GO
EXEC X_SET_PROP 'DOC_M15_MIDDLEMAN', 'SHORT_CODE_OBJ', 'MIDDLEMAN'
GO
EXEC X_SET_PROP 'DOC_M15_MIDDLEMAN', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".MIDDLEMAN"'
GO
EXEC X_SET_PROP 'DOC_M15_MIDDLEMAN', 'CONTROL_NAME_EDIT', 'parent.Page3.Asel_spr2'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST', 'TITLE', 'Затребовал'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''KU_EMPL_PLACING'', oForm.ALIAS, ''NAME_EMPL, POST_NAME'', ''REQUEST,REQ_POST'', "", "", "", .T., 1, oForm, oObj)
'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST', 'CONTROLSOURCE', 'm.cAlias + ".REQUEST"'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST', 'TYPE_FIELD_DICT', 'VARCHAR (60)'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST', 'SHORT_CODE_OBJ', 'REQUEST'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".REQUEST"'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST', 'CONTROL_NAME_EDIT', 'parent.Page3.Asel_spr3'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST_POST', 'TITLE', 'Затребовал(Должность)'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST_POST', 'CONTROLSOURCE', 'm.cAlias + ".REQ_POST"'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST_POST', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST_POST', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST_POST', 'TYPE_FIELD_DICT', 'VARCHAR (100)'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST_POST', 'SHORT_CODE_OBJ', 'REQ_POST'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST_POST', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".REQ_POST"'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW', 'TITLE', 'Разрешил'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''KU_EMPL_PLACING'', oForm.ALIAS, ''NAME_EMPL, POST_NAME'', ''ALLOW, ALLOW_POST'', "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW', 'CONTROLSOURCE', 'm.cAlias + ".ALLOW"'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW', 'TYPE_FIELD_DICT', 'VARCHAR (60)'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW', 'SHORT_CODE_OBJ', 'ALLOW'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ALLOW"'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW', 'CONTROL_NAME_EDIT', 'parent.Page3.Asel_spr4'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW_POST', 'TITLE', 'Разрешил(должность)'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW_POST', 'CONTROLSOURCE', 'm.cAlias + ".ALLOW_POST"'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW_POST', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW_POST', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW_POST', 'TYPE_FIELD_DICT', 'VARCHAR (100)'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW_POST', 'SHORT_CODE_OBJ', 'ALLOW_POST'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW_POST', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ALLOW_POST"'
GO
EXEC X_SET_PROP 'DOC_M15_BASE', 'TITLE', 'Основание'
GO
EXEC X_SET_PROP 'DOC_M15_BASE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_M15_BASE', 'CONTROLSOURCE', 'm.cAlias + ".BASE"'
GO
EXEC X_SET_PROP 'DOC_M15_BASE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_BASE', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_M15_BASE', 'TYPE_FIELD_DICT', 'VARCHAR (120)'
GO
EXEC X_SET_PROP 'DOC_M15_BASE', 'SHORT_CODE_OBJ', 'BASE'
GO
EXEC X_SET_PROP 'DOC_M15_BASE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".BASE"'
GO
EXEC X_SET_PROP 'DOC_M15_BASE', 'CONTROL_NAME_EDIT', 'parent.Page3.ATxt5'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT', 'TITLE', 'Примечание'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT', 'CONTROLSOURCE', 'm.cAlias + ".COMMENT"'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT', 'TYPE_FIELD_DICT', 'VARCHAR(500)'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT', 'SHORT_CODE_OBJ', 'COMMENT'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COMMENT"'
GO
EXEC X_SET_PROP 'DOC_M15_COMMENT', 'CONTROL_NAME_EDIT', 'Aebox3'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_LINK', 'TITLE', 'Кому ссылка'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_LINK', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_LINK', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_LINK', 'SHORT_CODE_OBJ', 'K_DEP_LINK'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_CODE', 'TITLE', 'Кому'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_CODE', 'EDIT_OBJECT_METHOD', 'XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS, "LINK,CODE,NAME,FULL_NAME", "K_DEP_LINK, K_DEP_CODE, K_DEP_NAME, K_DEP_FNAME", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS")'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_CODE', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_CODE', 'CONTROLSOURCE', 'm.cAlias + ".K_DEP_CODE"'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_CODE', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_CODE', 'REFERENCE_TO_DICT', 'DOC_M15_K_DEP_LINK'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_CODE', 'TYPE_FIELD_DICT', 'VARCHAR (10)'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_CODE', 'SHORT_CODE_OBJ', 'K_DEP_CODE'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".K_DEP_CODE"'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_CODE', 'CONTROL_NAME_EDIT', 'parent.Page3.Asel_spr6'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_NAME', 'TITLE', 'Кому'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_NAME', 'CONTROLSOURCE', 'm.cAlias + ".K_DEP_NAME"'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_NAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_NAME', 'REFERENCE_TO_DICT', 'DOC_M15_K_DEP_LINK'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_NAME', 'TYPE_FIELD_DICT', 'VARCHAR (60)'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_NAME', 'SHORT_CODE_OBJ', 'K_DEP_NAME'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".K_DEP_NAME"'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_NAME', 'CONTROL_NAME_EDIT', 'parent.Page3.aTxt6'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_FNAME', 'TITLE', 'Кому'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_FNAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_FNAME', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_FNAME', 'REFERENCE_TO_DICT', 'DOC_M15_K_DEP_LINK'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_FNAME', 'TYPE_FIELD_DICT', 'VARCHAR (254)'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_FNAME', 'SHORT_CODE_OBJ', 'K_DEP_FNAME'
GO
EXEC X_SET_PROP 'DOC_M15_K_DEP_FNAME', 'REFERENCE_TO_FIELD', 'FULL_NAME'
GO
EXEC X_SET_PROP 'DOC_M15_MOVE_REST', 'TITLE', 'Внутреннее перемещение'
GO
EXEC X_SET_PROP 'DOC_M15_MOVE_REST', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_M15_MOVE_REST', 'CONTROLSOURCE', 'm.cAlias + ".MOVE_REST"'
GO
EXEC X_SET_PROP 'DOC_M15_MOVE_REST', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_MOVE_REST', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_M15_MOVE_REST', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'DOC_M15_MOVE_REST', 'SHORT_CODE_OBJ', 'MOVE_REST'
GO
EXEC X_SET_PROP 'DOC_M15_MOVE_REST', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".MOVE_REST"'
GO
EXEC X_SET_PROP 'DOC_M15_INVENT_TABLE', 'TITLE', 'Таблица материальных ценностей'
GO
EXEC X_SET_PROP 'DOC_M15_INVENT_TABLE', 'SAVE_OBJECT_METHOD', 'X_SAVE(''BV_SAVE_DOC_M15_INVENT_TABLE'', m.cAlias,''SQLNULL(LINK_UP), ORDERS, TYPE_INV, INV_LINK, GRP_CODE, SQLNULL(SOU_LINK), QTY_REQUEST, QTY_GIVEN, PRICE, TAX_PRICE, SUMMA_1, TAX_SUM, SUMMA_2, ACC_CODE, NOTICE'',"DOC_M15_INVENT_TABLE")'
GO
EXEC X_SET_PROP 'DOC_M15_INVENT_TABLE', 'SELECT_RECORDS_METHOD', 'x_select_doc_table_list(''BV_DOC_M15_INVENT_TABLE'')'
GO
EXEC X_SET_PROP 'DOC_M15_INVENT_TABLE', 'SELECT_RECORDS_METHOD_EDIT', 'x_select_doc_table_list(''BV_DOC_M15_INVENT_TABLE'')'
GO
EXEC X_SET_PROP 'DOC_M15_INVENT_TABLE', 'SERVER_TABLE_NAME', 'OUT_TABLE_ROW'
GO
EXEC X_SET_PROP 'DOC_M15_OPTIONS', 'TITLE', 'Настройки накладной'
GO
EXEC X_SET_PROP 'DOC_M15_OPTIONS', 'SAVE_OBJECT_METHOD', 'X_SAVE_DOCUMENT_OPTIONS()'
GO
EXEC X_SET_PROP 'DOC_M15_OPTIONS', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''BV_DOC_M15_OPTIONS'')'
GO
EXEC X_SET_PROP 'DOC_M15_OPTIONS', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_OPTIONS(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'DOC_M15_OPTIONS', 'OPTIONS_OBJECT_CODE', 'DOC_M15_OPTIONS'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_LINK_1', 'TITLE', 'Ссылка на операцию'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_LINK_1', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_LINK_1', 'SHORT_CODE_OBJ', 'TYP_LINK_1'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_LINK_1', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_1', 'TITLE', 'Типовая операция (Номенклатура)'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_1', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TYP_LINK_1", "TYP_NAME_1", "DOCUMENTS_M15")'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_1', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_1', 'REFERENCE_TO_DICT', 'DOC_M15_OPT_TYP_LINK_1'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_1', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_1', 'SHORT_CODE_OBJ', 'TYP_NAME_1'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_1', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TYP_NAME_1"'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_1', 'CONTROL_NAME_EDIT', 'Asel_spr1'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_1', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_LINK_2', 'TITLE', 'Ссылка на операцию'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_LINK_2', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_LINK_2', 'SHORT_CODE_OBJ', 'TYP_LINK_2'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_LINK_2', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_2', 'TITLE', 'Типовая операция (Инвентарь)'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_2', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TYP_LINK_2", "TYP_NAME_2", "DOCUMENTS_M15")'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_2', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_2', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_2', 'REFERENCE_TO_DICT', 'DOC_M15_OPT_TYP_LINK_2'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_2', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_2', 'SHORT_CODE_OBJ', 'TYP_NAME_2'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_2', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TYP_NAME_2"'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_2', 'CONTROL_NAME_EDIT', 'Asel_spr2'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_2', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_LINK_3', 'TITLE', 'Ссылка на операцию'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_LINK_3', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_LINK_3', 'SHORT_CODE_OBJ', 'TYP_LINK_3'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_LINK_3', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_3', 'TITLE', 'Типовая операция (ТМЦ)'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_3', 'EDIT_OBJECT_METHOD', 'X_VIBOR_OPER(m.oForm, m.oObj, "TYP_LINK_3", "TYP_NAME_3", "DOCUMENTS_M15")'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_3', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_3', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_3', 'STORAGE', 'G_PROV1'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_3', 'REFERENCE_TO_DICT', 'DOC_M15_OPT_TYP_LINK_3'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_3', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_3', 'SHORT_CODE_OBJ', 'TYP_NAME_3'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_3', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TYP_NAME_3"'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_3', 'CONTROL_NAME_EDIT', 'Asel_spr3'
GO
EXEC X_SET_PROP 'DOC_M15_OPT_TYP_NAME_3', 'REFERENCE_TO_FIELD', 'NAME_OPER'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_MARKER', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_MARKER', 'CONTROLSOURCE', 'm.cAlias+''.CHECKED'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_MARKER', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_TYPE_INV', 'TITLE', 'Тип МЗ'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_TYPE_INV', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_TYPE_INV', 'CONTROLSOURCE', 'm.cAlias+''.TYPE_INV'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_TYPE_INV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_TYPE_INV', 'ROWSOURCE', 'Номенклатура,Инвентарь,Товарно-материальные ценности'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_TYPE_INV', 'STORAGE', 'STRING'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_TYPE_INV', 'REFERENCE_TO_DICT', 'BV_NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_TYPE_INV', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_TYPE_INV', 'SHORT_CODE_OBJ', 'TYPE_INV'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_TYPE_INV', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_LINK', 'TITLE', 'Материал'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_LINK', 'CONTROLSOURCE', 'm.cAlias+''.INV_LINK'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_LINK', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_LINK', 'REFERENCE_TO_DICT', 'BV_NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_LINK', 'SHORT_CODE_OBJ', 'INV_LINK'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_CODE', 'TITLE', 'Материал'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_CODE', 'EDIT_OBJECT_METHOD', 'bv_document_invoice_grid_valid_inventory()'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_CODE', 'CONTROLSOURCE', 'm.cAlias+''.INV_CODE'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_CODE', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_CODE', 'REFERENCE_TO_DICT', 'DOC_M15_INV_TAB_INV_LINK'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_CODE', 'TYPE_FIELD_DICT', 'CHAR(12)'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_CODE', 'SHORT_CODE_OBJ', 'INV_CODE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.INV_CODE'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_NAME', 'TITLE', 'Материал'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_NAME', 'CONTROLSOURCE', 'm.cAlias+''.INV_NAME'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_NAME', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_NAME', 'REFERENCE_TO_DICT', 'DOC_M15_INV_TAB_INV_LINK'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(80)'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_NAME', 'SHORT_CODE_OBJ', 'INV_NAME'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_GRP_CODE', 'TITLE', 'Группа'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_GRP_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_GRP_CODE', 'CONTROLSOURCE', 'm.cAlias+''.GRP_CODE'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_GRP_CODE', 'STORAGE', 'STRING'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_GRP_CODE', 'TYPE_FIELD_DICT', 'CHAR(5)'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_GRP_CODE', 'SHORT_CODE_OBJ', 'GRP_CODE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_LINK_SOU', 'TITLE', 'ИФ'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_LINK_SOU', 'CONTROLSOURCE', 'm.cAlias+''.SOU_LINK'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_LINK_SOU', 'STORAGE', 'FIN_SOURCE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_LINK_SOU', 'REFERENCE_TO_DICT', 'DICTIONARY_FIN_SOURCE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_LINK_SOU', 'SHORT_CODE_OBJ', 'SOU_LINK'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_LINK_SOU', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_CODE_SOU', 'TITLE', 'ИФ'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_CODE_SOU', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_FIN_SOURCE", oForm.Pages.Page4.Bchildspisok1.Bgrid1.RecordSource, "LINK,CODE,NAME", "SOU_LINK, SOU_CODE, SOU_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_CODE_SOU', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_CODE_SOU', 'CONTROLSOURCE', 'm.cAlias+".SOU_CODE"'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_CODE_SOU', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_CODE_SOU', 'STORAGE', 'FIN_SOURCE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_CODE_SOU', 'REFERENCE_TO_DICT', 'DOC_M15_INV_TAB_LINK_SOU'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_CODE_SOU', 'TYPE_FIELD_DICT', 'CHAR(1)'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_CODE_SOU', 'SHORT_CODE_OBJ', 'SOU_CODE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_CODE_SOU', 'CONTROLSOURCE_EDIT', 'm.cAlias+".SOU_CODE"'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_CODE_SOU', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_NAME_SOU', 'TITLE', 'ИФ'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_NAME_SOU', 'CONTROLSOURCE', 'm.cAlias+".SOU_NAME"'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_NAME_SOU', 'STORAGE', 'FIN_SOURCE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_NAME_SOU', 'REFERENCE_TO_DICT', 'DOC_M15_INV_TAB_LINK_SOU'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_NAME_SOU', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_NAME_SOU', 'SHORT_CODE_OBJ', 'SOU_NAME'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_NAME_SOU', 'CONTROLSOURCE_EDIT', 'm.cAlias+".SOU_NAME"'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_NAME_SOU', 'REFERENCE_TO_FIELD', 'SHORT_NAME'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_QTY_REQUEST', 'TITLE', 'Количество затребовано'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_QTY_REQUEST', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_QTY_REQUEST', 'CONTROLSOURCE', 'm.cAlias+''.QTY_REQUEST'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_QTY_REQUEST', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_QTY_REQUEST', 'STORAGE', 'SUMMA'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_QTY_REQUEST', 'TYPE_FIELD_DICT', 'NUMERIC(12,4)'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_QTY_REQUEST', 'SHORT_CODE_OBJ', 'QTY_REQUEST'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_QTY_GIVEN', 'TITLE', 'Количество отпущено'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_QTY_GIVEN', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_QTY_GIVEN', 'CONTROLSOURCE', 'm.cAlias+''.QTY_GIVEN'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_QTY_GIVEN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_QTY_GIVEN', 'STORAGE', 'SUMMA'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_QTY_GIVEN', 'TYPE_FIELD_DICT', 'NUMERIC(12,4)'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_QTY_GIVEN', 'SHORT_CODE_OBJ', 'QTY_GIVEN'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_PRICE', 'TITLE', 'Цена без НДС'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_PRICE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_PRICE', 'CONTROLSOURCE', 'm.cAlias+''.PRICE'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_PRICE', 'STORAGE', 'SUMMA'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_PRICE', 'TYPE_FIELD_DICT', 'NUMERIC(12,2)'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_PRICE', 'SHORT_CODE_OBJ', 'PRICE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_TAX_PRICE', 'TITLE', 'Цена с НДС'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_TAX_PRICE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_TAX_PRICE', 'CONTROLSOURCE', 'm.cAlias+''.TAX_PRICE'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_TAX_PRICE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_TAX_PRICE', 'STORAGE', 'SUMMA'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_TAX_PRICE', 'TYPE_FIELD_DICT', 'NUMERIC(12,2)'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_INV_TAX_PRICE', 'SHORT_CODE_OBJ', 'TAX_PRICE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_SUMMA_1', 'TITLE', 'Сумма без НДС'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_SUMMA_1', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_SUMMA_1', 'CONTROLSOURCE', 'm.cAlias+''.SUMMA_1'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_SUMMA_1', 'STORAGE', 'SUMMA'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_SUMMA_1', 'TYPE_FIELD_DICT', 'NUMERIC(12,2)'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_SUMMA_1', 'SHORT_CODE_OBJ', 'SUMMA_1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_TAX_SUM', 'TITLE', 'Сумма НДС'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_TAX_SUM', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_TAX_SUM', 'CONTROLSOURCE', 'm.cAlias+''.TAX_SUM'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_TAX_SUM', 'STORAGE', 'SUMMA'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_TAX_SUM', 'TYPE_FIELD_DICT', 'NUMERIC(12,2)'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_TAX_SUM', 'SHORT_CODE_OBJ', 'TAX_SUM'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_SUMMA_2', 'TITLE', 'Всего с НДС'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_SUMMA_2', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_SUMMA_2', 'CONTROLSOURCE', 'm.cAlias+''.SUMMA_2'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_SUMMA_2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_SUMMA_2', 'STORAGE', 'SUMMA'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_SUMMA_2', 'TYPE_FIELD_DICT', 'NUMERIC(12,2)'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_SUMMA_2', 'SHORT_CODE_OBJ', 'SUMMA_2'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_ACC_CODE', 'TITLE', 'Счет материала'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_ACC_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_ACC_CODE', 'CONTROLSOURCE', 'm.cAlias+''.ACC_CODE'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_ACC_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_ACC_CODE', 'STORAGE', 'STRING'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_ACC_CODE', 'TYPE_FIELD_DICT', 'VARCHAR(13)'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_ACC_CODE', 'SHORT_CODE_OBJ', 'ACC_CODE'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_NOTICE', 'TITLE', 'Примечание'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_NOTICE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_NOTICE', 'CONTROLSOURCE', 'm.cAlias+''.NOTICE'''
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_NOTICE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_NOTICE', 'STORAGE', 'STRING'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_NOTICE', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_M15_INV_TAB_NOTICE', 'SHORT_CODE_OBJ', 'NOTICE'
GO




GO
-- Акт о возврате ТМЦ, сданных на хранение --
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3', 'Акт о возврате ТМЦ, сданных на хранение', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOC_MAT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3', NAME = 'Акт о возврате ТМЦ, сданных на хранение', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DOC_MAT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DOC_MX3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_DEP_LINK1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_DEP_LINK1', 'Ссылка на поклажедателя', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_DEP_LINK1', NAME = 'Ссылка на поклажедателя', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_DEP_LINK1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_DEP_CODE1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_DEP_CODE1', 'Код поклажедателя', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_DEP_CODE1', NAME = 'Код поклажедателя', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_DEP_CODE1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_DEP_NAME1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_DEP_NAME1', 'Наименование поклажедателя', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_DEP_NAME1', NAME = 'Наименование поклажедателя', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_DEP_NAME1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_DEP_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_DEP_NAME', 'Наименование организации', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_DEP_NAME', NAME = 'Наименование организации', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_DEP_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_OSNOV_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_OSNOV_LINK', 'Ссылка на основание', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_OSNOV_LINK', NAME = 'Ссылка на основание', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_OSNOV_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_OSNOV_NUMBER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_OSNOV_NUMBER', 'Номер документа основания', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_OSNOV_NUMBER', NAME = 'Номер документа основания', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_OSNOV_NUMBER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_OSNOV_INF')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_OSNOV_INF', 'Вид документа основания', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_OSNOV_INF', NAME = 'Вид документа основания', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_OSNOV_INF'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_NOTICE_OP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_NOTICE_OP', 'Вид операции', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_NOTICE_OP', NAME = 'Вид операции', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_NOTICE_OP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_COUNT_DAY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_COUNT_DAY', 'Количество дней хранения', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_COUNT_DAY', NAME = 'Количество дней хранения', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_COUNT_DAY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_COMMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_COMMENT', 'Примечание', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_COMMENT', NAME = 'Примечание', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_COMMENT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_INV_TABLE', 'Таблица материальных ценностей', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_INV_TABLE', NAME = 'Таблица материальных ценностей', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DOC_MX3_INV_TABLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_T_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_INV_T_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_INV_T_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_INV_T_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_T_INV_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_INV_T_INV_TYPE', 'Тип МЗ', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_INV_T_INV_TYPE', NAME = 'Тип МЗ', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_INV_T_INV_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_T_INV_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_INV_T_INV_LINK', 'Ссылка на МЦ', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_INV_T_INV_LINK', NAME = 'Ссылка на МЦ', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_INV_T_INV_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_T_INV_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_INV_T_INV_CODE', 'Код МЦ', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_INV_T_INV_CODE', NAME = 'Код МЦ', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_INV_T_INV_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_T_INV_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_INV_T_INV_NAME', 'Наименование МЦ', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_INV_T_INV_NAME', NAME = 'Наименование МЦ', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_INV_T_INV_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_T_INV_CHAR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_INV_T_INV_CHAR', 'Характеристика', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_INV_T_INV_CHAR', NAME = 'Характеристика', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_INV_T_INV_CHAR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_T_PRICE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_INV_T_PRICE', 'Цена', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_INV_T_PRICE', NAME = 'Цена', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_INV_T_PRICE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_T_QTY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_INV_T_QTY', 'Количество', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_INV_T_QTY', NAME = 'Количество', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_INV_T_QTY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_T_SUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_INV_T_SUMMA', 'Сумма', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_INV_T_SUMMA', NAME = 'Сумма', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_INV_T_SUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_T_COMMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_MX3_INV_T_COMMENT', 'Примечание', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_MX3_INV_T_COMMENT', NAME = 'Примечание', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_MX3_INV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_MX3_INV_T_COMMENT'
GO
EXEC X_SET_PROP 'DOC_MX3', 'TITLE', 'Акт о возврате ТМЦ, сданных на хранение'
GO
EXEC X_SET_PROP 'DOC_MX3', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS (m.cAlias,"DOC_MX3", "BV_DELETE_DOCUMENTS", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DOC_MX3', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_DOC_MX3'', m.cAlias,"NUMBER, SQLNULL(DATE), SQLNULL(DATE_PROV), SUMMA, COMMENT, SQLNULL (DEP_LINK), SQLNULL (ACC_LINK), SQLNULL(DEP_LINK1), SQLNULL(OSNOV), NOTICE_OP, COUNT_DAY","DOC_MX3")'
GO
EXEC X_SET_PROP 'DOC_MX3', 'PRINT_OBJECT_METHOD', 'BK_PRINT_WITH_SQL_PROC ("dbo.BK_PRINTDOC_AKT_MX3")'
GO
EXEC X_SET_PROP 'DOC_MX3', 'EDIT_OBJECT_METHOD', 'bdoc_brow(''BK_DOC_MX3'')'
GO
EXEC X_SET_PROP 'DOC_MX3', 'SELECT_RECORDS_METHOD', 'X_SELECT_DOCUMENT_LIST_ZB ("DOC_MX3")'
GO
EXEC X_SET_PROP 'DOC_MX3', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST("DOC_MX3")'
GO
EXEC X_SET_PROP 'DOC_MX3', 'SNAME', 'Акт о возврате ТМЦ, сданных на хранение'
GO
EXEC X_SET_PROP 'DOC_MX3', 'QUERY_REPMAKER', 'KirRepMakerMultiSheet.xls'
GO
EXEC X_SET_PROP 'DOC_MX3', 'QUERY_REPORT', 'AKT_MX3.XLT'
GO
EXEC X_SET_PROP 'DOC_MX3', 'QUERY_ADD_MODULE', 'AKT_MX3.BAS'
GO
EXEC X_SET_PROP 'DOC_MX3', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'DOC_MX3', 'REPORT_EXTERNAL_GENERATOR', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_LINK1', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_LINK1', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_LINK1', 'REFERENCE_TO_DICT', 'DICTIONARY_DEPARTMENT'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_LINK1', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_LINK1', 'SHORT_CODE_OBJ', 'DEP_LINK1'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_LINK1', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_CODE1', 'TITLE', 'Поклажедатель'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_CODE1', 'EDIT_OBJECT_METHOD', 'X_VALID_HEAD_AP(XD_VIBOR_GROUPED_01("DICTIONARY_DEPARTMENT", oForm.ALIAS,"LINK,CODE,NAME", "DEP_LINK1, DEP_CODE1, DEP_NAME1", "", "", "", .T., 1, oForm, oObj,"",.F.,"DEPARTMENT_GROUPS"), oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_CODE1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_CODE1', 'CONTROLSOURCE', 'm.cAlias+".DEP_CODE1"'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_CODE1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_CODE1', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_CODE1', 'REFERENCE_TO_DICT', 'DOC_MX3_DEP_LINK1'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_CODE1', 'TYPE_FIELD_DICT', 'VARCHAR (20)'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_CODE1', 'SHORT_CODE_OBJ', 'DEP_CODE1'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_CODE1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DEP_CODE1"'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_CODE1', 'CONTROL_NAME', 'selDEP1'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_CODE1', 'CONTROL_NAME_EDIT', 'selDEP1'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_CODE1', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME1', 'TITLE', 'Поклажедатель'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME1', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME1', 'CONTROLSOURCE', 'm.cAlias+".DEP_NAME1"'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME1', 'STORAGE', 'DEPARTMENTS'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME1', 'REFERENCE_TO_DICT', 'DOC_MX3_DEP_LINK1'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME1', 'TYPE_FIELD_DICT', 'VARCHAR (254)'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME1', 'SHORT_CODE_OBJ', 'DEP_NAME1'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DEP_NAME1"'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME1', 'CONTROL_NAME', 'txtDep1'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME1', 'CONTROL_NAME_EDIT', 'txtDep1'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME1', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME', 'CONTROLSOURCE', 'm.cAlias+".DEP_NAME"'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME', 'TYPE_FIELD_DICT', 'varchar(50)'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME', 'SHORT_CODE_OBJ', 'DEP_NAME'
GO
EXEC X_SET_PROP 'DOC_MX3_DEP_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DEP_NAME"'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_LINK', 'TITLE', 'Основание'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_LINK', 'STORAGE', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_LINK', 'REFERENCE_TO_DICT', 'BD_OSNOV'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_LINK', 'SHORT_CODE_OBJ', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_NUMBER', 'TITLE', 'Основание'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_NUMBER', 'EDIT_OBJECT_METHOD', 'BK_VIBOR_OSNOV(oForm.Alias, "LINK, NUMBER, INFO", "OSNOV, OSNOV_NUM, OSNOV_INF","", EVALUATE (oForm.Alias + ".DEP_LINK"), oForm, oObj,,.T.)'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_NUMBER', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_NUMBER', 'CONTROLSOURCE', 'm.cAlias + ".OSNOV_NUM"'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_NUMBER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_NUMBER', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_NUMBER', 'STORAGE', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_NUMBER', 'REFERENCE_TO_DICT', 'DOC_MX3_OSNOV_LINK'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_NUMBER', 'TYPE_FIELD_DICT', 'varchar(30)'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_NUMBER', 'SHORT_CODE_OBJ', 'OSNOV_NUM'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_NUMBER', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".OSNOV_NUM"'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_NUMBER', 'CONTROL_NAME', 'selOsnov'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_NUMBER', 'CONTROL_NAME_EDIT', 'selOsnov'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_NUMBER', 'REFERENCE_TO_FIELD', 'NUMBER'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_INF', 'TITLE', 'Основание'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_INF', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_INF', 'CONTROLSOURCE', 'm.cAlias + ".OSNOV_INF"'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_INF', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_INF', 'STORAGE', 'OSNOV'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_INF', 'REFERENCE_TO_DICT', 'DOC_MX3_OSNOV_LINK'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_INF', 'TYPE_FIELD_DICT', 'varchar (254)'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_INF', 'SHORT_CODE_OBJ', 'OSNOV_INF'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_INF', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".OSNOV_INF"'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_INF', 'CONTROL_NAME', 'txtOsnov'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_INF', 'CONTROL_NAME_EDIT', 'txtOsnov'
GO
EXEC X_SET_PROP 'DOC_MX3_OSNOV_INF', 'REFERENCE_TO_FIELD', 'INFO'
GO
EXEC X_SET_PROP 'DOC_MX3_NOTICE_OP', 'TITLE', 'Вид операции'
GO
EXEC X_SET_PROP 'DOC_MX3_NOTICE_OP', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_MX3_NOTICE_OP', 'CONTROLSOURCE', 'm.cAlias + ''.NOTICE_OP'''
GO
EXEC X_SET_PROP 'DOC_MX3_NOTICE_OP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_NOTICE_OP', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_MX3_NOTICE_OP', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'DOC_MX3_NOTICE_OP', 'SHORT_CODE_OBJ', 'NOTICE_OP'
GO
EXEC X_SET_PROP 'DOC_MX3_NOTICE_OP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.NOTICE_OP'''
GO
EXEC X_SET_PROP 'DOC_MX3_NOTICE_OP', 'CONTROL_NAME', 'txtNOTICE_OP'
GO
EXEC X_SET_PROP 'DOC_MX3_NOTICE_OP', 'CONTROL_NAME_EDIT', 'txtNOTICE_OP'
GO
EXEC X_SET_PROP 'DOC_MX3_COUNT_DAY', 'TITLE', 'Количество дней хранения'
GO
EXEC X_SET_PROP 'DOC_MX3_COUNT_DAY', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOC_MX3_COUNT_DAY', 'CONTROLSOURCE', 'm.cAlias + ''.COUNT_DAY'''
GO
EXEC X_SET_PROP 'DOC_MX3_COUNT_DAY', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_COUNT_DAY', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_MX3_COUNT_DAY', 'TYPE_FIELD_DICT', 'VARCHAR(4)'
GO
EXEC X_SET_PROP 'DOC_MX3_COUNT_DAY', 'SHORT_CODE_OBJ', 'COUNT_DAY'
GO
EXEC X_SET_PROP 'DOC_MX3_COUNT_DAY', 'CONTROLSOURCE_EDIT', 'm.cAlias + ''.COUNT_DAY'''
GO
EXEC X_SET_PROP 'DOC_MX3_COUNT_DAY', 'CONTROL_NAME', 'txtCOUNT_DAY'
GO
EXEC X_SET_PROP 'DOC_MX3_COUNT_DAY', 'CONTROL_NAME_EDIT', 'txtCOUNT_DAY'
GO
EXEC X_SET_PROP 'DOC_MX3_COMMENT', 'TITLE', 'Примечание'
GO
EXEC X_SET_PROP 'DOC_MX3_COMMENT', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'DOC_MX3_COMMENT', 'CONTROLSOURCE', 'm.cAlias + ".COMMENT"'
GO
EXEC X_SET_PROP 'DOC_MX3_COMMENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_COMMENT', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_MX3_COMMENT', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'DOC_MX3_COMMENT', 'SHORT_CODE_OBJ', 'COMMENT'
GO
EXEC X_SET_PROP 'DOC_MX3_COMMENT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COMMENT"'
GO
EXEC X_SET_PROP 'DOC_MX3_COMMENT', 'CONTROL_NAME', 'txtCOMMENT'
GO
EXEC X_SET_PROP 'DOC_MX3_COMMENT', 'CONTROL_NAME_EDIT', 'txtCOMMENT'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_TABLE', 'TITLE', 'Таблица материальных ценностей'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_TABLE', 'SAVE_OBJECT_METHOD', 'X_SAVE(''BK_SAVE_DOC_MX3_INV_TABLE'', m.cAlias,''SQLNULL(LINK_UP), ORDERS, INV_TYPE, INV,  QTY, PRICE,  SUMMA, COMMENT,INV_CHAR'', "DOC_MX3_INV_TABLE")'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_TABLE', 'SELECT_RECORDS_METHOD', 'SQL.EXEC(''SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, INV_TYPE AS TYPE_INV, INV AS INV_LINK, * FROM dbo.BK_DOC_TAB_MX3_INV_FN (''+STR(NVL (m.nLINK, 0)) + '')'',m.cAlias)'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_TABLE', 'SELECT_RECORDS_METHOD_EDIT', 'SQL.EXEC(''SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, INV_TYPE AS TYPE_INV, INV AS INV_LINK, * FROM dbo.BK_DOC_TAB_MX3_INV_FN (''+STR(NVL (m.nLINK, 0)) + '')'',m.cAlias)'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_TABLE', 'SERVER_TABLE_NAME', 'OUT_TABLE_ROW'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_MARKER', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_MARKER', 'CONTROLSOURCE', 'm.cAlias+''.CHECKED'''
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_MARKER', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_TYPE', 'TITLE', 'Тип МЗ'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_TYPE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_TYPE', 'CONTROLSOURCE', 'm.cAlias+''.INV_TYPE'''
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_TYPE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_TYPE', 'ROWSOURCE', 'Номенклатура,Инвентарь,Товарно-материальные ценности'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_TYPE', 'STORAGE', 'STRING'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_TYPE', 'REFERENCE_TO_DICT', 'BV_NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_TYPE', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_TYPE', 'SHORT_CODE_OBJ', 'INV_TYPE'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_TYPE', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_LINK', 'TITLE', 'Материал'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_LINK', 'CONTROLSOURCE', 'm.cAlias+''.INV'''
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_LINK', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_LINK', 'REFERENCE_TO_DICT', 'BV_NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_LINK', 'SHORT_CODE_OBJ', 'INV_LINK'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CODE', 'TITLE', 'Код МЦ'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CODE', 'EDIT_OBJECT_METHOD', 'bv_document_invoice_grid_valid_inventory()'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CODE', 'CONTROLSOURCE', 'm.cAlias+''.INV_CODE'''
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CODE', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CODE', 'TYPE_FIELD_DICT', 'CHAR(12)'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CODE', 'SHORT_CODE_OBJ', 'INV_CODE'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.INV_CODE'''
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CODE', 'REFERENCE_TO_FIELD', 'CODE'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_NAME', 'TITLE', 'Наименование МЦ'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_NAME', 'CONTROLSOURCE', 'm.cAlias+''.INV_NAME'''
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_NAME', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(80)'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_NAME', 'SHORT_CODE_OBJ', 'INV_NAME'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CHAR', 'TITLE', 'Характеристика'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CHAR', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CHAR', 'CONTROLSOURCE', 'm.cAlias+''.INV_CHAR'''
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CHAR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CHAR', 'STORAGE', 'STRING'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CHAR', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CHAR', 'SHORT_CODE_OBJ', 'INV_CHAR'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_INV_CHAR', 'REFERENCE_TO_FIELD', 'STRING'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_PRICE', 'TITLE', 'Цена'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_PRICE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_PRICE', 'CONTROLSOURCE', 'm.cAlias+''.PRICE'''
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_PRICE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_PRICE', 'STORAGE', 'SUMMA'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_PRICE', 'TYPE_FIELD_DICT', 'NUMERIC(12,2)'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_QTY', 'TITLE', 'Количество'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_QTY', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_QTY', 'CONTROLSOURCE', 'm.cAlias+''.QTY'''
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_QTY', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_QTY', 'STORAGE', 'SUMMA'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_QTY', 'TYPE_FIELD_DICT', 'NUMERIC(12,4)'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_QTY', 'SHORT_CODE_OBJ', 'QTY'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_SUMMA', 'TITLE', 'Сумма'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_SUMMA', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_SUMMA', 'CONTROLSOURCE', 'm.cAlias+''.SUMMA'''
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_SUMMA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_SUMMA', 'STORAGE', 'SUMMA'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_SUMMA', 'TYPE_FIELD_DICT', 'NUMERIC(12,2)'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_SUMMA', 'SHORT_CODE_OBJ', 'SUMMA'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_COMMENT', 'TITLE', 'Примечание'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_COMMENT', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_COMMENT', 'CONTROLSOURCE', 'm.cAlias+''.COMMENT'''
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_COMMENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_COMMENT', 'STORAGE', 'STRING'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_COMMENT', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'DOC_MX3_INV_T_COMMENT', 'SHORT_CODE_OBJ', 'COMMENT'
GO

-- Навигатор --
IF NOT EXISTS (SELECT * FROM dbo.S_NAVIGATOR WHERE CODE = 'DOC_MX3')
	INSERT INTO dbo.S_NAVIGATOR (CODE, NAME, ORDERS, SYS, LINK_SELF, OBJECT, LINK_VAR, IMAGE_KEY, USERS, VISIBLE)
	SELECT 'DOC_MX3', 'Акт о возврате ТМЦ, сданных на хранение', 23, 1, (SELECT LINK FROM dbo.S_NAVIGATOR WHERE CODE = 'TMC_DOC'), (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'DOC_MX3'), NULL, 'DOCUMENT', NULL, 3
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'DOC_MX3', 'Смета-КС', 63,0
GO


GO
-- Табличная часть документов МЗ с НДС --
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS', 'Табличная часть документов МЗ с НДС', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DIR_SHABLON_DOC_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS', NAME = 'Табличная часть документов МЗ с НДС', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DIR_SHABLON_DOC_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_MARKER')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_MARKER', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_MARKER', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_MARKER'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_INV_TYPE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_INV_TYPE', 'Тип материальных запасов', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_INV_TYPE', NAME = 'Тип материальных запасов', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_INV_TYPE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_INV_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_INV_LINK', 'Материал (ссылка)', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_INV_LINK', NAME = 'Материал (ссылка)', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_INV_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_INV_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_INV_CODE', 'Материал (код)', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_INV_CODE', NAME = 'Материал (код)', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_INV_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_INV_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_INV_NAME', 'Наименование материала', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_INV_NAME', NAME = 'Наименование материала', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_INV_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_UM_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_UM_LINK', 'Единица измерения(ссылка)', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_UM_LINK', NAME = 'Единица измерения(ссылка)', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_UM_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_UM_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_UM_CODE', 'Единица измерения (Код)', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_UM_CODE', NAME = 'Единица измерения (Код)', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_UM_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_UM_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_UM_NAME', 'Наименование единицы измерения', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_UM_NAME', NAME = 'Наименование единицы измерения', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_UM_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_QTY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_QTY', 'Количество', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_QTY', NAME = 'Количество', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_QTY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_PRICE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_PRICE', 'Цена (тариф) за единицу измерения', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_PRICE', NAME = 'Цена (тариф) за единицу измерения', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_PRICE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_SUMMA')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_SUMMA', 'Стоимость товаров (работ, услуг), всего без налога', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_SUMMA', NAME = 'Стоимость товаров (работ, услуг), всего без налога', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_SUMMA'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_AKCIZ')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_AKCIZ', 'В том числе акциз', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_AKCIZ', NAME = 'В том числе акциз', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_AKCIZ'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_STAVKA_NDS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_STAVKA_NDS', 'Налоговая ставка', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_STAVKA_NDS', NAME = 'Налоговая ставка', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_STAVKA_NDS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_NO_NDS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_NO_NDS', 'Не облагается НДС', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_NO_NDS', NAME = 'Не облагается НДС', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_NO_NDS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_SUMMA_NDS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_SUMMA_NDS', 'Сумма налога', 15, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_SUMMA_NDS', NAME = 'Сумма налога', ORDERS = '15', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_SUMMA_NDS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_SUMMA_ALL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_SUMMA_ALL', 'Стоимость товаров (работ, услуг) всего с учетом налога', 16, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_SUMMA_ALL', NAME = 'Стоимость товаров (работ, услуг) всего с учетом налога', ORDERS = '16', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_SUMMA_ALL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_STATE_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_STATE_CODE', 'Страна происхождения (код)', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_STATE_CODE', NAME = 'Страна происхождения (код)', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_STATE_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_STATE_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_STATE_NAME', 'Страна происхождения (наименование)', 18, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_STATE_NAME', NAME = 'Страна происхождения (наименование)', ORDERS = '18', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_STATE_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_NUM_DEC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_NUM_DEC', 'Номер грузовой таможенной декларации', 19, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_NUM_DEC', NAME = 'Номер грузовой таможенной декларации', ORDERS = '19', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_NUM_DEC'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_EKR_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_EKR_LINK', 'Ссылка на ЭКР', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_EKR_LINK', NAME = 'Ссылка на ЭКР', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_EKR_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_EKR_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_EKR_CODE', 'Код ЭКР', 21, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_EKR_CODE', NAME = 'Код ЭКР', ORDERS = '21', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_EKR_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_SFIN_SOURCE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_SFIN_SOURCE', 'Источник финансирования', 22, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_SFIN_SOURCE', NAME = 'Источник финансирования', ORDERS = '22', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_SFIN_SOURCE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_TYPE_NDS_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_TYPE_NDS_CODE', 'Вид НДС', 23, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_TYPE_NDS_CODE', NAME = 'Вид НДС', ORDERS = '23', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_TYPE_NDS_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS_COMMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_TABLE_MZ_NDS_COMMENT', 'Примечание', 24, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_TABLE_MZ_NDS_COMMENT', NAME = 'Примечание', ORDERS = '24', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOC_TABLE_MZ_NDS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_TABLE_MZ_NDS_COMMENT'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS', 'SAVE_OBJECT_METHOD', 'X_SAVE(''dbo.BK_SAVE_DOC_TABLE_MZ_NDS'', m.cAlias,''SQLNULL(LINK_UP), ORDERS, INV_TYPE, SQLNULL(INV_LINK),  PRICE, AKCIZ, NUM_TD, QTY, SUMMA, STAVKA_NDS, SUMMA_NDS, SUMMA_ALL, SQLNULL(EKR_LINK), SFIN_CODE, NO_NDS, SQLNULL (STATE_LINK), SQLNULL (TNDS_LINK),COMMENT'', "DOC_TABLE_MZ_NDS")'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS', 'SELECT_RECORDS_METHOD', 'SQL.EXEC(''SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * FROM dbo.BK_DOC_TABLE_MZ_NDS_FN (''+STR(NVL (m.nLINK, 0)) + '')'',m.cAlias)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS', 'SERVER_TABLE_NAME', 'OUT_TABLE_ROW'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_MARKER', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_MARKER', 'CONTROLSOURCE', 'm.cAlias+''.CHECKED'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_MARKER', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_MARKER', 'SHORT_CODE_OBJ', 'CHECKED'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_TYPE', 'TITLE', 'Тип'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_TYPE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_TYPE', 'CONTROLSOURCE', 'm.cAlias+''.INV_TYPE'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_TYPE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_TYPE', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_LINK', 'TITLE', 'Материал'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_LINK', 'STORAGE', 'NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_LINK', 'REFERENCE_TO_DICT', 'BV_NOMENCLATURE'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_LINK', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_LINK', 'SHORT_CODE_OBJ', 'INV_LINK'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_CODE', 'TITLE', 'Номен.\Инв. №'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_CODE', 'EDIT_OBJECT_METHOD', 'bk_vibor_doc_table_mz_nds()'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_CODE', 'CONTROLSOURCE', 'm.cAlias+''.INV_CODE'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_CODE', 'OPERATE_METHOD', 'X_OPERATE_METHOD (EVALUATE(m.cAliasOperate+''.INV_TYPE''),EVALUATE(m.cAliasOperate+''.INV_LINK''))
'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_CODE', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_NAME', 'CONTROLSOURCE', 'm.cAlias+''.INV_NAME'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_NAME', 'OPERATE_METHOD', 'X_OPERATE_METHOD (EVALUATE(m.cAliasOperate+''.INV_TYPE''),EVALUATE(m.cAliasOperate+''.INV_LINK''))
'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_INV_NAME', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_LINK', 'TITLE', 'Единица измерения'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_LINK', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_CODE', 'TITLE', 'ЕИ (Код)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_DIGIT", oObj.parent.Parent.RECORDSOURCE, "LINK, CODE, NAME", "UM_LINK, UM_CODE, UM_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_CODE', 'CONTROLSOURCE', 'm.cAlias+''.UM_CODE'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_CODE', 'OPERATE_METHOD', 'X_OPERATE_METHOD ("DICTIONARY_DIGIT", EVALUATE(m.cAliasOperate+''.UM_LINK''))
'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_CODE', 'TYPE_FIELD_DICT', 'varchar(10)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.UM_CODE'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_NAME', 'TITLE', 'Единица измерения'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_NAME', 'CONTROLSOURCE', 'm.cAlias+''.UM_NAME'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_NAME', 'OPERATE_METHOD', 'X_OPERATE_METHOD ("DICTIONARY_DIGIT", EVALUATE(m.cAliasOperate+''.UM_LINK''))
'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_UM_NAME', 'TYPE_FIELD_DICT', 'varchar(15)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_QTY', 'TITLE', 'Количество'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_QTY', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_QTY', 'CONTROLSOURCE', 'm.cAlias+''.QTY'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_QTY', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_QTY', 'TYPE_FIELD_DICT', 'NUMERIC(13,4)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_PRICE', 'TITLE', 'Цена'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_PRICE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_PRICE', 'CONTROLSOURCE', 'm.cAlias+''.PRICE'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_PRICE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_PRICE', 'TYPE_FIELD_DICT', 'NUMERIC(18,4)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA', 'TITLE', 'Стоимость'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA', 'CONTROLSOURCE', 'm.cAlias + ''.SUMMA'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA', 'TYPE_FIELD_DICT', 'NUMERIC(17,2)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_AKCIZ', 'TITLE', 'Акциз'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_AKCIZ', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_AKCIZ', 'CONTROLSOURCE', 'm.cAlias + ''.AKCIZ'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_AKCIZ', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_AKCIZ', 'TYPE_FIELD_DICT', 'NUMERIC(5,2)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_AKCIZ', 'AUTO_FILL_CONTEXT', '999.99'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STAVKA_NDS', 'TITLE', 'Налоговая ставка'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STAVKA_NDS', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STAVKA_NDS', 'CONTROLSOURCE', 'm.cAlias + ''.STAVKA_NDS'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STAVKA_NDS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STAVKA_NDS', 'TYPE_FIELD_DICT', 'NUMERIC(5,2)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STAVKA_NDS', 'INPUT_MASK', '99.99'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NO_NDS', 'TITLE', 'Без НДС'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NO_NDS', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NO_NDS', 'CONTROLSOURCE', 'm.cAlias + ''.NO_NDS'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NO_NDS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NO_NDS', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_NDS', 'TITLE', 'Сумма налога'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_NDS', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_NDS', 'CONTROLSOURCE', 'm.cAlias+''.SUMMA_NDS'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_NDS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_NDS', 'TYPE_FIELD_DICT', 'numeric(13,2)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_ALL', 'TITLE', 'Полная стоимость'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_ALL', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_ALL', 'CONTROLSOURCE', 'm.cAlias+''.SUMMA_ALL'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_ALL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SUMMA_ALL', 'TYPE_FIELD_DICT', 'numeric(13,2)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_CODE', 'TITLE', 'Код страны'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01("DICTIONARY_COUNTRY", oObj.parent.Parent.RECORDSOURCE, "LINK,CODE,NAME", "STATE_LINK, STATE_CODE, STATE_NAME", "", "","",  .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_CODE', 'CONTROLSOURCE', 'm.cAlias+''.STATE_CODE'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_NAME', 'TITLE', 'Наименование страны'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_NAME', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_NAME', 'CONTROLSOURCE', 'm.cAlias+''.STATE_NAME'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_STATE_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NUM_DEC', 'TITLE', 'Номер ГТД'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NUM_DEC', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NUM_DEC', 'CONTROLSOURCE', 'm.cAlias+''.NUM_TD'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NUM_DEC', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_NUM_DEC', 'TYPE_FIELD_DICT', 'varchar(5)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_LINK', 'TITLE', 'Ссылка на ЭКР'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_LINK', 'CONTROLSOURCE', 'm.cAlias+''.EKR_LINK'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_LINK', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_LINK', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_LINK', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_CODE', 'TITLE', 'ЭКР'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_CODE', 'EDIT_OBJECT_METHOD', 'a_vibor_01("DICTIONARY_ITEM", oObj.parent.Parent.RECORDSOURCE, "LINK,CODE", "EKR_LINK, EKR_CODE", "", "","",  .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_CODE', 'CONTROLSOURCE', 'm.cAlias+''.EKR_CODE'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_CODE', 'OPERATE_METHOD', 'X_OPERATE_METHOD ("DICTIONARY_KOSGU", EVALUATE(m.cAliasOperate+''.EKR_LINK''))
'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_EKR_CODE', 'TYPE_FIELD_DICT', 'CHAR(3)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SFIN_SOURCE', 'TITLE', 'Источник'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SFIN_SOURCE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SFIN_SOURCE', 'CONTROLSOURCE', 'm.cAlias+''.SFIN_NAME'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SFIN_SOURCE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_SFIN_SOURCE', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_TYPE_NDS_CODE', 'TITLE', 'Вид НДС'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_TYPE_NDS_CODE', 'EDIT_OBJECT_METHOD', 'a_vibor_01("DICTIONARY_TYPE_OPER_NDS", oObj.parent.Parent.RECORDSOURCE, "LINK,CODE", "TNDS_LINK, TNDS_CODE", "", "","",  .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_TYPE_NDS_CODE', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_TYPE_NDS_CODE', 'CONTROLSOURCE', 'm.cAlias+''.TNDS_CODE'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_TYPE_NDS_CODE', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_TYPE_NDS_CODE', 'OPERATE_METHOD', 'X_OPERATE_METHOD ("DICTIONARY_TYPE_OPER_NDS",EVALUATE(m.cAliasOperate+''.TNDS_LINK''))
'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_TYPE_NDS_CODE', 'TYPE_FIELD_DICT', 'VARCHAR(2)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_TYPE_NDS_CODE', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.TNDS_CODE'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_COMMENT', 'TITLE', 'Примечание'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_COMMENT', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_COMMENT', 'CONTROLSOURCE', 'm.cAlias+''.COMMENT'''
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_COMMENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_COMMENT', 'TYPE_FIELD_DICT', 'VARCHAR(254)'
GO
EXEC X_SET_PROP 'DOC_TABLE_MZ_NDS_COMMENT', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.COMMENT'''
GO



GO
--добавление колонки [DAYS_VAC_O] в таблицу STAFF
IF COLUMNPROPERTY(object_id('[dbo].[STAFF]'), 'DAYS_VAC_O', 'AllowsNull') is null
	ALTER TABLE [dbo].[STAFF] add [DAYS_VAC_O] NUMERIC(2,0) NOT NULL CONSTRAINT [DF_STAFF_DAYS_VAC_O] DEFAULT 0
GO

--добавление колонки [DAYS_VAC_D] в таблицу STAFF
IF COLUMNPROPERTY(object_id('[dbo].[STAFF]'), 'DAYS_VAC_D', 'AllowsNull') is null
	ALTER TABLE [dbo].[STAFF] add [DAYS_VAC_D] NUMERIC(2,0) NOT  NULL  CONSTRAINT [DF_STAFF_DAYS_VAC_D] DEFAULT 0
GO


GO
--Таблица sys_events_rms
IF not exists(select * from sysobjects where id = object_id('[dbo].[SYS_EVENTS_RMS]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
CREATE TABLE [dbo].[SYS_EVENTS_RMS] (
	[LINK] int NOT NULL IDENTITY(1,1) ,
	[LINK_MSG] int NULL ,
	[GUID] nvarchar(255) NULL ,
	[DIRECTION] nvarchar(50) NULL ,
	[TYPE] nvarchar(50) NULL ,
	[NAME] nvarchar(255) NULL ,
	[SUBJECT] nvarchar(1024) NULL ,
	[DATETIME] datetime NULL ,
	[SENDER] nvarchar(255) NULL ,
	[RECIPIENTS] nvarchar(4000) NULL ,
	[PRIORITY] int NULL ,
	[STATUS] nvarchar(50) NULL ,
	[STATUS_DATE] datetime NULL ,
	[STATUS_INFO] nvarchar(4000) NULL ,
	[PROCESSED] int NULL ,
	[USERS] int NULL ,
	[LOGINAME] varchar(128) NULL ,
	[HOSTNAME] varchar(128) NULL )
GO

GRANT SELECT, UPDATE, DELETE ON dbo.[sys_events_rms] TO PUBLIC
GO
GO
--Добавление колонки [VAC_V] в таблицу VACATION_VID
IF COLUMNPROPERTY(object_id('[dbo].[VACATION_VID]'), 'VAC_V', 'AllowsNull') is null
	ALTER TABLE [dbo].[VACATION_VID] add [VAC_V] tinyint NOT NULL
		CONSTRAINT [DF_VACATION_VID_VAC_V] DEFAULT (0) -- FOR [VAC_V]
GO

GO

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

GO


/*2. Обновление справочника по зарплате*/
CREATE	VIEW [dbo].DICTIONARY_MROT
AS
SELECT LINK,PERIOD,MROT1,MROT2,TARIF,KOEF, KOEF_BL = (case when coalesce(KOEF_BL,0) = 0 then KOEF else KOEF_BL end),
REF_DEP, 
[CODE_DEP] = isnull((select CODE from PAYS where LINK = REF_DEP),''),
[NAME_DEP] = isnull((select NAME from PAYS where LINK = REF_DEP),'') ,
RESERV
FROM dbo.MINROT


GO


GRANT SELECT ON dbo.[DICTIONARY_MROT] TO PUBLIC

GO


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

GO

CREATE VIEW [dbo].DICT_RMS_CONTACTS 
AS 
SELECT 	[LINK] ,
	[CONTACT_ID] ,
	[TYPE] ,
	[NAME] = LEFT(NAME,254) ,
	[ADDRESS] = LEFT(ADDRESS,254) ,
	[ENABLED] = CASE WHEN [ENABLED] = 1 THEN CONVERT (VARCHAR (3), 'Да')
					 ELSE CONVERT (VARCHAR (3), 'Нет')
					 END,
	[SERVICE] ,
	[MYSELF] ,
	[OPENED] ,
	[ON_LINE] ,
	[ACCESS_MODE] ,
	[COMMENTS] = LEFT(COMMENTS,254)
FROM 
	DBO.RMS_CONTACTS 




GO


GRANT SELECT ON dbo.[DICT_RMS_CONTACTS] TO PUBLIC

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 = 
			SUBSTRING(
			(case when COALESCE(S.[ter_usl],'') <> '' then ',' + COALESCE(S.[ter_usl],'') else '' end )
			+ (case when coalesce(ter_koef,0) <> 0 then ',' + convert(varchar(20),coalesce(ter_koef,0)) else '' end )
			,2,254),	
	--Особые условия труда
	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 = 
			SUBSTRING(
			(case when COALESCE(S.[osob_usl],'') <> '' then ',' + COALESCE(S.[osob_usl],'') else '' end )
			+ (case when COALESCE(S.[osob_k1],'') <> '' then ',' + COALESCE(S.[osob_k1],'') else '' end )
			+ (case when COALESCE(S.[osob_k2],'') <> '' then ',' + COALESCE(S.[osob_k2],'') else '' end )
			+ (case when COALESCE(S.[osob_k3],'') <> '' then ',' + COALESCE(S.[osob_k3],'') else '' end )
			+ (case when COALESCE(S.[osob_spo],'') <> '' then ',' + COALESCE(S.[osob_spo],'') else '' end )
			,2,254),
	-- Исчисление страхового стажа
	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.[RN_VIEW_TYPE_KOR]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[RN_VIEW_TYPE_KOR]

GO

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

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

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

CREATE VIEW dbo.[RN_VIEW_TYPE_KOR]
AS

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

GO


GRANT SELECT ON dbo.[RN_VIEW_TYPE_KOR] TO PUBLIC

GO



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

GO

CREATE     VIEW dbo.DOCUMENTS_ADD_RESERV
AS
SELECT 
	[LINK]			= S.LINK,
	[NUMBER]		= S.NUMBER,
	[DATE]			= S.[DATE],
	[PERIOD]		= S.DATE_CALC,
	[MONTH]			= MONTH(S.DATE_CALC),
	[YEAR]			= YEAR(S.DATE_CALC),
	[SUMMA]			= S.SUMMA_T,
	[LINK_DEP]  	= S.LINK_DEP,
	DEP.[NAME] as NAME_DEP,
	[COMMENTARY]	= S.[COMMENTARY]
FROM 
	dbo.SDOC S INNER JOIN dbo.SDOC_RESERV SD ON (S.LINK = SD.LINK_UP AND S.OBJECT =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOCUMENTS_ADD_RESERV'))
	INNER JOIN dbo.DEPARTMENTS DEP ON DEP.link = S.LINK_DEP



GO


GRANT SELECT ON dbo.[DOCUMENTS_ADD_RESERV] TO PUBLIC

GO




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

GO
CREATE View [dbo].SALARY_GROUP_DEDUCTION as

		SELECT CODE = 1, [NAME] = 'Стандартные налоговые вычеты, ст.218 НК РФ'
UNION	SELECT CODE = 2, [NAME] = 'Вычеты по ст.211 НК РФ (при получении доходов в натуральной форме)'
UNION	SELECT CODE = 3, [NAME] = 'Вычеты по ст.214.1 НК РФ (на доходы по операциям с ценными бумагами)'
UNION	SELECT CODE = 4, [NAME] = 'Вычеты по п/п.2 п.1 ст.220 НК РФ (Имущественные налоговые вычеты)'
UNION	SELECT CODE = 5, [NAME] = 'Вычеты по ст.221 НК РФ (профессиональные налоговые вычеты)'
UNION	SELECT CODE = 6, [NAME] = 'Вычеты по ст.217 НК РФ (мат.помощь, пособия, пенсии, компенсационные выплаты и др.)'
UNION	SELECT CODE = 7, [NAME] = 'Вычеты по ст.214 НК РФ (дивиденды от долевого участия в организации)'
UNION	SELECT CODE = 8, [NAME] = 'Вычеты по ст.213 НК РФ (по дог. страхования)'
UNION	SELECT CODE = 9, [NAME] = 'Вычеты по ст.213.1 НК РФ (по договорам негос. пенс. обеспечения)'
UNION	SELECT CODE = 10, [NAME] = 'Вычеты по п/п.4 п.1 ст.219 НК РФ (Социальные налоговые вычеты по договорам негос. пенс. обеспечения)'
UNION	SELECT CODE = 11, [NAME] = 'Вычеты по п/п.2 п.1 ст.219 НК РФ (Социальные налоговые вычеты по оплате образования)'
UNION	SELECT CODE = 12, [NAME] = 'Вычеты по п/п.3 п.1 ст.219 НК РФ (Социальные налоговые вычеты по мед. затратам и добровольн. страх.)'
UNION	SELECT CODE = 13, [NAME] = 'Вычеты по п/п.5 п.1 ст.219 НК РФ (Социальные налоговые вычеты по доп. страх.взносам на накопитю пенсию)'

GO


GRANT SELECT ON dbo.[SALARY_GROUP_DEDUCTION] TO PUBLIC

GO


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

GO

CREATE FUNCTION dbo.DateEndOfYear(@dDate Datetime)

RETURNS DATETIME
AS
BEGIN
	RETURN DATEADD(YEAR, DATEDIFF(YEAR, -1, @dDate), -1)
END

GO


GRANT EXECUTE ON dbo.[DateEndOfYear] TO PUBLIC

GO


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

CREATE VIEW dbo.SCJ_NDFL_R
AS
SELECT
	J.LINK_EMPL,
	[YEAR_BEGIN] = YEAR(J.PERIOD_BEGIN),
	[MONTH_BEGIN]	= MONTH(J.PERIOD_BEGIN),
	LINK_VKR,
	name_vkr = SF.CODE,
	LINK_EKR = S.LINK,
	NAME_EKR = S.CODE	
FROM
	dbo.PAYS P
	INNER JOIN dbo.CALCULATE_JURNAL J ON J.LINK_PAYS = P.LINK
	INNER JOIN dbo.sal_sfin SF ON SF.LINK = J.LINK_VKR
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = 'R211') R211
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = '211') T211
	INNER JOIN dbo.KOSGU S ON S.LINK = (CASE WHEN R211.LINK = ISNULL(J.LINK_EKR,P.LINK_EKR) THEN T211.LINK ELSE ISNULL(J.LINK_EKR,P.LINK_EKR) END)
WHERE
	P.[OBJECT] = 1	


GO


GRANT SELECT ON dbo.[SCJ_NDFL_R] TO PUBLIC

GO

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


CREATE    FUNCTION dbo.DateBeginOfMonth(@varKSdDate Datetime)

RETURNS DATETIME
AS
BEGIN
	RETURN DATEADD(MONTH, DATEDIFF(MONTH, 0, @varKSdDate), 0)
END
GO


GRANT EXECUTE ON dbo.[DateBeginOfMonth] TO PUBLIC

GO

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

GO


CREATE FUNCTION dbo.DateEndOfMonth(@varKSdDate Datetime)

RETURNS DATETIME
AS
BEGIN
	RETURN DATEADD(MONTH, DATEDIFF(MONTH, -1, @varKSdDate), -1)
END
GO


GRANT EXECUTE ON dbo.[DateEndOfMonth] TO PUBLIC

GO

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

CREATE   FUNCTION dbo.DateBeginOfYear(@dDate Datetime)

RETURNS DATETIME
AS
BEGIN
	RETURN DATEADD(YEAR, DATEDIFF(YEAR, 0, @dDate), 0)
END

GO


GRANT EXECUTE ON dbo.[DateBeginOfYear] 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].[RMSGetProp]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[RMSGetProp]
GO
create function [dbo].[RMSGetProp] (@msgLink int, @Name nvarchar(255))
	returns nvarchar(max) as
begin
  declare @cRes nvarchar(max)
  
  select top 1 @cRes = c.value 
  from dbo.rms_message_properties c
  where c.message_link = @msgLink
    and c.name = @Name
	
  return @cRes 
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

/*
Назначение: Возвращает собственный адрес в системе службы сообщений
Входные параметры: нет
Код возврата:	строка адреса
Пример вызова: select [dbo].[RmsGetSelfAddress]()
Примечание:
Автор: Петров А.Н.
*/

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


CREATE function [dbo].[RmsGetSelfAddress] ()
returns nvarchar(1024)
begin
    declare @Res nvarchar(1024)
    set @Res = ''
    if object_id('[dbo].[rms_contacts]') is not null 
      select top 1 @Res = isnull(c.address,'') from dbo.rms_contacts c where c.myself>0    

    return @Res
end

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].[RMSGetSender]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[RMSGetSender]
GO
create function [dbo].[RMSGetSender] (@msgLink int)
	returns nvarchar(255) as
begin
  declare @cRes nvarchar(255)
  
  select top 1 @cRes = rtrim(m.sender)
  from dbo.rms_messages m
  where m.link = @msgLink
	
  return @cRes 
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.[GetNums]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[GetNums]

GO
CREATE FUNCTION dbo.GetNums(@low AS BIGINT, @high AS BIGINT) RETURNS TABLE
AS
RETURN
WITH
L0 AS (SELECT c FROM (SELECT 1 UNION ALL SELECT 1) AS D(c)),
L1 AS (SELECT 1 AS c FROM L0 AS A CROSS JOIN L0 AS B),
L2 AS (SELECT 1 AS c FROM L1 AS A CROSS JOIN L1 AS B),
L3 AS (SELECT 1 AS c FROM L2 AS A CROSS JOIN L2 AS B),
L4 AS (SELECT 1 AS c FROM L3 AS A CROSS JOIN L3 AS B),
L5 AS (SELECT 1 AS c FROM L4 AS A CROSS JOIN L4 AS B),
Nums AS (SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS rownum
FROM L5)
SELECT TOP(@high - @low + 1) (@low + rownum - 1) AS n
FROM Nums
ORDER BY rownum;

GO


GRANT SELECT ON dbo.[GetNums] 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].[RMSGetSubject]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[RMSGetSubject]
GO
create function [dbo].[RMSGetSubject] (@msgLink int)
	returns nvarchar(1024) as
begin
  declare @cRes nvarchar(max)
  
  select top 1 @cRes = rtrim(c.subject)
  from dbo.rms_messages c
  where c.link = @msgLink
	
  return @cRes 
end

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].[RMSGetValue]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[RMSGetValue]
GO
create function [dbo].[RMSGetValue] (@msgLink int, @Name nvarchar(255))
	returns nvarchar(max) as
begin
  declare @cRes nvarchar(max)
  
  select top 1 @cRes = c.value 
  from dbo.rms_message_contents c
  where c.message_link = @msgLink
  and upper(rtrim(@Name)) like upper(rtrim(c.name)) 
	
  return @cRes 
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.[SAL_OPTIONS_INTEGRATION_VIEW]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[SAL_OPTIONS_INTEGRATION_VIEW]

GO


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

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

*******************************************************************************/
CREATE VIEW dbo.SAL_OPTIONS_INTEGRATION_VIEW
AS
SELECT   T.*,
		(SELECT [ADDRESS] FROM DICT_RMS_CONTACTS WHERE LINK = T.CHANAL_LINK) AS CHANAL_ADDRESS,
		(SELECT NAME FROM DICT_RMS_CONTACTS WHERE LINK = T.CHANAL_LINK) AS CHANAL_NAME
FROM	(	
		SELECT	convert(int, dbo.sa_get_option_by_code('SAL_OPT_INTEGR_CHANAL')) as CHANAL_LINK,
				str( dbo.sa_get_option_by_code('SAL_OPT_INTEGR_PROV_ZP_EXP')) as EXP_PROV_ZP,
				str( dbo.sa_get_option_by_code('SAL_OPT_INTEGR_KLASSIF_IMP')) as IMP_KLASSIF,
				str( dbo.sa_get_option_by_code('SAL_OPT_INTEGR_IMP_KORR')) as IMP_KORR,
				str( dbo.sa_get_option_by_code('SAL_OPT_INTEGR_KADR_EXP')) as EXP_KADR,
				str(dbo.sa_get_option_by_code('SAL_OPT_INTEGR_PROV_PERECH_IMP')) as IMP_PROV_PERECH,
				str(dbo.sa_get_option_by_code('SAL_OPT_INTEGR_PP_ZKR_EXP')) as EXP_PP_ZKR
		) AS T




GO


GRANT SELECT ON dbo.[SAL_OPTIONS_INTEGRATION_VIEW] TO PUBLIC

GO



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

GO
-- Ставки по налогу на имуществу --
CREATE VIEW dbo.DIC_IMU_TAX_RATE
AS
	SELECT
		CHECKED	=	0,
		LINK	=	1,
		CODE	=	'0',
		NAME	=	'Не облагается налогом'
	
	UNION ALL

	SELECT
		CHECKED	=	0,
		LINK	=	2,
		CODE	=	CONVERT (VARCHAR (5), ISNULL ([PERCENT], 0)),
		NAME	=	'Облагается налогом'
	FROM dbo.AVANSE_ASSETS_OPTIONS

	UNION ALL

	SELECT
		CHECKED	=	0,
		LINK	=	3,
		CODE	=	'-',
		NAME	=	'Льготируемое имущество'
GO

GRANT SELECT ON dbo.[DIC_IMU_TAX_RATE] TO PUBLIC

GO

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

GO
CREATE FUNCTION dbo.days_ex
	(@PERIOD_BEGIN DATETIME,
	 @PERIOD_END DATETIME)
RETURNS TABLE 

RETURN

	SELECT @PERIOD_BEGIN + N.N-1 AS [DATE] FROM dbo.GetNums(1,DATEDIFF(D,@PERIOD_BEGIN,@PERIOD_END)+1) N 

GO


GRANT SELECT ON dbo.[days_ex] TO PUBLIC

GO

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

CREATE FUNCTION dbo.SD_DAY(@varKSdDate1 datetime, @varKSdDate2 datetime)
RETURNS TABLE 

RETURN

	SELECT @varKSdDate1 + N.N-1 AS [DATE] FROM dbo.GetNums(1,DATEDIFF(D,@varKSdDate1,@varKSdDate2)+1) N 
GO

GRANT SELECT ON dbo.[SD_DAY] TO PUBLIC

GO

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

CREATE FUNCTION dbo.KU_DAY(@dDate1 datetime, @ndays int)
RETURNS TABLE
AS
	RETURN SELECT @dDate1 + N.N-1 AS [DATE] FROM dbo.GetNums(1,@ndays) N 
GO

GRANT SELECT ON dbo.[KU_DAY] TO PUBLIC
GO

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

GO

CREATE	FUNCTION dbo.BK_PrintDocProv (
	@varKSLINK_DOC	INT = NULL,
	@varKSPRN_SPRAV	TINYINT = 0
	)
--	Если @varKSPRN_SPRAV = 0, то настройки документа,
--		иначе настройки бух. справки
RETURNS @TABLE_RES TABLE
	([LINK_G]	[INT],
	[LINK_G1]	[INT],
	[LINK_G2]	[INT],
	XOZ_OPER	INT,
	[NAME_OPER]	[VARCHAR] (254),
	[SUMMA]		[NUMERIC] (28,4),
	[QTY]		[NUMERIC] (28,4),
	[ORDERS_G1]	[INT],
	[ORDERS_G2]	[INT],
	[ACCT_DB]	[INT],
	[ACCT_KT]	[INT],
	[ACCT_CD_D]	[VARCHAR] (60),
	[ACCT_CD_K]	[VARCHAR] (60),
	[SA_CODE_D]	[VARCHAR] (20),
	[SA_CODE_K]	[VARCHAR] (20)
	)
AS 
BEGIN
	DECLARE @intPrintAll TINYINT,
		@intPrintKBK TINYINT,
		@intPrintSGU TINYINT

	SELECT @intPrintAll = dbo.XK_GET_NASTR_INT ('XD_DOC_NASTR_OPTIONS_ALL_PRINT')

	-- Общая настройка на все документы -- 
	IF @intPrintAll = 1
	BEGIN
		SELECT @intPrintKBK = dbo.XK_GET_NASTR_INT ('XD_DOC_NASTR_OPTIONS_KBK_PRINT'),
			@intPrintSGU = dbo.XK_GET_NASTR_INT ('XD_DOC_NASTR_OPTIONS_SGU_PRINT')

		INSERT INTO @TABLE_RES
		SELECT
			G.LINK,
			G1.LINK,
			G2.LINK,
			G2.ECON_OPER,
			CASE 
				WHEN ISNULL (G2.[NAME], '') = '' THEN ISNULL (G1.NAME_OPER, '')
				ELSE G2.[NAME]
			END,
			G2.SUMMA,
			CASE
				WHEN SA_DB.KSU = 1 OR SA_KT.KSU = 1 THEN G2.QUANTITY
				ELSE 0
			END,
			G1.ORDERS,
			G2.ORDERS,
			GAP_DB.ACCOUNT,	
			GAP_KT.ACCOUNT,
			dbo.BK_GetAcctFullCode1 (GAP_DB.ACCOUNT, GAP_DB.KBK, GAP_DB.SGU,
				@intPrintKBK, @intPrintSGU),
			dbo.BK_GetAcctFullCode1 (GAP_KT.ACCOUNT, GAP_KT.KBK, GAP_KT.SGU,
				@intPrintKBK, @intPrintSGU),
			SA_DB.CODE,
			SA_KT.CODE
		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)
		LEFT OUTER JOIN dbo.G_PROV_AP GAP_DB ON (GAP_DB.LINK_UP = G2.LINK
			AND GAP_DB.DB_KR = 0)
		LEFT OUTER JOIN dbo.S_ACCOUNTS SA_DB ON (SA_DB.LINK = GAP_DB.ACCOUNT)
		LEFT OUTER JOIN dbo.G_PROV_AP GAP_KT ON (GAP_KT.LINK_UP = G2.LINK
			AND GAP_KT.DB_KR = 1)
		LEFT OUTER JOIN dbo.S_ACCOUNTS SA_KT ON (SA_KT.LINK = GAP_KT.ACCOUNT)
		WHERE @varKSLINK_DOC IS NULL
			OR G.LINK = @varKSLINK_DOC
	END
	ELSE
	BEGIN
		INSERT INTO @TABLE_RES
		SELECT G.LINK,
			G1.LINK,
			G2.LINK,
			G2.ECON_OPER,
			CASE 
				WHEN ISNULL (G2.[NAME], '') = '' THEN ISNULL (G1.NAME_OPER, '')
				ELSE G2.[NAME]
			END,
			G2.SUMMA,
			CASE
				WHEN SA_DB.KSU = 1 OR SA_KT.KSU = 1 THEN G2.QUANTITY
				ELSE 0
			END,
			G1.ORDERS,
			G2.ORDERS,
			GAP_DB.ACCOUNT,	
			GAP_KT.ACCOUNT,
			CASE 
				WHEN @varKSPRN_SPRAV = 0 OR (SO.CODE = 'DOCUMENTS_OPER' OR SO.CODE = 'DOCUMENTS_ZB_OPER')
					THEN	dbo.BK_GetAcctFullCode1 (GAP_DB.ACCOUNT, GAP_DB.KBK, GAP_DB.SGU,
								NASTR_DOC.PRINT_KBK, NASTR_DOC.PRINT_SGU)
					ELSE	dbo.BK_GetAcctFullCode1 (GAP_DB.ACCOUNT, GAP_DB.KBK, GAP_DB.SGU,
								NASTR_SPR.PRINT_KBK, NASTR_SPR.PRINT_SGU)
			END,
			CASE 
				WHEN @varKSPRN_SPRAV = 0 OR (SO.CODE = 'DOCUMENTS_OPER' OR SO.CODE = 'DOCUMENTS_ZB_OPER')
					THEN	dbo.BK_GetAcctFullCode1 (GAP_KT.ACCOUNT, GAP_KT.KBK, GAP_KT.SGU,
								NASTR_DOC.PRINT_KBK, NASTR_DOC.PRINT_SGU)
					ELSE	dbo.BK_GetAcctFullCode1 (GAP_KT.ACCOUNT, GAP_KT.KBK, GAP_KT.SGU,
								NASTR_SPR.PRINT_KBK, NASTR_SPR.PRINT_SGU)
			END,
			SA_DB.CODE,
			SA_KT.CODE
		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)
		LEFT OUTER JOIN dbo.G_PROV_AP GAP_DB ON (GAP_DB.LINK_UP = G2.LINK
			AND GAP_DB.DB_KR = 0)
		LEFT OUTER JOIN dbo.S_ACCOUNTS SA_DB ON (SA_DB.LINK = GAP_DB.ACCOUNT)
		LEFT OUTER JOIN dbo.G_PROV_AP GAP_KT ON (GAP_KT.LINK_UP = G2.LINK
			AND GAP_KT.DB_KR = 1)
		LEFT OUTER JOIN dbo.S_ACCOUNTS SA_KT ON (SA_KT.LINK = GAP_KT.ACCOUNT)
		INNER JOIN dbo.S_OBJECTS SO ON (SO.LINK = G.OBJECT)
		LEFT OUTER JOIN dbo.DOC_NASTR NASTR_DOC ON (NASTR_DOC.LINK = SO.LINK)
		LEFT OUTER JOIN dbo.S_OBJECTS SO_SPR ON (SO_SPR.CODE = 'DOCUMENTS_F0504833')
		LEFT OUTER JOIN dbo.DOC_NASTR NASTR_SPR ON (NASTR_SPR.LINK = SO_SPR.LINK)
		WHERE @varKSLINK_DOC IS NULL
			OR G.LINK = @varKSLINK_DOC
	END
	RETURN 
END


GO


GRANT SELECT ON dbo.[BK_PrintDocProv] TO PUBLIC

GO


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


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

GO
CREATE TRIGGER dbo.G_PROV_XDELETE ON G_PROV
FOR DELETE 
AS
  IF @@ROWCOUNT>0
	BEGIN
		
		
		IF  convert(int, dbo.sa_get_option_by_code('SAL_OPT_INTEGR_CHANAL')) <> 0  AND convert(tinyint,dbo.sa_get_option_by_code('SAL_OPT_INTEGR_PROV_ZP_EXP')) = 1
		BEGIN
			DECLARE @CHANAL_LINK INT, 
				@PROV_ZP_EXP TINYINT ,
				@OBJECT varchar(50)
				
			SET @CHANAL_LINK =  (select convert(int, dbo.sa_get_option_by_code('SAL_OPT_INTEGR_CHANAL')))
			SET @PROV_ZP_EXP = (SELECT convert(tinyint,dbo.sa_get_option_by_code('SAL_OPT_INTEGR_PROV_ZP_EXP')))
			SET @OBJECT = (select code from s_objects where link = (SELECT TOP 1 [OBJECT] FROM DELETED)) 
			IF @PROV_ZP_EXP = 1 AND @OBJECT = 'DOCUMENTS_SALARY' 
			BEGIN
				SET @OBJECT = 'DOCUMENTS_SALARY' 	
				
				/* СОЗДАЕМ ВРЕМЕНННУЮ ТАБЛИЦУ */

				------------------------------- ВЫБИРАЮТСЯ ВСЕ ЛИНКИ УДАЛЯЕМЫХ ПРОВОДОК ИЗ ЖУРНАЛА и  закидываются в буфер  ------------
			
				----------В этой таблице будут лежать GUID на удаляемые проводки --------------
				DECLARE @SYNC_TABLE1 VARCHAR(20),
						@SQLText NVARCHAR(1000),
						@MSG VARCHAR(500),
						@iERROR INT
				EXEC DBO.X_GET_TABLE_NAME @SYNC_TABLE1 OUTPUT
				

		
				CREATE TABLE #SYNC_TABLE (ID int IDENTITY(1,1), F_NAME VARCHAR(254), XML_DATA TEXT)
				INSERT INTO #SYNC_TABLE  ( F_NAME, XML_DATA)
				SELECT  '', OUT_TEXT = CONVERT( TEXT, CONVERT(VARCHAR(36), d.GUID)) 
				from DELETED d
				
				
				IF (SELECT COUNT(*) FROM #SYNC_TABLE ) > 0
				BEGIN
									
					SET @SQLText = ''
					SET @SQLText = 'SELECT * INTO '+@SYNC_TABLE1+' from #SYNC_TABLE'
					exec sp_executesql @SQLText 
			
					-----------------------	
					-------Выгрузка/удаление в Смету-Смарт
					DECLARE @Protocol_Text VARCHAR(8000),
							@CH_LINK VARCHAR(10)
		
					SET @CH_LINK = @CHANAL_LINK	
					SET @SQLtext = ''
					SET @SQLText = '  EXEC  @iERROR =  dbo.SMETA_SMART_SYNC ''' + @SYNC_TABLE1 + ''', '+ @CH_LINK +','''+@OBJECT+''',1 ,@protocol_text output '
					exec sp_executesql @SQLText, N'@protocol_text varchar(8000) output, @iERROR int output', @protocol_text = @protocol_text OUTPUT, @iERROR = @iERROR OUTPUT
					SET @MSG = ''	
					IF @iERROR <> 0 OR ISNULL(@protocol_text,'')<>''  --- Если ошибка выполнения в хранике  dbo.SMETA_SMART_SYNC
					BEGIN
						SET @MSG = 'Операция передачи информации об удалении в ПК Смета-Смарт не выполнена' + CHAR(13) + CHAR(10) + ''+@protocol_text+'' 
						raiserror(@MSG,11,0)	
						RETURN 
					END				
				 END	
				 DROP TABLE #SYNC_TABLE
			END
		END	
		IF EXISTS( SELECT * FROM dbo.GP_EXCH_STATUS GS 
		           WHERE GS.LINK_GP in (Select   LINK  from DELETED))
		
		BEGIN
			DELETE FROM dbo.GP_EXCH_STATUS 
			where
			link_GP IN (Select   link from DELETED )
		
	
		END

			INSERT INTO dbo.SALDO_CHANGES([DATE], [ACCOUNT])
				SELECT G.[DATE_PROV], AP.ACCOUNT
					FROM deleted G, dbo.G_PROV1 G1, dbo.G_PROV2 G2, dbo.G_PROV_AP AP
					WHERE G.DATE_PROV IS NOT NULL AND G1.LINK_UP = G.LINK AND G2.LINK_UP = G1.LINK AND AP.LINK_UP = G2.LINK
			EXECUTE dbo.X_Saldo_CommitChanges
			UPDATE dbo.FIN_RR SET [LINK_REESTR]=null WHERE [LINK_REESTR] IN (SELECT [LINK] FROM DELETED) 
			UPDATE dbo.G_PROV_REF SET [DOC_REF_FOREIGN]=null WHERE [DOC_REF_FOREIGN] IN (SELECT [LINK] FROM DELETED) 
			DELETE FROM dbo.G_PROV1 WHERE [LINK_UP] IN (SELECT [LINK] FROM DELETED)
			DELETE FROM dbo.GZ_PLAN_TABLE WHERE [LINK_UP] IN (SELECT [LINK] FROM DELETED)
			DELETE FROM dbo.OUT_TABLE_INVOICE_COR WHERE [DOC_LINK] IN (SELECT [LINK] FROM DELETED)
			UPDATE dbo.RP_OPERATION SET [PKO_LINK]=null WHERE [PKO_LINK] IN (SELECT [LINK] FROM DELETED) 
		
	END


GO

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

GO
CREATE TRIGGER dbo.G_PROV2_XDELETE ON G_PROV2
FOR DELETE 
AS
  IF @@ROWCOUNT>0
	BEGIN
		
		
		IF convert(int, dbo.sa_get_option_by_code('SAL_OPT_INTEGR_CHANAL')) <> 0 AND  convert(tinyint,dbo.sa_get_option_by_code('SAL_OPT_INTEGR_PROV_ZP_EXP')) = 1
		BEGIN
			DECLARE @CHANAL_LINK INT, 
				@PROV_ZP_EXP TINYINT ,
				@OBJECT varchar(50)
				
			SET @CHANAL_LINK =  (select convert(int, dbo.sa_get_option_by_code('SAL_OPT_INTEGR_CHANAL')))
			SET @PROV_ZP_EXP = (SELECT convert(tinyint,dbo.sa_get_option_by_code('SAL_OPT_INTEGR_PROV_ZP_EXP')))
			IF @PROV_ZP_EXP = 1 
			BEGIN
				SET @OBJECT = 'DOCUMENTS_SALARY' 	
				
				/* СОЗДАЕМ ВРЕМЕНННУЮ ТАБЛИЦУ */

				------------------------------- ВЫБИРАЮТСЯ ВСЕ ЛИНКИ УДАЛЯЕМЫХ ПРОВОДОК ИЗ ЖУРНАЛА и  закидываются в буфер  ------------
			
				----------В этой таблице будут лежать GUID на удаляемые проводки --------------
				DECLARE @SYNC_TABLE1 VARCHAR(20),
						@SQLText NVARCHAR(1000),
						@MSG VARCHAR(500),
						@iERROR INT
				EXEC DBO.X_GET_TABLE_NAME @SYNC_TABLE1 OUTPUT
				
							
				CREATE TABLE #SYNC_TABLE (ID int IDENTITY(1,1), F_NAME VARCHAR(254), XML_DATA TEXT)
				INSERT INTO #SYNC_TABLE  ( F_NAME, XML_DATA)
				SELECT  '', OUT_TEXT = CONVERT( TEXT, CONVERT(VARCHAR(36), G.GUID)) 
				from dbo.G_PROV G 
					inner join dbo.G_PROV1 G1  on G.LINK = G1.LINK_UP 
				WHERE G1.LINK IN (Select   LINK_UP  from DELETED)/* AND G.object = (SELECT link FROM s_objects WHERE code = 'DOCUMENTS_SALARY' )*/
				
				IF (SELECT COUNT(*) FROM #SYNC_TABLE ) > 0
				BEGIN
									
					SET @SQLText = ''
					SET @SQLText = 'SELECT * INTO '+@SYNC_TABLE1+' from #SYNC_TABLE'
					exec sp_executesql @SQLText 
			
					-----------------------	
					-------Выгрузка/удаление в Смету-Смарт
					DECLARE @Protocol_Text VARCHAR(8000),
							@CH_LINK VARCHAR(10)
		
					SET @CH_LINK = @CHANAL_LINK	
					SET @SQLtext = ''
					SET @SQLText = '  EXEC  @iERROR =  dbo.SMETA_SMART_SYNC ''' + @SYNC_TABLE1 + ''', '+ @CH_LINK +','''+@OBJECT+''',1 ,@protocol_text output '
					exec sp_executesql @SQLText, N'@protocol_text varchar(8000) output, @iERROR int output', @protocol_text = @protocol_text OUTPUT, @iERROR = @iERROR OUTPUT
					SET @MSG = ''	
					
					IF @iERROR <> 0 OR ISNULL(@protocol_text,'')<>''  --- Если ошибка выполнения в хранике  dbo.SMETA_SMART_SYNC
					BEGIN
						SET @MSG = 'Операция передачи информации об удалении в ПК Смета-Смарт не выполнена' + CHAR(13) + CHAR(10) + ''+@protocol_text+'' 
						raiserror(@MSG,11,0)	
						RETURN 
					END				
				 END	
				 DROP TABLE #SYNC_TABLE
			END
		END	
		IF EXISTS( SELECT * FROM dbo.GP_EXCH_STATUS GS 
						inner join dbo.G_PROV G on GS.LINK_GP = G.LINK 
						inner join dbo.G_PROV1 G1  on G.LINK = G1.LINK_UP 
						WHERE G1.LINK IN (Select   LINK_UP  from DELETED)
						AND G.object = (SELECT link FROM s_objects WHERE code = 'DOCUMENTS_SALARY' ))
		
		BEGIN
			DELETE FROM GP_EXCH_STATUS 
			where
			link_GP IN (Select   G.LINK  FROM dbo.G_PROV G 
										inner join dbo.G_PROV1 G1  on G.LINK = G1.LINK_UP
										 WHERE G1.LINK IN (Select   LINK_UP  from DELETED)
										 AND G.object = (SELECT link FROM s_objects WHERE code = 'DOCUMENTS_SALARY' ) )
		END

		INSERT INTO dbo.SALDO_CHANGES([DATE], [ACCOUNT])
		SELECT G.[DATE_PROV], AP.ACCOUNT
			FROM dbo.G_PROV G, dbo.G_PROV1 G1, deleted G2, dbo.G_PROV_AP AP
			WHERE G.DATE_PROV IS NOT NULL AND G1.LINK_UP = G.LINK AND G2.LINK_UP = G1.LINK AND AP.LINK_UP = G2.LINK
		DELETE FROM dbo.G_PROV_AP WHERE [LINK_UP] IN (SELECT [LINK] FROM DELETED)
		DELETE FROM dbo.G_PROV_DVZ WHERE [LINK_UP] IN (SELECT [LINK] FROM DELETED)
		UPDATE dbo.G_PROV2 SET [LINK_SELF]=null WHERE [LINK_SELF] IN (SELECT [LINK] FROM DELETED) 
		UPDATE dbo.JURN_BO SET [LINK_PO_PROV]=null WHERE [LINK_PO_PROV] IN (SELECT [LINK] FROM DELETED) 


	END



GO


GO



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

GO

CREATE      
VIEW dbo.DOCUMENTS_ADVANCE_CASH
AS
  SELECT  
    G.LINK,
    G.NUMBER,
    [SUMMA] = ISNULL(dbo.CalcDocSumma(G.LINK), G.SUMMA),
    G.COMMENT,
    G.DATE, 
    G.DATE_PROV,
    [FLAG_JC] = CASE WHEN DATE_PROV IS NULL THEN 0 ELSE 1 END,


  [DEP_LINK]  = D.LINK,
  [DEP_CODE]  = CONVERT(VARCHAR(10), D.CODE),
  [DEP_NAME]  = CONVERT(varchar(100),D.NAME),
  [ACC_LINK]  = DA.LINK,
  [ACC_CODE]  = DA.CODE,
  [ACC_NAME]  = CONVERT(varchar(80), DA.ANAME),    
  
  [ACC_LINK_V]  =  DAV.LINK,
  [ACC_CODE_V]  =  DAV.CODE,   
  [ACC_NAME_V]  =  DAV.ANAME,    

  [EKR_CODE]= CONVERT(CHAR(3),  (SELECT CODE FROM dbo.KOSGU as D WITH (NOLOCK), dbo.G_PROV_SGU GPSGU WHERE GPSGU.DOC_LINK = G.LINK AND GPSGU.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'ADVANCE_CASH_EKR_LINK') AND D.LINK = GPSGU.SGU)),
  [EKR_LINK]=   (SELECT GPSGU.SGU FROM dbo.G_PROV_SGU GPSGU WHERE GPSGU.DOC_LINK = G.LINK AND GPSGU.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'ADVANCE_CASH_EKR_LINK')),
  [EKR_NAME]= CONVERT(VARCHAR(60),  (SELECT NAME FROM dbo.KOSGU as D WITH (NOLOCK), dbo.G_PROV_SGU GPSGU WHERE GPSGU.DOC_LINK = G.LINK AND GPSGU.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'ADVANCE_CASH_EKR_LINK') AND D.LINK = GPSGU.SGU)),
  [EMP_CODE]= CONVERT(VARCHAR(10), (SELECT TAB FROM dbo.EMPL as D WITH (NOLOCK), dbo.G_PROV_EMPL GPE WHERE GPE.DOC_LINK = G.LINK AND GPE.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'ADVANCE_CASH_EMP_LINK') AND D.LINK = GPE.EMPL)),
  [EMP_LINK]=   (SELECT GPEM.EMPL FROM dbo.G_PROV_EMPL GPEM WHERE GPEM.DOC_LINK = G.LINK AND GPEM.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'ADVANCE_CASH_EMP_LINK')),
  [EMP_NAME]= CONVERT(varchar(50),  (SELECT dbo.sd_GetEmplName (GPE.EMPL) FROM dbo.G_PROV_EMPL GPE WHERE GPE.DOC_LINK = G.LINK AND GPE.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'ADVANCE_CASH_EMP_LINK'))),
  [DOC_LINK]=   (SELECT doc_ref_foreign FROM dbo.G_PROV as GR WITH (NOLOCK) INNER JOIN dbo.G_PROV_REF GPR WITH (NOLOCK) ON GPR.DOC_REF_PRIMARY = G.LINK AND GPR.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'ADVANCE_CASH_RKO') AND GR.LINK = GPR.DOC_REF_FOREIGN),
  [SOURCE] = CONVERT(VARCHAR(254), (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'ADVANCE_CASH_SOURCE'))),
  [VKR_CODE]= CONVERT(VARCHAR(30),  (SELECT CODE FROM dbo.KL_KBK as D WITH (NOLOCK), dbo.G_PROV_KBK GPKBK WHERE GPKBK.DOC_LINK = G.LINK AND GPKBK.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'ADVANCE_CASH_VKR_LINK') AND D.LINK = GPKBK.KBK)),
  [VKR_LINK]=   (SELECT GPKBK.KBK FROM dbo.G_PROV_KBK GPKBK WHERE GPKBK.DOC_LINK = G.LINK AND GPKBK.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'ADVANCE_CASH_VKR_LINK')),
  [VKR_NAME]= CONVERT(VARCHAR(60),  (SELECT NAME FROM dbo.KL_KBK as D WITH (NOLOCK), dbo.G_PROV_KBK GPKBK WHERE GPKBK.DOC_LINK = G.LINK AND GPKBK.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'ADVANCE_CASH_VKR_LINK') AND D.LINK = GPKBK.KBK)),
  [SYMBOL] = CONVERT(VARCHAR(6), (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'ADVANCE_CASH_SYMBOL')))


  FROM dbo.G_PROV as G WITH (NOLOCK)
  left join dbo.DEPARTMENTS D on D.LINK = G.DEP
  left join dbo.DICTIONARY_ACCOUNTS DA on DA.LINK = G.ACC
  left join dbo.G_PROV_DEP_ACCT GDA on GDA.DOC_LINK = G.LINK and exists(select * from dbo.S_OBJECTS SO where SO.LINK = GDA.OBJECT and SO.CODE = 'ADVANCE_CASH_ACC_LINK_V')
  left join dbo.DICTIONARY_ACCOUNTS DAV on DAV.LINK = GDA.ACCOUNT
  
  WHERE G.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOCUMENTS_ADVANCE_CASH')


GO


GRANT SELECT ON dbo.[DOCUMENTS_ADVANCE_CASH] TO PUBLIC

GO


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

GO


CREATE VIEW dbo.KD_VACATION_VID
AS
SELECT 
	[LINK] 		= 	V.LINK,
	[CODE]		= 	V.CODE,
	[NAME]		=	V.NAME,
	[TYPE_LINK]	=	V.TYPE_LINK,	
	[TYPE_NAME]	=	(SELECT NAME FROM dbo.TYP_DAYS WHERE LINK = V.TYPE_LINK),
	[LINK_PAYS]	=	V.LINK_PAYS,
	[CODE_PAYS]	=	(SELECT CODE FROM dbo.PAYS WHERE LINK = V.LINK_PAYS),
	[NAME_PAYS]	=	(SELECT NAME FROM dbo.PAYS WHERE LINK = V.LINK_PAYS),
	[PERIOD1]	=	V.PERIOD1,
	[BonusTakeTime] = 	COALESCE(V.BonusTakeTime,0), /*Учитывать время при расчете премии*/
	[BonusTakeTimeC]=	(Case when COALESCE(V.BonusTakeTime,0) = 0 then '' else 'Вкл.' end),
	[Time_Arche]	= 	COALESCE(V.Time_Arche,0), /*Учитывать время при расчете календарных дней в расчете больничных*/
	[Time_ArcheC]	=	(Case when COALESCE(V.Time_Arche,0) = 0 then '' else 'Вкл.' end),
	[NO_SAL] 	= 	COALESCE(V.NO_SAL,0), /*Отпуск без сохранения заработной платы*/
	[NO_SALC]	=	(Case when COALESCE(V.NO_SAL,0) = 0 then 'Опл.' else 'Не опл.' end),
	[CHILDREN] 	= 	case when WORK_D = 7 then 1 else 0 end, /*Перерыв - Уход за ребенком до 1,5 и до 3 лет*/
	[CHILDRENC]	=	case when WORK_D = 7 then 'Дети' else '' end,
	[HOLIDAY]	=	COALESCE(V.HOLIDAY,0), /*Учитывать праздничные дни в отпусках*/
	[HOLIDAYC]	=	(Case when COALESCE(V.HOLIDAY,0) = 0 then 'Не учит.' else 'Учит.' end),
	[EDUC] = case when WORK_D = 5 then 1 else 0 end,
	[EDUCC] = case when WORK_D = 5 then 'ОУ' else '' end,
	[ADM] = COALESCE(ADM,0),
	[ADMC] = CASE WHEN COALESCE(ADM,0) = 1 THEN 'Адм.' ELSE '' END,
	[NOT_LGOT_EXPIR] = COALESCE(NOT_LGOT_EXPIR,0),
	[NOT_LGOT_EXPIRC] = CASE WHEN COALESCE(NOT_LGOT_EXPIR,0) = 1 THEN 'Не вкл.' ELSE '' END,
	[IS_DOP]   = ISNULL(LTRIM(RTRIM(v.IS_DOP)),''),
	[N_IS_DOP] = ISNULL((SELECT TOP 1 RTRIM(LTRIM(NAME)) FROM dbo.SA_SZV4_SPR WHERE SPR_CODE = 'ISCHISL_STAZH_DOP_SV' AND CODE = ISNULL(LTRIM(RTRIM(v.IS_DOP)),'')),''),
	[VAC_V] = v.VAC_V /*CASE WHEN COALESCE(V.ADM,0) = 1 THEN 1
				   WHEN COALESCE(V.ADM,0) = 0 
						AND COALESCE(D.WORK_D,0) NOT IN (5,7) 
						AND ( D.NAME LIKE '%дополн%отпуск%'	
							  OR D.NAME LIKE '%отпуск%дополн%' 
							  OR D.NAME LIKE '%доп.%отп.%' 
							  OR D.NAME LIKE '%отп.%доп.%' )
						AND ( v.Name LIKE '%дополн%отпуск%'	
							  OR v.Name  LIKE '%отпуск%дополн%' 
							  OR v.NAME LIKE '%доп.%отп.%' 
							  OR v.NAME LIKE '%отп.%доп.%')
						/*AND (V.LINK_PAYS = (SELECT TOP 1 link 
						                   FROM PAYS p 
											WHERE p.way_calc = 15 
											AND (p.NAME LIKE '%дополн%отпуск%' 
													OR p.NAME LIKE '%отпуск%дополн%' ))
								OR  V.LINK_PAYS IS NULL)
							*/  			
				   THEN 2
				   WHEN COALESCE(V.ADM,0) = 0 
						AND COALESCE(D.WORK_D,0) NOT IN (5,7,13) 
						AND ( D.NAME LIKE '%основн%отпуск%'	
							  OR D.NAME LIKE '%отпуск%основн%' 
							  OR D.NAME LIKE '%ежегодн%отпуск%'
							  OR D.NAME LIKE '%отпуск%ежегодн%'
							  OR D.NAME LIKE '%планов%отпуск%'
							  OR D.NAME LIKE '%отпуск%планов%')
						AND (v.Name LIKE '%основн%отпуск%' 
							  OR v.Name LIKE '%отпуск%основн%' 
							  OR v.Name LIKE '%ежегодн%отпуск%'
							  OR v.Name LIKE '%отпуск%ежегодн%'
							  OR v.Name LIKE '%планов%отпуск%'
							  OR v.Name LIKE '%отпуск%планов%'  )
						/*AND  V.LINK_PAYS = (SELECT TOP 1 link 
						                   FROM PAYS p 
											WHERE p.way_calc = 15 
											AND (p.NAME LIKE '%основн%отпуск%' 
													OR p.NAME LIKE '%отпуск%основн%' 
													OR p.NAME LIKE '%ежегодн%отпуск%'
													OR p.NAME LIKE '%отпуск%ежегодн%'
													OR p.NAME LIKE '%планов%отпуск%'
													OR p.NAME LIKE '%отпуск%планов%'  ))
														
			*/
				   THEN 3
 				   WHEN COALESCE(D.WORK_D,0) in(7,13) THEN 4
				   WHEN COALESCE(D.WORK_D,0) = 5 THEN 5
				  ELSE 0 end*/,
	[VAC_VC] = CASE COALESCE(v.VAC_V,0) 
					WHEN 1 THEN '1.Административный отпуск'
					WHEN 2 THEN '2.Дополнительный оплачиваемый отпуск' 
					WHEN 3 THEN '3.Основной оплачиваемый отпуск' 
					WHEN 4 THEN '4.Отпуск по уходу за ребенком' 
					WHEN 5 THEN '5.Учебный отпуск'  
					ELSE '0.Не определен' END	  
	FROM 
		dbo.VACATION_VID V 
		left join dbo.TYP_DAYS D on V.TYPE_LINK = D.LINK


GO


GRANT SELECT ON dbo.[KD_VACATION_VID] TO PUBLIC

GO


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

GO

/*
© Кейсистемс (Keysystems), 2005
ВОЗВРАЩАЕТ СПИСОК ВСЕХ СОТРУДНИКОВ НА ДАТУ, ВКЛЮЧАЯ УВОЛЕННЫХ
УВОЛЕННЫЕ ФИКСИРУЮТСЯ ПОЛЕМ "SACK"
*/

CREATE   FUNCTION dbo.KU_EMPL_PLACING_FN(@dDATE datetime = null)
RETURNS @RESULT TABLE
		( [LINK] INT,
		[PERS_LINK]	INT,
		[DEP_LINK] INT,
		[DEP_NAME] VARCHAR(254),
		[TAB] VARCHAR(10),
		[FM] VARCHAR(100),
		[IM] VARCHAR(100),
		[OT] VARCHAR(100),
		[FIO] VARCHAR(100),
		[NAME_EMPL] VARCHAR(100),
		[SUBDIV_HEAD] INT,
		[SUBDIV_LINK] INT,
		[SUBDIV_CODE] VARCHAR(5),
		[SUBDIV_NAME] VARCHAR(254),
		[POST_LINK] INT,
		[POST_CODE] VARCHAR(10),
		[POST_NAME] VARCHAR(254),
		[STAFF_HEAD] INT,
		[STAFF_LINK] INT,
		[NUM_STAKE] NUMERIC(3,2),
		[STATUS] INT,
		[STATUS_NAME] VARCHAR(60),
		[NOTWORK] tinyint,
		[DATE_BEGIN] DATETIME,
		[DATE_MOV] DATETIME,
		[OKLAD] NUMERIC(10,2),
		[GRAPH_LINK] INT,
		[GRAPH_NAME] VARCHAR(60),
		[DATE_SACK]	DATETIME,
		[ITEM_MOVE_LINK] INT,
		[VIS] BIT,
		[LINK_KBK] INT,
		[CODE_KBK] VARCHAR(30),
		[NAME_KBK] VARCHAR(120),
		[RAZR] TINYINT,
		[SYST_PAY] TINYINT,
		[POST_GROUP] VARCHAR(60),
		KATEG VARCHAR(50),
		[CHIN] VARCHAR(150),
		[CHIN_DATE] DATETIME,
		[EMAIL] VARCHAR(254),
		[PHONE_WORK] VARCHAR(254),
		[PHONE_MOB] VARCHAR(254),
		[INN] VARCHAR(12),
		[SNILS] VARCHAR(14),
		[RESIDENT]	tinyint,
		[RESIDENT_N] VARCHAR(34),
		[SACK] INT,
		[SACK_PER] INT) 
AS
BEGIN
SET @dDATE = Isnull(@dDATE,(SELECT workdate FROM user_dates))

-- Сведения о чине --------------------------------------------------------------------------------------
DECLARE @CHIN_EMPL TABLE(EMPL_LINK INT, CHIN_CODE VARCHAR(2), CHIN_NAME VARCHAR(150), CHIN_DATE DATETIME)
---------------------------------------------------------------------------------------------------------
INSERT INTO @CHIN_EMPL (EMPL_LINK, CHIN_CODE, CHIN_NAME, CHIN_DATE)
SELECT EMPL_LINK, CODE, [NAME], DATE
FROM  dbo.EMPL_CHIN ch1 inner join dbo.DICTIONARY_CHIN dh ON  ch1.chin_link = dh.link
WHERE  ch1.[DATE] = 
				(SELECT TOP 1 C.DATE 
				 FROM dbo.EMPL_CHIN C 
				 WHERE C.EMPL_LINK = ch1.EMPL_LINK AND C.DATE <= @dDATE 
				 ORDER BY DATE DESC)	

-- Сведения о текушей должности -------------------------------------------------------------------------
DECLARE @POST_EMPL TABLE(EMPL_LINK INT,STAFF_HEAD INT,STAFF_LINK INT, NUM_STAKE NUMERIC(3,2), [STATUS] INT, OKLAD NUMERIC(10,2),
						 MOVE_LINK INT, LINK_KBK INT, POST_LINK INT, SUBDIV_LINK INT, DATE_BEG DATETIME)
---------------------------------------------------------------------------------------------------------
INSERT INTO @POST_EMPL (EMPL_LINK, STAFF_HEAD, STAFF_LINK, NUM_STAKE, [STATUS], OKLAD, MOVE_LINK, LINK_KBK,POST_LINK,SUBDIV_LINK, DATE_BEG)
SELECT A.EMPL_LINK, A.STAFF_HEAD, A.STAFF_LINK, A.NUM_STAKE, A.[STATUS], A.OKLAD, A.MOVE_LINK, A.LINK_KBK,A.POST_LINK,A.SUBDIV_LINK, A.DATE_BEGIN
FROM dbo.EMPL_STAFF(@dDATE) A

-- Сведения об увольнении -------------------------------------------------------------------------------
DECLARE @ITEM_DIS_FACE TABLE(EMPL_LINK int, DIS_DATE DATETIME)
---------------------------------------------------------------------------------------------------------
INSERT INTO @ITEM_DIS_FACE (EMPL_LINK,DIS_DATE)
SELECT empl_link, dis_date 
FROM dbo.item_dis_face IDF
WHERE dis_date =
	(SELECT TOP 1 dis_date 
	 FROM dbo.item_dis_face IDF1 
	 WHERE IDF1.EMPL_LINK = IDF.EMPL_LINK AND active =1 AND dis_date <=@dDATE 
	 ORDER BY dis_date desc)

-- Сведения о телефонах, эл.адресах сотрудников ---------------------------------------------------------
DECLARE @PHONE_MAIL_EMPL TABLE(EMPL_LINK INT, [EMAIL] VARCHAR(254), [PHONE_WORK] VARCHAR(254), [PHONE_MOB] VARCHAR(254))
---------------------------------------------------------------------------------------------------------
INSERT INTO @PHONE_MAIL_EMPL(EMPL_LINK, [EMAIL], [PHONE_WORK],[PHONE_MOB])
SELECT EMPL_LINK, EMAIL, CITY_NUMBER, MOB_NUMBER FROM dbo.EMPL_PHONE_STR

-- Заполнение результирующей таблицы --------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------
INSERT INTO @RESULT([LINK],
		[PERS_LINK],		[DEP_LINK],		[DEP_NAME],
		[TAB],		[FM],	[IM],	[OT],	[FIO],
		[NAME_EMPL],		[SUBDIV_HEAD],	[SUBDIV_LINK],
		[SUBDIV_CODE],		[SUBDIV_NAME],	[POST_LINK],
		[POST_CODE],		[POST_NAME],	[STAFF_HEAD],
		[STAFF_LINK],		[NUM_STAKE],	[STATUS],
		[STATUS_NAME],		[NOTWORK],		[DATE_BEGIN], [DATE_MOV],
		[OKLAD],			[GRAPH_LINK],	[GRAPH_NAME],
		[DATE_SACK],		[ITEM_MOVE_LINK],		[VIS],
		[LINK_KBK], 		[CODE_KBK], 	[NAME_KBK],
		[RAZR],				[SYST_PAY],		[POST_GROUP], [KATEG],
		[CHIN],				[CHIN_DATE],	[EMAIL],
		[PHONE_WORK],		[PHONE_MOB],	[INN],
		[SNILS],			[RESIDENT],			[RESIDENT_N],		
		[SACK],			[SACK_PER])
SELECT	distinct
	T.*,
	CASE
		WHEN datediff(day,T.DATE_SACK, @dDATE) > 0  THEN 1
		ELSE 0
	END AS SACK,
	CASE
		WHEN YEAR(T.DATE_SACK) = YEAR(@dDATE)
		     AND MONTH(T.DATE_SACK) = MONTH(@dDATE) THEN 1
		ELSE 0
	END AS SACK_PER
FROM	(
	SELECT 
		[LINK] 			= 	E.LINK, 
		[PERS_LINK]		= 	P.LINK, 
		[DEP_LINK]		= 	E.DEP_LINK,
		[DEP_NAME]		=	DEP.NAME,
		[TAB]			= 	E.TAB,
		[FM]			= 	P.FM,
		[IM]			= 	P.IM, 
		[OT]			=	P.OT,
		[FIO]			=	LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(FM)) + ' ' + LTRIM(RTRIM(IM)) + ' ' + LTRIM(RTRIM(OT)),'Не заполнено'))),100),
		[NAME_EMPL]		= 	LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(FM)) + ' ' + LEFT(LTRIM(RTRIM(IM)),1) + '.' + LEFT(LTRIM(RTRIM(OT)),1) + '.', 'Не заполнено'))),30),
		[SUBDIV_HEAD]	=	DS.link_up,
		[SUBDIV_LINK]	=	DS.LINK,
		[SUBDIV_CODE]	=	DS.CODE,
		[SUBDIV_NAME]	=	DS.NAME,
		[POST_LINK]		=	DP.LINK,
		[POST_CODE]		=	DP.CODE,
		[POST_NAME]		=	DP.NAME,
		[STAFF_HEAD]	=	PE.STAFF_HEAD,
		[STAFF_LINK]	= 	PE.STAFF_LINK,
		[NUM_STAKE]		=	PE.NUM_STAKE,
		[STATUS]		=	PE.[STATUS],
		[STATUS_NAME]	=	CASE WHEN PE.[STATUS] = 1 THEN 'Основной' WHEN PE.[STATUS] = 2 THEN 'Совместитель' WHEN PE.[STATUS] = 3 THEN 'Внешний совместитель' END,
		[NOTWORK]		=	E.NOTWORK,
		[DATE_BEGIN]	=	IM.DATE_BEGIN,
		[DATE_MOV]		=	PE.DATE_BEG,
		[OKLAD]			=	PE.oklad,
		[GRAPH_LINK]	= 	G.LINK,
		[GRAPH_NAME]	=	G.NAME,
		[DATE_SACK]		=	IDF.DIS_DATE,
		[ITEM_MOVE_LINK] =	PE.MOVE_LINK,
		[VIS]			=	CONVERT(bit, 0),
		LINK_KBK		=	KBK.LINK,
		CODE_KBK		=	KBK.CODE,
		NAME_KBK		=	KBK.NAME,
		RAZR			=	COALESCE(IM.ETS_RAZR,0),
		[SYST_PAY]		=	E.SYST_PAY,		
		[POST_GROUP]	=	GR.NAME,
		[KATEG]			=	KAT.NAME,
		[CHIN]			=	CE.CHIN_NAME,
		[CHIN_DATE]		=	CE.CHIN_DATE,		
		[EMAIL]			=	PME.[EMAIL] ,
		[PHONE_WORK]	=	PME.[PHONE_WORK],
		[PHONE_MOB]		=	PME.[PHONE_MOB],
		[INN]			=	P.INN,
		[SNILS]			=	P.INSUR_NUM,
		[RESIDENT]		= 	 (CASE WHEN P.RESIDENT = 0 then 1 when P.RESIDENT = 1 then 2 else 3 END),
		[RESIDENT_N]	= 	 (CASE WHEN P.RESIDENT = 0 then 'Нерезидент (временно проживающий)' when P.RESIDENT = 1 then 'Резидент' else 'Нерезидент (постоянно проживающий)' END)	

	FROM			dbo.EMPL		E
		INNER JOIN	dbo.PERSON 			P	 ON e.pers_link=p.link
		LEFT JOIN	dbo.GRAPH			G	 ON e.graph_link=g.link
		LEFT JOIN	@POST_EMPL		PE	 ON E.LINK = PE.EMPL_LINK
		LEFT JOIN	dbo.SAL_SFIN		KBK	 ON KBK.LINK = PE.LINK_KBK		
		LEFT JOIN	dbo.SUBDIV			DS	 ON PE.subdiv_link = DS.LINK
		LEFT JOIN	dbo.POST			DP	 ON PE.post_link = DP.LINK
		LEFT JOIN	dbo.ITEM_MOVE		IM	 ON IM.ACTIVE = 1 AND IM.NEW_FACE = 1 AND IM.EMPL_LINK = E.LINK
		LEFT JOIN	dbo.DEPARTMENTS		DEP	 ON E.DEP_LINK = DEP.LINK
		LEFT JOIN	dbo.ITEM_MOVE	SE	 ON E.LINK = SE.EMPL_LINK AND @dDATE between SE.date_begin and SE.date_end and SE.active=1
		LEFT JOIN	@ITEM_DIS_FACE	IDF	 ON E.LINK = IDF.EMPL_LINK
		LEFT JOIN	@CHIN_EMPL		CE	 ON E.LINK = CE.EMPL_LINK
		LEFT JOIN   @PHONE_MAIL_EMPL PME ON E.LINK = PME.EMPL_LINK
		LEFT JOIN	dbo.STAFF ST ON ST.LINK = PE.STAFF_LINK
		LEFT JOIN	dbo.GR_GOS GR ON GR.LINK = ST.GR_GOS_LINK
		LEFT JOIN   DBO.KAT_GOS KAT ON KAT.LINK = ST.KAT_GOS_LINK
		--LEFT JOIN	dbo.KATEG KAT ON KAT.LINK = ST.KAT_LINK

	) T

RETURN
END



GO


GRANT SELECT ON dbo.[KU_EMPL_PLACING_FN] TO PUBLIC

GO


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


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

GO


/*
© Кейсистемс (Keysystems), 2005
*/
CREATE VIEW [dbo].KD_HOLIDAYS
AS
SELECT 
	H.LINK,
	H.NAME,
	H.[DAY],
	H.[MONTH], 
	[DATE] = dbo.ConvertDMY2Date(H.[DAY],H.[MONTH],H.[YEAR]),
	H.[TD_LINK],
	TD.[NAME] AS TD_NAME,
	TD.WORK_D,
	ORD = 1,-- + (Select count(LINK) from dbo.HOLIDAYS H1 where (10000 + H1.[month] * 100 + H1.[day]) < (10000 + H.[month] * 100 + H.[day]) ),
	H.TYPE_HOL,
	CASE WHEN H.TYPE_HOL = 1 THEN 'Нерабочий праздничный в РФ'
	     WHEN H.TYPE_HOL = 2 THEN 'Предпраздничный'
	     WHEN H.TYPE_HOL = 3 THEN 'Дополнительный день отдыха'
	END as TYPE_HOL_STR,
	H.[DAY1], -- перенос с этого дня
	H.[MONTH1], -- перенос с этого дня
	[DATE1] = dbo.ConvertDMY2Date(H.[DAY1],H.[MONTH1],H.[YEAR]),
	H.[YEAR]
FROM dbo.HOLIDAYS H LEFT OUTER JOIN dbo.TYP_DAYS TD ON H.TD_LINK = TD.LINK


GO


GRANT SELECT ON dbo.[KD_HOLIDAYS] TO PUBLIC

GO



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

GO

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

-- ИСПОЛЬЗУЕТСЯ ДЛЯ ЖУРНАЛА ПРОВОДОК ПО ЗАДАЧЕ
--	Журнал операций (Группа ХО завсисит от настроек пользователя)
--		@intLINK_PAR: 
--			1. NULL	- вывести все проводки по задаче
--			2. -1	- вывести проводки, у которых не указан ЖО (ХО)
--			3. вывести проводки, по заданному журналу (Группе ХО)
--
CREATE FUNCTION dbo.XK_USER_PROV (@intLINK_PAR INT = NULL,
				@ENABLE_ZB TINYINT = 1)
RETURNS @RETURN_TABLE TABLE 
	(
		[FLAG_JC]	[TINYINT],
		[DOC_LINK] 	[INT],
		[DATEDOC]	[DATETIME],
		[DATE_PROV]	[DATETIME],
		[NUMDOC]	[CHAR] (30),
		[KINDDOC] 	[VARCHAR] (254),
		[ORDER1] 	[INT],
		[LINK]		[INT],
		[SUMMA] 	[NUMERIC] (19,2),
		[QUANTITY]	[NUMERIC] (19,4),
		[COMMENT]	[VARCHAR] (254),
		[ORDER2] 	[INT],
		[DEB_CODE] 	[VARCHAR] (20),
		[CRE_CODE] 	[VARCHAR] (20),
		[KBK_CODE] 	[VARCHAR] (30),
		[EKR_CODE] 	[VARCHAR] (10),
		[DCL_CODE] 	[VARCHAR] (10),
		[DEP_NAME] 	[VARCHAR] (254),
		[SUB_NAME] 	[VARCHAR] (254),
		[EMP_CODE] 	[VARCHAR] (10),
		[EMP_NAME] 	[VARCHAR] (30),
		[DKAU_CODE] 	[VARCHAR] (20),
		[KKAU_CODE] 	[VARCHAR] (20),
		[NOMEN_CODE]	[VARCHAR] (20),
		[NOMEN_NAME]	[VARCHAR] (254),
		[DEP_ACC_CODE] 	[VARCHAR] (20),
		[INV_CODE] 	[VARCHAR] (20),
		[INV_NAME] 	[VARCHAR] (254),
		[TMC_NAME] 	[VARCHAR] (254),
		[DT_DATE] 	[DATETIME],
		[KT_DATE] 	[DATETIME],
		[NUMBERMO]  	[VARCHAR] (20),
		[JO]		[INT],
		[XO_GROUP]	[INT],
		[KIND_HO]	[VARCHAR] (254),
		[OBJECT]	[INT],
		[NAME_OPER]	[VARCHAR] (254),
		[DEB_NAME] 	[VARCHAR] (254),
		[CRE_NAME] 	[VARCHAR] (254),
		[LINK_DEP]	[INT],
		[STATUS_EXCH] [INT],
		[STATUS_EX_DATE] [DATETIME],
		[ST_EX_COMMENT] VARCHAR(800)
	)
AS 
BEGIN
	DECLARE @intDEP_LINK		INT,
		@intUSER_PROV_MODE	INT,
		@intEXCLUDE_DOC	INT

	SET @intDEP_LINK = dbo.BK_GetDepZB ()

	SELECT @intUSER_PROV_MODE = CONVERT (INT, S_OPT.VALUE)
	FROM S_OBJECTS SO, S_OPTIONS S_OPT 
	WHERE SO.CODE = 'JURNAL_PROV_OPTIONS_XO_FILTER'
		AND SO.LINK = S_OPT.OBJECT
		AND S_OPT.SID = SUSER_SID()

	DECLARE @DEP_ACCESS TABLE (DEP_LINK INT)
	INSERT INTO @DEP_ACCESS
	SELECT D1.LINK FROM dbo.DEPARTMENTS D1
	WHERE (D1.[ZB] = 1 OR D1.[TYPE] = 4) AND dbo.xu_GetAccessByDep (D1.LINK) > 0

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

	SELECT @intUSER_PROV_MODE = ISNULL (@intUSER_PROV_MODE, 0)

	INSERT INTO @RETURN_TABLE
	SELECT 	[FLAG_JC]	=  (CASE WHEN G.DATE_PROV IS NULL THEN 0 ELSE 1 END),
			[DOC_LINK] 	= 	G.LINK,
			[DATEDOC]	=	G.DATE,
			[DATE_PROV]	= 	G.DATE_PROV,
			[NUMDOC]	=	G.NUMBER,
			[KINDDOC] 	=	CASE WHEN N.KINDDOC = 1 
							THEN CONVERT (VARCHAR (254), dbo.JurnalProvGetDocKind(G.LINK, G.OBJECT)) ELSE NULL END,
			[ORDER1] 	= 	G1.ORDERS,
			[LINK]		=	G2.LINK,
			[SUMMA] 	= 	G2.SUMMA,
			[QUANTITY]	= 	G2.QUANTITY,
			[COMMENT]	=	CONVERT (VARCHAR (254), G2.NAME),
			[ORDER2] 	= 	G2.ORDERS,
			[DEB_CODE] 	= 	CONVERT (VARCHAR (20), LTRIM(RTRIM((D_SA.CODE))) + ISNULL(LTRIM(RTRIM('-' + D_SGU.CODE)), '')),
			[CRE_CODE] 	= 	CONVERT (VARCHAR (20), LTRIM(RTRIM((K_SA.CODE))) + ISNULL(LTRIM(RTRIM('-' + K_SGU.CODE)), '')),
			[KBK_CODE] 	= 	CONVERT (VARCHAR (30), AP_KBK.CODE),
			[EKR_CODE] 	= 	CONVERT (VARCHAR (10), AP_EKR.CODE),
			[DCL_CODE] 	= 	CONVERT (VARCHAR (10), AP_DCL.CODE),
			[DEP_NAME] 	= 	CONVERT (VARCHAR (254), AP_DEP.[NAME]),
			[SUB_NAME] 	= 	CONVERT (VARCHAR (254), AP_SUB.[NAME]),
			[EMP_CODE] 	= 	CONVERT (VARCHAR (10), AP_EMP.TAB),
			[EMP_NAME] 	=	CONVERT (VARCHAR (30), CASE WHEN N.EMP_NAME = 1
										THEN dbo.sd_GetEmplName(AP_EMP.LINK)
										ELSE NULL END),
			[DKAU_CODE]	=CONVERT (VARCHAR (20), D_KAU.CODE),
			[KKAU_CODE]	= CONVERT (VARCHAR (20), K_KAU.CODE),
			[NOMEN_CODE]	= CONVERT (VARCHAR (20), CASE WHEN N.NOMEN_CODE = 1 THEN AP_NOMEN.CODE ELSE NULL END),
			[NOMEN_NAME]	= CONVERT (VARCHAR (254), CASE WHEN N.NOMEN_NAME   = 1 THEN AP_NOMEN.[NAME] ELSE NULL END),
			[DEP_ACC_CODE] 	= CONVERT (VARCHAR (20), AP_DEP_ACC.CODE),
			[INV_CODE] 	= CONVERT (VARCHAR (20), CASE WHEN N.INV_CODE = 1 THEN AP_INV.CODE ELSE NULL END),
			[INV_NAME] 	= CONVERT (VARCHAR (254), CASE WHEN N.INV_NAME = 1 THEN AP_INV.[NAME] ELSE NULL END),
			[TMC_NAME] 	=  CONVERT (VARCHAR (254), CASE WHEN N.TMC_NAME = 1 THEN AP_TMC.[NAME] ELSE NULL END),
			[DT_DATE] 	= DT.[INDATE],
			[KT_DATE] 	= KT.[INDATE],
			[NUMBERMO]  	= CONVERT (VARCHAR (20), CASE WHEN N.NUMBERMO = 1 THEN JOUR_CODE ELSE NULL END),
			[JO]		= ISNULL(JO.LINK,-1),
			[XO_GROUP]	= ISNULL(XG.LINK,-1), 
			[KIND_HO]	=  CASE WHEN N.KIND_HO = 1 
							THEN CONVERT(VARCHAR(254),(XG.CODE+'.'+XO.CODE+' '+XO.NAME)) ELSE NULL END ,
			[OBJECT]= G.OBJECT,
			[NAME_OPER]= CONVERT (VARCHAR (254), G1.NAME_OPER),
			[DEB_NAME] 	= 	CONVERT (VARCHAR (254), D_SA.[NAME]),
			[CRE_NAME] 	= 	CONVERT (VARCHAR (254), K_SA.[NAME]),
			LINK_DEP	=	G.DEP, 
			[STATUS_EXCH] = GEX.[STATUS],
			[STATUS_EX_DATE] = GEX.[DATE],
			[ST_EX_COMMENT] = GEX.COMMENT
	FROM dbo.USER_DATES UI
		LEFT JOIN dbo.WHO_IS_WHO WW ON UI.SID = WW.SID
		LEFT JOIN dbo.NASTR_JURNAL_PROV_AP N ON N.USER_LINK = WW.USER_REF OR N.USER_LINK = 0 AND WW.USER_REF IS NULL
		LEFT JOIN dbo.G_PROV as G ON ((G.[DATE] BETWEEN UI.BEGINDATE AND UI.ENDDATE) OR
						(G.DATE_PROV BETWEEN UI.BEGINDATE AND UI.ENDDATE))
		INNER JOIN dbo.G_PROV1 as G1 ON G1.LINK_UP = G.LINK
		INNER JOIN dbo.G_PROV2 as G2 ON G2.LINK_UP = G1.LINK
		LEFT JOIN dbo.G_PROV_AP DT ON DT.LINK_UP = G2.LINK AND DT.DB_KR = 0
		LEFT JOIN dbo.G_PROV_AP KT ON KT.LINK_UP = G2.LINK AND KT.DB_KR = 1
		LEFT JOIN dbo.XOZ_OPER XO ON XO.LINK = G2.ECON_OPER
		LEFT JOIN dbo.XOZ_OPER_JURN XJ ON XJ.XOZ_LINK = XO.LINK
			AND ((@intUSER_PROV_MODE = 1 AND XJ.GK=1)
				OR (@intUSER_PROV_MODE = 0
					AND (@intLINK_PAR IS NOT NULL OR @intLINK_PAR IS NULL AND XJ.GK=1)))

		LEFT JOIN dbo.JOURNAL_OPERATION JO ON JO.LINK = XJ.JURN_LINK
		LEFT JOIN dbo.XOZ_OPER_GROUP XG ON XG.LINK = XO.GROUP_LINK
		
		-- АНАЛИТИКА --
		LEFT JOIN dbo.S_ACCOUNTS D_SA ON (D_SA.LINK = DT.ACCOUNT)
		LEFT JOIN dbo.S_ACCOUNTS K_SA ON (K_SA.LINK = KT.ACCOUNT)

		LEFT JOIN dbo.KOSGU D_SGU ON (D_SGU.LINK = DT.SGU)
		LEFT JOIN dbo.KOSGU K_SGU ON (K_SGU.LINK = KT.SGU)

		LEFT JOIN dbo.KL_KBK AP_KBK ON (AP_KBK.LINK = ISNULL(DT.KBK, KT.KBK))
		LEFT JOIN dbo.KOSGU AP_EKR ON (AP_EKR.LINK = ISNULL(DT.EKR, KT.EKR))
		LEFT JOIN dbo.DOP_CLASSIF AP_DCL ON (AP_DCL.LINK = ISNULL(DT.AP2, KT.AP2))

		LEFT JOIN dbo.DEPARTMENTS AP_DEP ON (N.DEP_NAME  = 1
				AND AP_DEP.LINK = dbo.JurnalProvGetDepLink(DT.DEP, KT.DEP))
		LEFT JOIN dbo.SUBDIV AP_SUB ON (N.SUB_NAME = 1
				AND AP_SUB.LINK = ISNULL(DT.SUB, KT.SUB))
		LEFT JOIN dbo.EMPL AP_EMP ON (N.EMP_CODE = 1
				AND AP_EMP.LINK = ISNULL(KT.EMP, DT.EMP))
		LEFT JOIN dbo.KAU D_KAU ON (N.DKAU_CODE = 1 
				AND D_KAU.LINK = DT.KAU)
		LEFT JOIN dbo.KAU K_KAU ON (N.KKAU_CODE = 1 
				AND K_KAU.LINK = KT.KAU)
		LEFT JOIN dbo.NOMENCLATURE AP_NOMEN ON (AP_NOMEN.LINK = ISNULL(DT.NOMEN , KT.NOMEN))
		LEFT JOIN dbo.DEPARTMENT_ACCOUNTS AP_DEP_ACC ON (N.DEP_ACC_CODE = 1
				AND AP_DEP_ACC.LINK = ISNULL(DT.DEP_ACC, KT.DEP_ACC))
		LEFT JOIN dbo.INVENTORY AP_INV ON (AP_INV.LINK = ISNULL(DT.INV, KT.INV))
		LEFT JOIN dbo.DICTION AP_TMC ON (AP_TMC.LINK = ISNULL (DT.TMC, KT.TMC))
		LEFT JOIN dbo.BK_TYPE_ECONOM_OPER EC_OPER ON (EC_OPER.LINK = G2.ECON_OPER)
		INNER JOIN @DEP_ACCESS DEP ON ((G.DEP = DEP.DEP_LINK)
			AND (@ENABLE_ZB = 0
				OR @intDEP_LINK IS NULL 
				OR G.DEP = @intDEP_LINK))
		LEFT JOIN dbo.GP_EXCH_STATUS GEX ON GEX.LINK_GP = G.LINK 		
	WHERE G.OBJECT <> @intEXCLUDE_DOC
/*		AND (@ENABLE_ZB = 0
			OR (@intDEP_LINK IS NULL AND G.DEP IN (SELECT DEP_LINK FROM @DEP_ACCESS))
			OR G.DEP = @intDEP_LINK)
*/		AND (@intLINK_PAR IS NULL
			OR (@intUSER_PROV_MODE = 0
				AND ((@intLINK_PAR > 0 AND JO.LINK = @intLINK_PAR) -- Условие ЖО
					OR (@intLINK_PAR = -1 AND JO.LINK IS NULL)))
			OR (@intUSER_PROV_MODE = 1
				AND ((@intLINK_PAR > 0 AND XG.LINK = @intLINK_PAR) -- Условие ХО
					OR (@intLINK_PAR = -1 AND XG.LINK IS NULL))))
	RETURN
END



GO


GRANT SELECT ON dbo.[XK_USER_PROV] TO PUBLIC

GO



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

GO

/*
© Кейсистемс (Keysystems), 2005
Соколов С.В. 
*/

CREATE VIEW dbo.BB_UVED_817_69N
AS
SELECT  G.LINK,
		G.NUMBER,
		G.COMMENT,
		G.DATE_PROV, 
		G.DATE,
		FLAG_JC		= CASE WHEN DATE_PROV IS NULL THEN 0 ELSE 1 END,
		DEP_LINK	= G.DEP,
		DEP_CODE	= D.CODE,
		DEP_NAME	= D.NAME,
		DEP_FNAME	= D.FULL_NAME,
		ACC_LINK	= G.ACC,
		ACC_CODE	= DA.CODE,   
		ACC_NAME	= DA.ANAME,  
		VED_CODE	= VED.CODE,
		BUDG_NAME	= BUDG.NAME,
		D.OKATO,
		D.OKTMO,
		PDEP_LINK	= PD.LINK,
		PDEP_CODE	= PD.CODE,
		PDEP_NAME	= PD.NAME,
		PBUDG_NAME	= PBUDG.NAME,
		PDEP_FNAME	= PD.FULL_NAME,
		OSN_LINK	= O.LINK,
		OSN_NUM		= O.NUMBER,
		OSN_TYPE	= O.TYPE,
		OSN_DATE	= O.DATE,
		OSN_COMMENT	= O.COMMENT,
		OSN_DOC		= O.DOC_LINK,
		PUNKT1		= CONVERT(int, (select gpv.value from G_PROV_VALUE gpv where gpv.doc_link=g.link and gpv.object=(select link from s_objects where code='BB_UVED_817_69N_P1')))
FROM dbo.G_PROV G WITH (NOLOCK)
inner join dbo.DEPARTMENTS D WITH (NOLOCK) on G.DEP = D.LINK
inner join dbo.DICTIONARY_ACCOUNTS DA WITH (NOLOCK) on G.ACC = DA.LINK
left join dbo.G_PROV_DEPARTMENT GPD WITH (NOLOCK) on GPD.DOC_LINK = G.LINK and GPD.OBJECT=(select LINK from dbo.S_OBJECTS where CODE = 'BB_UVED_817_69N_PDEP_LINK')
left join dbo.DEPARTMENTS PD WITH (NOLOCK) on PD.LINK = GPD.DEPARTMENT 
left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.LINK_bUDG = BUDG.LINK
left join dbo.KL_ADMIN_BS PVED WITH (NOLOCK) on PVED.LINK = PD.VED_LINK
left join dbo.KL_BUDG_TYPE PBUDG WITH (NOLOCK) on PVED.LINK_bUDG = PBUDG.LINK
left join dbo.G_PROV_OSNOV GPO WITH (NOLOCK) on GPO.DOC_LINK = G.LINK and GPO.OBJECT=(select LINK from dbo.S_OBJECTS where CODE = 'BB_UVED_817_69N_OSN_LINK')
left join dbo.BD_OSNOV O WITH (NOLOCK) on O.LINK = GPO.OSNOV
WHERE G.OBJECT=(SELECT LINK from dbo.S_OBJECTS WHERE CODE='BB_UVED_817_69N')



GO


GRANT SELECT ON dbo.[BB_UVED_817_69N] TO PUBLIC

GO


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

CREATE
VIEW dbo.DOCUMENTS_PAY
AS

 SELECT 	
		G.LINK,
		G.NUMBER,
		--SUMMA = case left(G.NUMBER,1) when 'Б' then ISNULL(dbo.CalcDocSummaOneProv(G.LINK), G.SUMMA) else ISNULL(dbo.CalcDocSumma(G.LINK), G.SUMMA) end,
		SUMMA = ISNULL(dbo.CalcDocSummaOneProv(G.LINK), G.SUMMA), --ISNULL(dbo.CalcDocSumma(G.LINK), G.SUMMA),
		SUMMA_NDS	= P.SUMMA_NDS,
		G.COMMENT,
		G.DATE, 
		G.DATE_PROV,
		DEP_LINK	=	G.DEP, -- для x_list_documents_zb
		FLAG_JC = CASE WHEN G.DATE_PROV IS NULL THEN 0 ELSE 1 END,

		--Плательщик		
		S_LINK	= G.DEP,
		S_CODE	= SD.CODE,
		S_BUDG	= SD.BUDG,
		S_INN =	SD.INN,
		S_KPP =	SD.KPP,
		S_NAME	= CONVERT(varchar(100),SD.NAME),
		S_FNAME = SD.FULL_NAME,
		
		-- Счет плательщика
		S_ACC_LINK	= G.ACC,
		S_ACC_NUM	= SA.CODE,		
		S_ACC_TYPE = SA.[TYPE],
		S_ANAME = SA.aname,
		SBANK_LINK = isnull(SA.REF_LINK_B,STA.BANK_LINK), 
		S_BIK = rtrim(isnull(SA.BANK_CODE,STA.BANK_CODE)), 
		S_BANK = rtrim(isnull(sA.BANK_FNAME,STA.BANK_FNAME)), 
		S_BANK_CITY = isnull(sA.BANK_CITY,STA.BANK_CITY), 
		S_BANK_FILIAL = isnull(SA.BANK_FILIAL,STA.FILIAL), 
		S_FBANK = isnull(SA.BANK_FNAME,STA.BANK_FNAME), 
		S_SCH_B = isnull(SA.BANK_KS,STA.BANK_KS),
		S_KAZN = SA.KAZN_NAME, 
		S_KAZN_CODE = SA.KAZN_CODE, 
		S_KAZN_INN = SA.KAZN_INN, 
		S_SCH_K = SA.K_ACC_CODE,
		S_SCH_K_LINK = SA.K_ACC_LINK,
		
		--Получатель
		D_LINK = DD.Link,
		D_CODE = DD.CODE,
		D_INN =	DD.INN,
		D_KPP =	DD.KPP,
		D_NAME = DD.NAME,
		D_FNAME = DD.FULL_NAME,
		
		-- Счет получателя
		D_ACC_LINK = P.D_Acc,
		D_ACC_NUM =	DA.code,
		D_ACC_TYPE = DA.[TYPE],
		D_ANAME = DA.aname,
		DBANK_LINK = DA.REF_LINK_B, 
		D_BIK = rtrim(isnull(DA.BANK_CODE,DTA.BANK_CODE)), 
		D_BANK = rtrim(isnull(DA.BANK_FNAME,DTA.BANK_FNAME)), 
		D_BANK_CITY = isnull(DA.BANK_CITY,DTA.BANK_CITY), 
		D_BANK_FILIAL = isnull(DA.BANK_FILIAL,DTA.FILIAL), 
		D_FBANK = isnull(DA.BANK_FNAME,DTA.BANK_FNAME), 
		D_SCH_B = isnull(DA.BANK_KS,DTA.BANK_KS),
		D_KAZN = DA.KAZN_NAME, 
		D_KAZN_CODE = DA.KAZN_CODE, 
		D_KAZN_INN = DA.KAZN_INN, 
		D_SCH_K = DA.K_ACC_CODE,
		D_SCH_K_LINK = DA.K_ACC_LINK,
		
		P.BK_IN_TGT,
		P.KIND,
		[ORDER]= P.Order_Pay,
		P.PAYKIND,
		P.PRINT_KPP,
		P.REASON,
		P.SROK,
		P.NDS,
		P.NDS_LINK,
		NDS_NAME=	CONVERT(VARCHAR(254),	(SELECT NAME FROM dbo.DICTION as D WITH (NOLOCK) WHERE D.LINK = P.NDS_LINK)),
		NDSKIND = convert(varchar(100),''), 
		P.TARGETTEXT,
		
		DOG_CODE = GD.Number,
		DOG_NAME = CONVERT (VARCHAR (254), GD.INFO),
		DOG_LINK = GD.DOC_LINK,
		DOG_OBJ = cast('' as char(100)),
		DOG_OSNOV = P.link_dogovor,

		BO_NUM = P.BO_NUM,
		
		REG = P.REG,
		REG_CODE = REG.CODE,
		REG_NAME = REG.NAME,
		
		INV_LINK = P.link_invoice,
		INV_CODE = GD1.Number,
		TITLE	= 'Пл.П №' + RTRIM(CONVERT(VARCHAR(20),G.NUMBER)) + ' от ' + CONVERT(VARCHAR(10),G.[DATE], 104),
		S_TARGET = CONVERT(VARCHAR(100),LEFT(TARGETTEXT,100)),
		P.OKATO,
		[PERIOD] = P.Nal_PERIOD,
		BK = dbo.BB_GET_PAY_BK(G.LINK)
	
	FROM  dbo.G_PROV G 
	inner join dbo.FINANSE_PAYS P WITH (NOLOCK) on P.link = G.link
	inner join dbo.DICTIONARY_ACCOUNTS  SA WITH (NOLOCK) on P.S_ACC = SA.LINK
	inner join dbo.DICTIONARY_ACCOUNTS DA WITH (NOLOCK) on P.D_ACC = DA.LINK
	left join dbo.DICTIONARY_K_ACCOUNTS STA WITH (NOLOCK) on SA.K_Acc_LINK = STA.link
	left join dbo.DICTIONARY_K_ACCOUNTS DTA WITH (NOLOCK) on DA.K_Acc_LINK = DTA.link
	inner join dbo.DEPARTMENTS SD WITH (NOLOCK) on SA.REF_LINK_D = SD.link
	inner 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_REG REG on P.REG = REG.link
	
	WHERE G.OBJECT = (select link from s_objects where code = 'DOCUMENTS_PAY')




GO


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

GO


CREATE VIEW dbo.BB_CREDIT
AS
 	SELECT 	
		GP.LINK,
		GP.NUMBER,
		GP.SUMMA,
		GP.COMMENT,
		GP.[DATE],
		GP.DATE_PROV,
		[FLAG_JC]   = CASE WHEN GP.DATE_PROV IS NULL THEN 0 ELSE 1 END,
		PLAT_DAY   = dbo.BB_CREDIT_PLAT_DAY(GP.LINK),
		[TYPE]	    = CT.LINK,
		[TYPE_CODE] = CT.CODE,
		[TYPE_NAME] = CT.NAME,
		[ACC_LINK]  = GP.ACC,
		[ACC_CODE]  = DA.CODE,
		[ACC_NAME]  = DA.ANAME,
		[DEP_LINK]  = GP.DEP,
		[DEP_CODE]  = D.CODE,
		[DEP_NAME]  = D.NAME,
		[ZACC_LINK] = CH.ACC,
		[ZACC_CODE] = DAP.CODE,
		[ZACC_NAME] = DAP.ANAME,
		[ZDEP_LINK] = CH.DEP,
		[ZDEP_CODE] = DP.CODE,
		[ZDEP_NAME] = DP.NAME,
		[DOC_LINK]  = CH.DOC_LINK,
		[DOC_NUM]   = O.[NUMBER],
		[DOC_DATE]  = O.[DATE],
		[DOC_NAME]  = RTRIM(O.TYPE),
		[ADOC_NAME] = O.INFO,
		CH.FIN_SOURCE,
		CH.NUM_ACC,
		CH.SERIYA,
		CH.RAS,
		DATE_END = dbo.BB_CREDIT_DATE_END(GP.LINK, default, default),
		KBK_LINK = CH.KBK,
		KBK_CODE = KBK.CODE,
		KBK_NAME = KBK.NAME
	FROM dbo.G_PROV as GP WITH (NOLOCK)
	INNER JOIN dbo.CREDIT_HEAD CH 	   	ON CH.LINK  = GP.LINK
	LEFT  JOIN dbo.DEPARTMENTS D   	   	ON D.LINK   = GP.DEP
	LEFT  JOIN dbo.DICTIONARY_ACCOUNTS DA	ON DA.LINK  = GP.ACC
	LEFT  JOIN dbo.DEPARTMENTS DP   	ON DP.LINK  = CH.DEP
	LEFT  JOIN dbo.DICTIONARY_ACCOUNTS DAP	ON DAP.LINK = CH.ACC
	LEFT  JOIN dbo.BD_OSNOV O 			ON O.LINK   = CH.DOC_LINK
	LEFT  JOIN dbo.CREDIT_TYPES CT 		ON CT.LINK  = CH.TYPE
	LEFT  JOIN dbo.KL_KBK KBK			ON KBK.LINK  = CH.KBK
	WHERE GP.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'BB_CREDIT')



GO


GRANT SELECT ON dbo.[BB_CREDIT] TO PUBLIC

GO



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

GO

CREATE	function dbo.BB_NewPlatDate (@dDateOld datetime, @iMonthAdd int, @iDay tinyint/*, @iWorkDay tinyint = 0*/)
returns datetime
as
begin
declare @iMonth 	int,
		@iYear 		int,
		@dDateNew	datetime
	


set @dDateNew = dateadd(month,@iMonthAdd,@dDateOld)
	
if @iDay <> day(@dDateNew) and @iDay <= day(dbo.DateEndOfMonth(@dDateNew))
	set @dDateNew = dbo.ConvertDMY2Date(@iDay,month(@dDateNew),year(@dDateNew)) 
/*
if @iWorkDay = 1 and 
	(exists(select * from dbo.HOLIDAYS where [DAY] = @iDay and [MONTH] = month(@dDateNew) and [YEAR] = year(@dDateNew) and TYPE_HOL = 2) and 
	exists(select * from dbo.HOLIDAYS where [DAY] = @iDay and [MONTH] = month(@dDateNew) and [YEAR] = year(@dDateNew) and TYPE_HOL = 1)
*/

RETURN @dDateNew
END


GO


GRANT EXECUTE ON dbo.[BB_NewPlatDate] TO PUBLIC

GO

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

GO

CREATE       FUNCTION dbo.ku_WithoutHolidayCount (@dDate1 datetime, @dDate2 datetime)
RETURNS int
AS
BEGIN
	RETURN datediff(day, @dDate1, @dDate2) + 1
	 - (
		SELECT count(t1.DATE)
		FROM 
			dbo.days_ex(@dDate1,@dDate2) T1
			INNER JOIN dbo.HOLIDAYS DH ON day(t1.[DATE]) = DH.[DAY] and month(t1.DATE) = DH.[MONTH] AND YEAR(t1.DATE) = DH.[YEAR]
		WHERE 
			DH.TYPE_HOL = 1
		)
END

GO

GRANT EXECUTE ON dbo.[ku_WithoutHolidayCount] 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.link_vkr = Vkr.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 
							and s.LINK_vkr = Vkr.link
						) ,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 = case when  isnull(T2.SUMMA_BASE,0) <> 0 
				then (isnull(SRC.SUMMA_BASE,0)
					  -
					  isnull(T2.SUMMA_BASE,0)
					  ) 
				else 
				(isnull(SRC.SUMMA_BASE,0) - 
					( select top 1 isnull(sum(T.SUMMA_BASE),0) 
					from  @SPR_ESN_SRC2 T 
					where T.LINK_VKR = SRC.LINK_VKR  
					AND T.REF_PHYS_PERS = SRC.REF_PHYS_PERS  
					AND T.WAY_CALC = SRC.WAY_CALC 
					AND T.MONTH_BASE = (SRC.MONTH_BASE - 1)	
					)
				) 
		  end, 
	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_GetTableOperINV]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[BK_GetTableOperINV]

GO

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Возвращает операции по ОС и заданным хоз. операциям --
-- @iTYPE_OPER		TINYINT = 0 - выбирает все операции 
-- @iTYPE_OPER		TINYINT = 1 - выбирает операции вложения
-- @iTYPE_OPER		TINYINT = 2 - выбирает операции принятия к учету
-- @iTYPE_OPER		TINYINT = 3 - выбирает операции выбытия 
-- @iTYPE_OPER		TINYINT = 4 - выбирает операции по начислению амортизации
-- @iTYPE_OPER		TINYINT = 5 - выбирает операции по безвозмездному поступлению
CREATE FUNCTION dbo.BK_GetTableOperINV
	(@intDIC_LINK	INT = NULL,
	@dDATE_BEGIN	DATETIME = NULL,
	@dDATE_END		DATETIME = NULL,
	@iTYPE_OPER		TINYINT = 0,
	@intDEP_LINK	INT = NULL
	)
RETURNS TABLE
AS
RETURN
	SELECT
		DEP_LINK	=	T1.DEP_LINK,
		INV			=	T1.DIC_LINK,
		DOC_NUM		=	T1.DOC_NUM,
		DATE_OPER	=	T1.DATE_OPER,
		SUMMA		=	T1.SUMMA,
		QTY			=	T1.QTY,
		OPER_CODE	=	T1.OPER_CODE,
		LINK_XO		=	T1.LINK_XO,
		JO_NUM		=	T1.JO_NUM,
		STORNO		=	T1.STORNO,
		LINK_G2		=	T1.LINK_G2
	FROM (
		SELECT TYPE_OPER = 0, OPER_CODE = NULL	-- все операции
		UNION ALL
		SELECT TYPE_OPER = 1, OPER_CODE = '14.06'	-- операции вложения
		UNION ALL
		SELECT TYPE_OPER = 2, OPER_CODE = '17.01#17.02#17.03#17.05#17.06#17.12#17.13#23.13'	--	операции принятия к учету 
		UNION ALL
		SELECT TYPE_OPER = 3, OPER_CODE = '17.08#17.09#17.10#17.11#17.19#22.05'	-- операции выбытия 
		UNION ALL
		SELECT TYPE_OPER = 4, OPER_CODE = '17.14'	-- операции по начислению амортизации
--		UNION ALL
--		SELECT TYPE_OPER = 5, OPER_CODE = '22.05#17.02#17.32#17.35#17.36#17.39#17.40#23.16#23.13#31.02'	-- операции по безвозмездному поступлению
		) AS T0
	INNER JOIN
		(
		SELECT DATE_END = ISNULL (@dDATE_END, (SELECT WORKDATE FROM dbo.USER_INFO))
		) AS TD ON (1 = 1)	
	CROSS APPLY dbo.BK_GetTableOperAnalit ('INV',
									@dDATE_BEGIN,
									TD.DATE_END,
									T0.OPER_CODE,
									@intDIC_LINK,
									@intDEP_LINK,
									DEFAULT) T1
	WHERE T0.TYPE_OPER = @iTYPE_OPER

GO

GRANT SELECT ON dbo.[BK_GetTableOperINV] TO PUBLIC

GO

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


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

GO
/*
© Кейсистемс (Keysystems), 2005
*/
CREATE VIEW dbo.VACATION
AS
SELECT 
	iv.link, iv.moved,
	[flag_jc] = COALESCE(R.ref_doc,0)/COALESCE(R.ref_doc,1),--(case when  then 1 else 0 end),
	o.number, o.date, o.dep_link, iv.order_link, iv.empl_link,
	[tab_num] = LEFT(E.TAB,6), [fio] = LEFT(ISNULL( LTRIM(RTRIM(PERS.FM)) + ' ' + LTRIM(RTRIM(PERS.IM)) + ' ' + LTRIM(RTRIM(PERS.OT)),'Не заполнено'),100), 
	[subdiv] = S.[NAME], 
	[post] = p.[NAME], 
	iv.type_link,
	[type_name]=VV.[name],
	iv.period_begin, iv.period_end, iv.date_begin, iv.date_end, 
	iv.reason_LINK,
	[reason] = VO.OSN, 
	iv.reason_dop,
	iv.active,
	VGT.LINK as VAC_GRAPH_LINK,
	CHILDREN = case when D.WORK_D = 7 then 1 else 0 end,
	VV.HOLIDAY,
	dep.NAME as name_dep,
	NO_SAL ,
	iv.compens
FROM dbo.item_vacation iv inner join orders o on iv.order_link=o.link
INNER JOIN dbo.EMPL E on iv.empl_link = E.LINK
INNER JOIN dbo.PERSON PERS on E.PERS_LINK = PERS.LINK
INNER JOIN dbo.DEPARTMENTS dep ON dep.link = E.DEP_LINK
LEFT JOIN vacation_vid VV ON VV.LINK = iv.type_link
LEFT JOIN vacation_osn VO ON VO.LINK = iv.reason_link
LEFT JOIN dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK
LEFT JOIN dbo.empl_staff1(DEFAULT) es ON ES.EMPL_LINK = iv.EMPL_LINK
LEFT JOIN dbo.subdiv s ON s.link=es.subdiv_link
LEFT JOIN dbo.post p on p.link=es.post_link
LEFT JOIN dbo.VACATION_GRAPHICS_TABLE VGT ON VGT.SFORMIROVAN = IV.LINK
LEFT JOIN ( 
		select distinct sd.ref_doc  from dbo.SDOC S INNER JOIN dbo.SDOC_AVAC SD ON (S.LINK = SD.LINK_UP AND S.OBJECT =(SELECT LINK FROM S_OBJECTS WHERE CODE = 'DOCUMENTS_ADD_FURLOUGH'))
	) R ON R.ref_doc = iv.link




GO


GRANT SELECT ON dbo.[VACATION] TO PUBLIC

GO


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


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

GO
CREATE FUNCTION dbo.sa_used_vacation (@dDate datetime)
RETURNS TABLE
/*Возвраящает информацию по испльзованным дням отпуска в текущем году, по состоянию на дату*/
RETURN

WITH H AS
(
SELECT T1.[DATE]
FROM
	dbo.days_ex(DATEADD(YEAR, DATEDIFF(YEAR, 0, @dDate), 0),DATEADD(YEAR, DATEDIFF(YEAR, -1, @dDate), -1)) T1
	INNER JOIN dbo.HOLIDAYS DH ON day(t1.[DATE]) = DH.[DAY] and month(t1.DATE) = DH.[MONTH] AND YEAR(t1.DATE) = DH.[YEAR]	
WHERE 
	DH.TYPE_HOL = 1	
)
SELECT T1.EMPL_LINK, DVM = ISNULL(DVM,0), DVA = ISNULL(DVA,0), DHM = ISNULL(DHM,0), DHA = ISNULL(DHA,0)
FROM
(
	SELECT EMPL_LINK, 
			SUM(datediff(day, DATE_BEGIN, DATE_END) + 1) AS DV, 
			SUM((CASE WHEN VAC_V = 3 THEN datediff(day, DATE_BEGIN, DATE_END) + 1 ELSE 0 END)) AS DVM,
			SUM((CASE WHEN VAC_V = 2 THEN datediff(day, DATE_BEGIN, DATE_END) + 1 ELSE 0 END)) AS DVA 
	FROM
		dbo.item_vacation IV
		INNER JOIN dbo.vacation_vid vv ON vv.LINK = IV.TYPE_LINK
	WHERE
		active=1 AND (VAC_V = 2 OR VAC_V = 3)
		AND
		year(DATE_BEGIN) BETWEEN YEAR(DATEADD(YEAR, DATEDIFF(YEAR, 0, @dDate), 0)) and YEAR(DATEADD(YEAR, DATEDIFF(YEAR, 0, @dDate), 0))
	GROUP BY
		EMPL_LINK
) AS T1
LEFT JOIN 
(
SELECT EMPL_LINK, SUM(CASE WHEN VAC_V = 3 THEN 1 ELSE 0 END) AS DHM, SUM(CASE WHEN VAC_V = 2 THEN 1 ELSE 0 END) AS DHA
FROM
	dbo.item_vacation IV
	INNER JOIN dbo.vacation_vid vv ON vv.LINK = IV.TYPE_LINK
	INNER JOIN H ON H.[DATE] BETWEEN DATE_BEGIN AND DATE_END
WHERE
	active=1 AND (VAC_V = 2 OR VAC_V = 3)
	AND
	year(DATE_BEGIN) BETWEEN YEAR(DATEADD(YEAR, DATEDIFF(YEAR, 0, @dDate), 0)) and YEAR(DATEADD(YEAR, DATEDIFF(YEAR, 0, @dDate), 0))
GROUP BY
	EMPL_LINK	
) AS T2	ON T1.EMPL_LINK = T2.EMPL_LINK	


GO


GRANT SELECT ON dbo.[sa_used_vacation] TO PUBLIC

GO

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

GO

CREATE            Function dbo.BB_DEP_ACC_DOP(@iLinkDepAcc int = null)
RETURNS @varKStable TABLE ( ACC_LINK	int,
							ACC_CODE	varchar(20),
							DEP_LINK	int,
							DEP_TYPE	tinyint,
							DEP_B_CODE	varchar(10),
							CODE_UBP	varchar(5),
							DEP_KPP		varchar(20),
							DEP_OKATO	varchar(20),
							DEP_OKTMO   varchar(11),
							DEP_INN		varchar(20),
							DEP_FNAME	varchar(254),
							GRBS_NAME	varchar(254),
							GRBS_CODE	varchar(3),
							BUDG_NAME	varchar(254),
							BUDG_LEVEL	varchar(1),
							BUDG_CODE	varchar(2),
							FO_NAME		varchar(254),
							FO_CODE		varchar(10),
							FO_OKPO		varchar(10),
							TOFK_NAME	varchar(254),
							TOFK_CODE	varchar(4),
							K_ACC_CODE	varchar(20))
AS
BEGIN
insert into @varKStable
SELECT	ACC_LINK 	= DA.LINK,
		ACC_CODE	= DA.CODE,
		DEP_LINK	= D.LINK,
		DEP_TYPE	= D.TYPE,
		DEP_B_CODE	= D.BUDG,
		DEP_B_CODE	= D.CODE_UBP,
		DEP_KPP		= D.KPP,
		DEP_OKATO	= D.OKATO,
		DEP_OKTMO	= D.OKTMO,
		DEP_INN		= rtrim(D.INN) + case when D.INN_DOP = '' then '' else '\' + D.INN_DOP end,
		DEP_FNAME	= left(rtrim(D.prefix) + rtrim(D.FULL_NAME) + case when charindex('(',D.prefix,0) > 0 then ')' else '' end,254),
		GRBS_NAME	= VED.NAME,
		GRBS_CODE	= VED.CODE,
		BUDG_NAME	= BUDG.NAME,
		BUDG_LEVEL	= right(BUDG.CODE_EL,1),
		BUDG_CODE	= BUDG.CODE,
		FO_NAME		= FO.FULL_NAME,	
		FO_CODE		= FO.CODE,
		FO_OKPO		= FO.OKPO,
		TOFK_NAME	= DA.KAZN_F_NAME,
		TOFK_CODE	= DA.KAZN_CODE,
		K_ACC_CODE  = DA.K_ACC_CODE 
from dbo.DICTIONARY_ACCOUNTS DA
left join dbo.DEPARTMENTS D WITH (NOLOCK) on DA.REF_LINK_D = D.link
left join dbo.DEPARTMENTS FO WITH (NOLOCK) on D.FO_LINK = FO.LINK
left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
where DA.LINK = @iLinkDepAcc and @iLinkDepAcc is not null or @iLinkDepAcc is null

RETURN
END

GO


GRANT SELECT ON dbo.[BB_DEP_ACC_DOP] TO PUBLIC

GO




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

GO

CREATE FUNCTION [dbo].SA_HOLIDAY_COUNT_FN (@varKSdDate1 datetime, @varKSdDate2 datetime)
RETURNS INT
AS  
BEGIN
DECLARE @varKSCount INT

SELECT @varKSCount=count(t1.DATE)
FROM dbo.SD_DAY(@varKSdDate1,@varKSdDate2) T1, KD_HOLIDAYS DH
WHERE day(t1.DATE) = DH.DAY and month(t1.DATE) = DH.MONTH and YEAR(t1.DATE) = DH.YEAR AND (DH.WORK_D = 14 or DH.WORK_D = 11) AND TYPE_HOL = 1

RETURN @varKSCount

END



GO


GRANT EXECUTE ON dbo.[SA_HOLIDAY_COUNT_FN] TO PUBLIC

GO



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

GO

CREATE   VIEW dbo.BI_DICTION_KBK
AS
SELECT	K.LINK,
	K.code,
	K.Name,
	convert(char(5),(case
		when K.Type=1 then 'ВКР'
		when K.Type=2 then 'КД'
		when K.Type=4 then 'КИВФ'
		when K.Type=8 then 'КИВнФ' end)) as Type_Str,
	K.Type,
	A.code as Adm_Code,
	A.name as Adm_Name,
	K.link_adm,
	[USED]     = CASE WHEN K.USED = 1 or DKBK.KBK_LINK is not null THEN 1 ELSE 0 END,
	USED_ALL   = K.USED,
	USED_D	   = CASE WHEN DKBK.KBK_LINK is null THEN 0 ELSE 1 END,
	OSN		   = isnull(DKBK.OSN,0),
	DKBK.DEP_LINK,
	KBK14_CODE = RF14.RAZD_CODE+RF14.CEL_ST_CODE+RF14.VR_CODE+RF14.SHIFR

FROM KL_KBK K 
left join KL_ADMIN_BS A ON K.Link_Adm = A.link 
left join dbo.DEPARTMENT_KBK DKBK on DKBK.KBK_LINK = K.LINK and DEP_LINK = isnull(dbo.BK_getDepZB(),dbo.GetOwnDepLink())
LEFT JOIN dbo.KBK14_LINKED k14 ON k.link = k14.link 
LEFT join dbo.REPORT_FORM14_RAZD_NAME RF14 ON k14.link_KBK = rf14.link





GO


GRANT SELECT ON dbo.[BI_DICTION_KBK] TO PUBLIC

GO




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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE   FUNCTION dbo.w_days(@varKSnTyp int, @varKSDATE1 datetime, @varKSDate2 datetime)



RETURNS int
AS
BEGIN
	DECLARE @varKSnRet INT, @varKSDateCur datetime, @varKSDateCurr DATETIME
	
	if @varKSDate2<@varKSDATE1 or @varKSnTyp<1 or @varKSnTyp>7
		RETURN 0
	
	SET @varKSDateCur = @varKSDATE1
	SET @varKSnRet = 0
	while @varKSDateCur<=@varKSDate2
	begin
		IF DATEPART (DW , @varKSDateCur) <=@varKSnTyp 
			IF not exists(SELECT link FROM KD_HOLIDAYS WHERE TYPE_HOL = 1 AND [DAY]= day(@varKSDateCur) AND [MONTH] = month(@varKSDateCur) AND [YEAR] = YEAR(@varKSDateCur))
				SET @varKSnRet = @varKSnRet+1
		SET @varKSDateCur = DATEADD(D,1,@varKSDateCur)
		CONTINUE
	END
	RETURN ISNULL(@varKSnRet,0)
END


GO


GRANT EXECUTE ON dbo.[w_days] TO PUBLIC

GO




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

GO

CREATE FUNCTION dbo.RM_KBK14(@shifr varchar(30))
 	RETURNS VARCHAR(30)
AS 
BEGIN
	DECLARE 
        @kbk 		    varchar(30),
		@SplitterPos	int,
		@ShifrKbk	    varchar(30)

	set @SplitterPos = charindex('#',@shifr)

	if @SplitterPos>0
	begin	
		SET @shifr=substring(@shifr,1,@SplitterPos-1)

		select @kbk =  ltrim(rtrim(razd_code) + rtrim(cel_st_code) + vr_code)
		from REPORT_FORM14_RAZD_NAME
		where shifr = @shifr
		
		set @ShifrKbk = (isnull(@kbk,'--'))
	end
	else 
		set @ShifrKbk =	@shifr
	
	return @ShifrKbk
END
	
 


GO


GRANT EXECUTE ON dbo.[RM_KBK14] TO PUBLIC

GO



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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
/* Расширенный алиас КБК для формы редактирования КБК */
CREATE    VIEW [dbo].BI_DICTION_KBK_FULL
AS
SELECT	K.LINK,
	K.code,
	K.Name,
	convert(char(5),(case
		when K.Type=1 then 'ВКР'
		when K.Type=2 then 'КД'
		when K.Type=4 then 'КИВФ' 
		when K.Type=8 then 'КИВнФ' end)) as Type_Str,
	[Type] = convert(tinyint, log(K.Type)/log(2))+1,
	[Adm_Code] = A.code,	/* Администратор БС */
	[Adm_Name] = A.name,
	[Adm_Link] = K.link_adm,
	PROG_Link  = P.link,
	PROG_CODE  = P.code,	/* программа */
	PROG_Name  = P.name,
	[KD_LINK] = KD1.Link,	/* Классификатор доходов */
	[KD_CODE] = KD1.Code,
	[KD_NAME] = KD1.name,
	[IVF_LINK] = KF1.Link,	/* Классификатор Источ финанс */
	[IVF_CODE] = KF1.Code,
	[IVF_NAME] = KF1.name,
	[SGU_LINK] = (case when K.type=2 then KD.link_sgu  -- СГУ 
			   when K.type=4 then KF.link_sgu 
			   when K.type=8 then KF.link_sgu else null end),
	[SGU_CODE] = (case when K.type=2 then (select code from KOSGU SGU where SGU.link = KD.link_sgu)
			   when K.type=4 then (select code from KOSGU SGU where SGU.link = KF.link_sgu)
			   when K.type=8 then (select code from KOSGU SGU where SGU.link = KF.link_sgu)
			else NULL end),
	[SGU_NAME] = (case when K.type=2 then (select name from KOSGU SGU where SGU.link = KD.link_sgu)
			   when K.type=4 then (select name from KOSGU SGU where SGU.link = KF.link_sgu)
			   when K.type=8 then (select name from KOSGU SGU where SGU.link = KF.link_sgu)
			else  NULL end),
	[DIV_LINK] = DIV.Link,	/* ВКР: Подраздел */
	[DIV_CODE] = DIV.Code,
	[DIV_NAME] = DIV.name,
	[CSR_LINK] = CSR.Link,	/* ВКР: Целевая статья */
	[CSR_CODE] = CSR.Code,
	[CSR_NAME] = CSR.name,
	[EXP_LINK] = EX.Link,	/* ВКР: Вид расходов */
	[EXP_CODE] = EX.Code,
	[EXP_NAME] = EX.name,
	[USED]     = CASE WHEN K.USED = 1 or DKBK.KBK_LINK is not null THEN 1 ELSE 0 END,
	USED_ALL   = isnull(K.USED,0),
	USED_D	   = CASE WHEN DKBK.KBK_LINK is null THEN 0 ELSE 1 END,
	OSN		   = isnull(DKBK.OSN,0),
	DKBK.DEP_LINK,
	KBKL_LINK = KL.LINK,
	KBKL_CODE = KL.code,
	KBKL_NAME = KL.Name,
	KBK14_LINK = K14.LINK_KBK,
	KBK14_CODE = LEFT(RF14.RAZD_CODE+RF14.CEL_ST_CODE+RF14.VR_CODE+RF14.SHIFR,30),
	KBK14_NAME = RF14.Name_str,
	KBK14_RAZD = RF14.RAZD_CODE,
	KBK14_CEL_ST = RF14.CEL_ST_CODE,
	KBK14_VR =RF14.VR_CODE,
	KBK14_SHIFR = RF14.SHIFR
	
	
FROM KL_KBK K 
left join KL_ADMIN_BS A ON K.Link_Adm = A.link 
left join KL_KBK_KD KD ON K.Link = KD.link_kbk
	left join KL_KD KD1 ON KD.Link_KD = KD1.link
	left join KL_KBK_IVF KF ON K.Link = KF.link_kbk
	left join KL_IVF KF1 ON KF.Link_IVF = KF1.link
	left join KL_VKR KV ON K.Link = KV.link_kbk
		left join KL_DIVISION DIV ON KV.Link_Div = DIV.link
		left join KL_TARGET_ITEM CSR ON KV.Link_CSR = CSR.link
		left join KL_EXPEND EX ON KV.Link_EXP = EX.link
left join dbo.KL_KBK_LINKED L ON K.Link = L.link 
	left join dbo.KL_KBK KL ON L.Link_KBK = KL.link 
left join dbo.KL_PROG P ON P.Link = coalesce(KD.link_PROG,KF.link_PROG)
left join dbo.DEPARTMENT_KBK DKBK on DKBK.KBK_LINK = K.LINK and DEP_LINK = isnull(dbo.BK_getDepZB(),dbo.GetOwnDepLink())
LEFT JOIN dbo.KBK14_LINKED k14 ON k.link = k14.link 
LEFT join dbo.REPORT_FORM14_RAZD_NAME RF14 ON k14.link_KBK = rf14.link





GO


GRANT SELECT ON dbo.[BI_DICTION_KBK_FULL] TO PUBLIC

GO



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

GO

CREATE VIEW [dbo].VACATION_EX 
AS 
SELECT *,
	BEGIN_VACATION= (SELECT MIN(DATE_BEGIN) 
						FROM DBO.VACATION AS V 
						WHERE 
							V.EMPL_LINK = VAC.EMPL_LINK 
							AND 
							V.NUMBER = VAC.NUMBER 
							AND 
							V.[DATE] = VAC.[DATE]
						)
FROM 
	DBO.VACATION AS VAC




GO


GRANT SELECT ON dbo.[VACATION_EX] TO PUBLIC

GO



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

GO

CREATE  VIEW dbo.SALARY_ALL_PROV
AS

Select  
--[LINK]= DOC_LINK,
[DOC_LINK]= UP.DOC_LINK,
[LINK]= UP.LINK,
[FLAG_JC] = CASE WHEN UP.DATE_PROV IS NULL THEN 0 ELSE 1 END,
[DATE] = CONVERT(DATETIME,UP.DATEDOC, 112),
[DATE_PROV] = CONVERT(DATETIME,UP.DATE_PROV, 112),
[NUMBER] = UP.NUMDOC,
[COMMENTARY] = UP.NAME_OPER, 
[KBK_CODE] = UP.KBK_CODE,
[EKR_CODE] = UP.EKR_CODE,
[DEB_CODE] = UP.DEB_CODE, 
[DEB_NAME] = UP.DEB_NAME, 
[CRE_CODE] = UP.CRE_CODE,
[CRE_NAME] = UP.CRE_NAME,
[SUMMA]    = UP.SUMMA,
[LINK_DEP] = UP.LINK_DEP,
[DEP_NAME] = (SELECT NAME FROM dbo.DEPARTMENTS WHERE LINK = UP.LINK_DEP),
[ACC_LINK] = (SELECT ACC FROM G_PROV WHERE LINK = UP.DOC_LINK),
[ACC_CODE] = ISNULL((SELECT CODE FROM dbo.DICTIONARY_ACCOUNTS WHERE LINK = (SELECT ACC FROM G_PROV WHERE LINK = UP.DOC_LINK)),''),
[STATUS_EX] = CASE WHEN UP.STATUS_EXCH IS NULL THEN 0 ELSE UP.STATUS_EXCH end,
[STATUS_EX_DATE] = UP.STATUS_EX_DATE, 
[STATUS_EX_NAME] = CASE WHEN UP.STATUS_EXCH  = 1 THEN 'Передано ' +  CONVERT(VARCHAR(23),UP.STATUS_EX_DATE , 120)
						WHEN UP.STATUS_EXCH  = 2 THEN 'Принято ' + CONVERT(VARCHAR(23),UP.STATUS_EX_DATE , 120)
						WHEN UP.STATUS_EXCH  = 0 THEN 'Принято ранее ' + CONVERT(VARCHAR(23),UP.STATUS_EX_DATE , 120)
						WHEN UP.STATUS_EXCH  < 0 THEN 'Ошибка Приема ' + CONVERT(VARCHAR(23),UP.STATUS_EX_DATE , 120) 
						ELSE ''
					END	,	
[ST_EX_COMMENT]	= LEFT(UP.ST_EX_COMMENT,254)					
FROM dbo.xk_user_prov(NULL, DEFAULT) UP 
INNER JOIN dbo.SALARY_BUH_DOCS SD ON SD.LINK = UP.DOC_LINK AND CNT_PROV <> 0



GO


GRANT SELECT ON dbo.[SALARY_ALL_PROV] TO PUBLIC

GO




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

GO
CREATE FUNCTION DBO.SA_GET_EMPL_NWD_COMMENT (@LINK_EMPL INT = -1, @LINK_DOC INT = NULL, @DATE_BEG DATETIME = NULL, @DATE_END DATETIME= NULL)
/*ПОЛУЧЕНИЕ ИНФОРМАЦИИ ОБ ОТРАБОТАННЫХ ДНЯХ ЗА ЗАДАННЫЙ ПЕРИОД
@LINK_DAY = 0 ВСЕ ВИДЫ ЧАСОВ
@LINK_DAY > 0 ДЛЯ ЗАДАННОГО ВИДА ЧАСОВ
*/
RETURNS VARCHAR(1000)
AS
BEGIN

DECLARE @RES VARCHAR(1000), @DAY int

DECLARE @NW_DAYS TABLE (LINK INT, [day] INT)

IF @DATE_BEG IS NULL 
	SET @DATE_BEG = (SELECT TOP 1 PERIOD FROM DBO.TABELS WHERE LINK = @LINK_DOC)
SET @DATE_END = COALESCE(@DATE_END,DBO.DATEENDOFMONTH(@DATE_BEG))

DECLARE @N VARCHAR(1000),@D CHAR(1000), @TMP VARCHAR(1000), @TMP2 VARCHAR(1000)

DECLARE @Cur1 CURSOR
SET @TMP = ''
SET @TMP2 = ''
SET @Cur1 = CURSOR FORWARD_ONLY

FOR 

SELECT
	RES = 
	(CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 1) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('' + CONVERT(VARCHAR(20),D1),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 2) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D2),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 3) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D3),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 4) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D4),'') ELSE '' END)		
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 5) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D5),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 6) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D6),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 7) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D7),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 8) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D8),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 9) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D9),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 10) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D10),'') ELSE '' END)

	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 11) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D11),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 12) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D12),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 13) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D13),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 14) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D14),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 15) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D15),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 16) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D16),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 17) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D17),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 18) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D18),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 19) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D19),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 20) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D20),'') ELSE '' END)

	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 21) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D21),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 22) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D22),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 23) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D23),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 24) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D24),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 25) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D25),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 26) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D26),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 27) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D27),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 28) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D28),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 29) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D29),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 30) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D30),'') ELSE '' END)
	+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 31) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN ISNULL('#' + CONVERT(VARCHAR(20),D31),'') ELSE '' END),

	[DAY] = (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 1) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D1),'') <>'' THEN ('' + '1') ELSE '' END)  ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 2) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D2),'')<>'' THEN ('#' + '2') ELSE '' END)  ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 3) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D3),'')<>'' THEN ('#' + '3') ELSE '' END)  ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 4) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D4),'')<>'' THEN ('#' + '4') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 5) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D5),'')<>'' THEN ('#' + '5') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 6) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D6),'')<>'' THEN ('#' + '6') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 7) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D7),'')<>'' THEN ('#' + '7') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 8) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D8),'')<>'' THEN ('#' + '8') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 9) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D9),'')<>'' THEN ('#' + '9') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 10) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D10),'')<>'' THEN ('#' + '10') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 11) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D11),'')<>'' THEN ('#' + '11') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 12) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D12),'')<>'' THEN ('#' + '12') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 13) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D13),'')<>'' THEN ('#' + '13') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 14) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D14),'')<>'' THEN ('#' + '14') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 15) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D15),'')<>'' THEN ('#' + '15') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 16) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D16),'')<>'' THEN ('#' + '16') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 17) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D17),'')<>'' THEN ('#' + '17') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 18) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D18),'')<>'' THEN ('#' + '18') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 19) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D19),'')<>'' THEN ('#' + '19') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 20) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D20),'')<>'' THEN ('#' + '20') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 21) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D21),'')<>'' THEN ('#' + '21') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 22) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D22),'')<>'' THEN ('#' + '22') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 23) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D23),'')<>'' THEN ('#' + '23') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 24) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D24),'')<>'' THEN ('#' + '24') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 25) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D25),'')<>'' THEN ('#' + '25') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 26) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D26),'')<>'' THEN ('#' + '26') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 27) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D27),'')<>'' THEN ('#' + '27') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 28) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D28),'')<>'' THEN ('#' + '28') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 29) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D29),'')<>'' THEN ('#' + '29') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 30) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D30),'')<>'' THEN ('#' + '30') ELSE '' END) ELSE '' END)
			+ (CASE WHEN ((YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) * 100 + 31) BETWEEN ((YEAR(@DATE_BEG) * 100 + MONTH(@DATE_BEG)) * 100 + DAY(@DATE_BEG)) AND ((YEAR(@DATE_END) * 100 + MONTH(@DATE_END)) * 100 + DAY(@DATE_END)) THEN (CASE WHEN ISNULL(CONVERT(VARCHAR(20),D31),'')<>'' THEN ('#' + '31') ELSE '' END) ELSE '' END)
FROM
	DBO.TABELS T INNER JOIN DBO.TABELS_N N ON T.LINK = N.LINK_UP
	INNER JOIN DBO.MONTHS_EX(@DATE_BEG, @DATE_END) PER ON (YEAR(T.PERIOD) * 100 + MONTH(T.PERIOD)) = (YEAR(PER.DATE_BEGIN) * 100 + MONTH(PER.DATE_BEGIN))
WHERE
	(@LINK_EMPL = -1 OR @LINK_EMPL >= 0 AND T.LINK_EMPL = @LINK_EMPL) -- для заданного сотрудника или по всем
	AND
	(T.LINK_DOC = @LINK_DOC OR COALESCE(@LINK_DOC,0) = 0) --По заданному табелю или по всем табелям

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO   @N, @d
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN
		WHILE LEN(LTRIM(RTRIM(@N))) > 1 AND  LEN(LTRIM(RTRIM(@D))) > 1 
		BEGIN
		
			SET @TMP = DBO.SA_GET_WORD_NUM (@N,1,'#')
			
			SET @N = CASE WHEN LTRIM(RTRIM(@TMP)) = LTRIM(RTRIM(@N)) THEN '' ELSE SUBSTRING(@N, LEN(@TMP)+2, LEN(@N) - (LEN(@TMP)+1)) END
			
			SET @TMP2 = DBO.SA_GET_WORD_NUM (@d,1,'#')
			SET @d = CASE WHEN LTRIM(RTRIM(@TMP2)) = LTRIM(RTRIM(@d)) THEN '' ELSE SUBSTRING(@d, LEN(@TMP2)+2, LEN(@d) - (LEN(@TMP2)+1)) END
						
			INSERT INTO @NW_DAYS (LINK, [day]) VALUES (CONVERT(INT,@TMP),CONVERT(INT,@TMP2))
			
				
		END	

	END

	FETCH NEXT FROM @Cur1 INTO @N, @d
END

CLOSE @Cur1
DEALLOCATE @Cur1

---
DECLARE @CNT_DAYS INT , @MINDAY VARCHAR(10), @MAXDAY VARCHAR(10)

DECLARE @Cur2 CURSOR

SET @TMP = ''
SET @RES = ''

SET @Cur2 = CURSOR FORWARD_ONLY

FOR 

SELECT NAME = LTRIM(RTRIM(LEFT(TD.NAME,20))), CNT = COUNT(*) , MinDay  = CONVERT(VARCHAR(10),DBO.ConvertDMY2Date(MIN(d.[DAY]),MONTH(@DATE_BEG), YEAR(@DATE_BEG)),104), MaxDay = CONVERT(VARCHAR(10),DBO.ConvertDMY2Date(MAX(d.[DAY]),MONTH(@DATE_BEG), YEAR(@DATE_BEG)),104)
FROM DBO.TYP_DAYS TD INNER JOIN @NW_DAYS D ON TD.LINK = D.LINK 
WHERE TYP_YAVKA = 0 AND WORK_D NOT IN (11, 14)	
GROUP BY TD.NAME

OPEN @Cur2
FETCH NEXT FROM @Cur2 INTO @TMP, @CNT_DAYS, @MINDAY, @MAXDAY
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN

		SET @RES = @RES + CASE WHEN @RES <> '' THEN ', ' ELSE '' END
		SET @RES = @RES + CONVERT(VARCHAR(20),@CNT_DAYS) + 'дн.- ' + @TMP + ' c ' + @MINDAY + ' по ' + @MAXDAY
		
	END

	FETCH NEXT FROM @Cur2 INTO @TMP, @CNT_DAYS, @MINDAY, @MAXDAY
END

CLOSE @Cur2
DEALLOCATE @Cur2

RETURN @RES

END




GO


GRANT EXECUTE ON dbo.[SA_GET_EMPL_NWD_COMMENT] TO PUBLIC

GO



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

GO


CREATE   FUNCTION dbo.BK_GetTableDictionByAP (@strAP_CODE VARCHAR (60))  
RETURNS @RET_TABLE TABLE (LINK_AP INT,
			AP_CODE	VARCHAR (30),
			AP_NAME	VARCHAR (254),
			DOP_CODE VARCHAR (20),
			ANALIT VARCHAR (20)
			)
AS  
BEGIN 
	IF EXISTS (SELECT * FROM dbo.ANALIT WHERE CODE_AP = @strAP_CODE)
	BEGIN
		IF @strAP_CODE = 'EMP'
			INSERT INTO @RET_TABLE
			SELECT E1.LINK,
				E1.TAB,
				dbo.sd_GetEmplName (E1.LINK),
				'',
				@strAP_CODE
			FROM dbo.EMPL E1 
			INNER JOIN dbo.PERSON P1 ON E1.PERS_LINK = P1.LINK

		IF @strAP_CODE = 'NOMEN'
			INSERT INTO @RET_TABLE
			SELECT E1.LINK,
				E1.CODE,
				E1.[NAME],
				'',
				@strAP_CODE
			FROM dbo.NOMENCLATURE E1 

		IF @strAP_CODE = 'INV'
			INSERT INTO @RET_TABLE
			SELECT E1.LINK,
				E1.CODE,
				E1.[NAME],
				'',
				@strAP_CODE
			FROM dbo.INVENTORY E1 

		IF @strAP_CODE = 'TMC'
			INSERT INTO @RET_TABLE
			SELECT E1.LINK,
				E1.CODE,
				E1.[NAME],
				'',
				@strAP_CODE
			FROM dbo.DICTIONARY_TMC E1

		IF @strAP_CODE = 'DEP'
			INSERT INTO @RET_TABLE
			SELECT E1.LINK,
				E1.CODE,
				E1.[NAME],
				E1.OKPO,
				@strAP_CODE
			FROM dbo.DICTIONARY_DEPARTMENT E1 

		IF @strAP_CODE = 'DEP_ACC'
			INSERT INTO @RET_TABLE
			SELECT E1.LINK,
				E1.CODE,
				E1.CODE,
				'',
				@strAP_CODE
			FROM dbo.DEPARTMENT_ACCOUNTS E1 

		IF @strAP_CODE = 'KAU'
			INSERT INTO @RET_TABLE
			SELECT E1.LINK,
				E1.CODE,
				E1.[NAME],
				'',
				@strAP_CODE
			FROM dbo.DICTIONARY_ANALYTICAL_CODES E1 

		IF @strAP_CODE = 'KBK'
			INSERT INTO @RET_TABLE
			SELECT E1.LINK,
				E1.CODE,
				E1.[NAME],
				E1.TYPE_STR,
				@strAP_CODE
			FROM dbo.BI_DICTION_KBK E1 

		IF @strAP_CODE = 'SGU' OR @strAP_CODE = 'EKR'
			INSERT INTO @RET_TABLE
			SELECT E1.LINK,
				E1.CODE,
				E1.[NAME],
				'',
				@strAP_CODE
			FROM dbo.KOSGU E1 

		IF @strAP_CODE = 'AP1'
			INSERT INTO @RET_TABLE
	/*		SELECT E1.LINK, '', '', ''
			FROM dbo.OSNOV E1*/
			SELECT E1.LINK,
				'',
				E1.INFO,
				'',
				@strAP_CODE
			FROM dbo.BD_OSNOV E1
		
		-- Доп. классиф. --
		IF @strAP_CODE = 'AP2'
			INSERT INTO @RET_TABLE
			SELECT E1.LINK,
				E1.CODE,
				E1.[NAME],
				'',
				@strAP_CODE
			FROM dbo.DOP_CLASSIF E1

		-- Подразделение --
		IF @strAP_CODE = 'SUB'
			INSERT INTO @RET_TABLE
			SELECT D.LINK,
				D.CODE,
				D.[NAME],
				'',
				@strAP_CODE
			FROM dbo.SUBDIVISION(default) D
	END

	INSERT INTO @RET_TABLE VALUES (0, '', '', '', @strAP_CODE)

	RETURN 
END

GO


GRANT SELECT ON dbo.[BK_GetTableDictionByAP] TO PUBLIC

GO




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

GO

CREATE  VIEW dbo.DOCUMENTS_ADD_RESERV_TABLE
AS
SELECT
	[LINK]			= SD.LINK_UP,
	[ORDERS]		= SD.ORDERS,
	[REF_EMPL] 		= E.LINK,
	[TAB_NUMER]		= E.TAB,
	[NAME_EMPL]	 	= dbo.sd_GetEmplName(E.LINK),
	[SUMMA_BASE]	= SD.SUMMA_BASE,
	[AMOUNT_DED]	= SD.AMOUNT_DED,
	[SUMMA_DED]		= SD.SUMMA_DED,
	[AMOUNT_TR]		= SD.AMOUNT_TR,
	[SUMMA_TR]		= SD.SUMMA_TR,
	[OST_VAC_D]		= SD.OST_VAC_D,
	[SUMMA_RESERV]	= SD.SUMMA_RESERV,
	[REF_SUBDIV]    = E.SUBDIV_LINK,
 	[SUBDIV_NAME],
	[REF_POST]		= E.POST_LINK,
	[POST_NAME]
FROM 
	dbo.SDOC_RESERV D INNER JOIN 	dbo.SDOC_RESERV_TABLE SD ON D.LINK_UP = SD.LINK_UP
	LEFT JOIN dbo.KU_EMPL_PLACING E ON SD.LINK_EMPL = E.LINK

GO


GRANT SELECT ON dbo.[DOCUMENTS_ADD_RESERV_TABLE] TO PUBLIC

GO



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

GO

CREATE   Function dbo.BB_BK_FOR_SHABLON(@iLinkG int = null, @cShablon varchar(254), @cDELIM varchar(1), @cDELIM5 varchar(1))
RETURNS varchar(8000)
AS
BEGIN
Declare @iNotKBK tinyint, 
		@iNotVKR tinyint,
		@iTypeKbk tinyint,
		@iDopPos int,
		@cRes varchar(8000),
		@cResTemp varchar(8000),
		@bGroupBK tinyint,
		
		@cKBK_CODE varchar(30), 
		@cKBK_NAME varchar(1000), 
		@cADM_CODE varchar(3), 
		@cADM_NAME varchar(1000), 
		@cDIV_CODE varchar(4), 
		@cDIV_NAME varchar(1000), 
		@cCSR_CODE varchar(7), 
		@cCSR_NAME varchar(1000), 
		@cEXP_CODE varchar(3), 
		@cEXP_NAME varchar(1000), 
		@cSGU_CODE varchar(3), 
		@cSGU_NAME varchar(1000), 
		@cEKR_CODE varchar(3), 
		@cEKR_NAME varchar(1000), 
		@cDOP_CODE varchar(10), 
		@cDOP_NAME varchar(1000), 
		@cREG_CODE varchar(20), 
		@cREG_CODE_R varchar(20), 
		@cREG_NAME varchar(1000), 
		@nSUMMA	numeric(20,2),
		
		@cKBK_OLD varchar(20), 
		@cADM_OLD varchar(3), 
		@cDIV_OLD varchar(4), 
		@cCSR_OLD varchar(7), 
		@cEXP_OLD varchar(3),
		@iLinkedKBK	tinyint
		
set @iLinkedKBK = isnull(dbo.sa_get_option_by_code('NASTR_PAY_LINKED_KBK'),0)

if @iLinkG is null or @cShablon is null
	return ''
		
if charindex('<КБК',@cShablon) > 0
	set @iNotKBK = 0
else
	set @iNotKBK = 1

if charindex('<АДМ',@cShablon) > 0 OR charindex('<Раздел',@cShablon) > 0 OR charindex('<ЦС',@cShablon) > 0 OR charindex('<ВР',@cShablon) > 0
	set @iNotVKR = 0
else
	set @iNotVKR = 1
set @cRes = '' 
select @bGroupBK = GROUP_KBK from dbo.DOCUMENTS_PAY_OPTIONS
select @cKBK_OLD = '', @cADM_OLD = '', @cDIV_OLD = '', @cCSR_OLD = '', @cEXP_OLD = ''
		

--set @cShablon = UPPER(@cShablon)
if @iLinkG is not null
begin
	if @bGroupBK = 0
		declare BK_CUR cursor local static read_only for
		select	KBK_CODE = case when @iNotKBK = 1  or @iNotKBK = 0 and (KBK.TYPE = 1 and @iNotVKR = 0) then '' else isnull(KBK1.CODE, KBK.CODE) end, 
				KBK_NAME = case when @iNotKBK = 1  or @iNotKBK = 0 and (KBK.TYPE = 1 and @iNotVKR = 0) then '' else isnull(KBK1.CODE, KBK.NAME) end,
				ADM_CODE = case @iNotVKR when 1 then '' else isnull(KBK1.ADM_CODE, KBK.ADM_CODE) end, 
				ADM_NAME = case @iNotVKR when 1 then '' else isnull(KBK1.ADM_NAME, KBK.ADM_NAME) end, 
				DIV_CODE = case @iNotVKR when 1 then '' else isnull(KBK1.DIV_CODE, KBK.DIV_CODE) end, 
				DIV_NAME = case @iNotVKR when 1 then '' else isnull(KBK1.DIV_NAME, KBK.DIV_NAME) end, 
				CSR_CODE = case @iNotVKR when 1 then '' else isnull(KBK1.CSR_CODE, KBK.CSR_CODE) end, 
				CSR_NAME = case @iNotVKR when 1 then '' else isnull(KBK1.CSR_NAME, KBK.CSR_NAME) end, 
				EXP_CODE = case @iNotVKR when 1 then '' else isnull(KBK1.EXP_CODE, KBK.EXP_CODE) end, 
				EXP_NAME = case @iNotVKR when 1 then '' else isnull(KBK1.EXP_NAME, KBK.EXP_NAME) end,	
				SGU_CODE = isnull(SGU.CODE,''), 
				SGU_NAME = isnull(SGU.NAME,''), 
				EKR_CODE = isnull(EKR.CODE,''), 
				EKR_NAME = isnull(EKR.NAME,''), 
				DOP_CODE = isnull(DC.CODE,''), 
				DOP_NAME = isnull(DC.NAME,''),
				REG_CODE = isnull(REG.CODE,''), 
				REG_CODE_R = isnull(rtrim(REG.CODE) + isnull(@cDELIM,' '),''), 
				REG_NAME = isnull(REG.NAME,''),
				SUMMA	 = G2.SUMMA,
				KBK.TYPE	
		from  dbo.FINANSE_PAYS P
		inner join dbo.G_PROV1 G1 on P.LINK = G1.LINK_UP
		inner join dbo.G_PROV2 G2 on G1.LINK = G2.LINK_UP and @iLinkG = G1.LINK_UP
		inner join dbo.G_PROV_AP GAP on G2.LINK = GAP.LINK_UP and GAP.DB_KR = 1
		inner join dbo.BI_DICTION_KBK_FULL KBK ON KBK.LINK = GAP.KBK
		LEFT JOIN KL_KBK_LINKED KBKL ON KBKL.LINK = KBK.LINK and @iLinkedKBK = 1
		LEFT JOIN BI_DICTION_KBK_FULL KBK1 ON KBKL.LINK_KBK = KBK1.LINK
		inner join DBO.KOSGU SGU ON SGU.LINK = GAP.SGU
		LEFT join DBO.KOSGU EKR ON EKR.LINK = GAP.EKR
		LEFT OUTER JOIN BD_DOP_CLASSIF DC ON DC.Link = GAP.AP2
		LEFT OUTER JOIN dbo.KL_REG REG ON REG.Link = P.REG
		where P.LINK = @iLinkG
		order by 1,3,5,7,9,11,13
	ELSE
		declare BK_CUR cursor local static read_only for
		select	KBK_CODE = case when @iNotKBK = 1  or @iNotKBK = 0 and (KBK.TYPE = 1 and @iNotVKR = 0) then '' else isnull(KBK1.CODE, KBK.CODE) end, 
				KBK_NAME = case when @iNotKBK = 1  or @iNotKBK = 0 and (KBK.TYPE = 1 and @iNotVKR = 0) then '' else isnull(KBK1.CODE, KBK.NAME) end,
				ADM_CODE = case @iNotVKR when 1 then '' else isnull(KBK1.ADM_CODE, KBK.ADM_CODE) end, 
				ADM_NAME = case @iNotVKR when 1 then '' else isnull(KBK1.ADM_NAME, KBK.ADM_NAME) end, 
				DIV_CODE = case @iNotVKR when 1 then '' else isnull(KBK1.DIV_CODE, KBK.DIV_CODE) end, 
				DIV_NAME = case @iNotVKR when 1 then '' else isnull(KBK1.DIV_NAME, KBK.DIV_NAME) end, 
				CSR_CODE = case @iNotVKR when 1 then '' else isnull(KBK1.CSR_CODE, KBK.CSR_CODE) end, 
				CSR_NAME = case @iNotVKR when 1 then '' else isnull(KBK1.CSR_NAME, KBK.CSR_NAME) end, 
				EXP_CODE = case @iNotVKR when 1 then '' else isnull(KBK1.EXP_CODE, KBK.EXP_CODE) end, 
				EXP_NAME = case @iNotVKR when 1 then '' else isnull(KBK1.EXP_NAME, KBK.EXP_NAME) end,	
				SGU_CODE = isnull(SGU.CODE,''), 
				SGU_NAME = isnull(SGU.NAME,''), 
				EKR_CODE = isnull(EKR.CODE,''), 
				EKR_NAME = isnull(EKR.NAME,''), 
				DOP_CODE = isnull(DC.CODE,''), 
				DOP_NAME = isnull(DC.NAME,''),
				REG_CODE = isnull(REG.CODE,''), 
				REG_CODE_R = isnull(rtrim(REG.CODE) + isnull(@cDELIM,' '),''), 
				REG_NAME = isnull(REG.NAME,''),
				SUMMA	 = sum(G2.SUMMA),
				KBK.TYPE	
		from  dbo.FINANSE_PAYS P
		inner join dbo.G_PROV1 G1 on P.LINK = G1.LINK_UP
		inner join dbo.G_PROV2 G2 on G1.LINK = G2.LINK_UP
		inner join dbo.G_PROV_AP GAP on G2.LINK = GAP.LINK_UP and GAP.DB_KR = 1
		inner join dbo.BI_DICTION_KBK_FULL KBK ON KBK.LINK = GAP.KBK
		LEFT JOIN KL_KBK_LINKED KBKL ON KBKL.LINK = KBK.LINK and @iLinkedKBK = 1
		LEFT JOIN BI_DICTION_KBK_FULL KBK1 ON KBKL.LINK_KBK = KBK1.LINK
		inner join DBO.KOSGU SGU ON SGU.LINK = GAP.SGU
		LEFT join DBO.KOSGU EKR ON EKR.LINK = GAP.EKR
		LEFT OUTER JOIN BD_DOP_CLASSIF DC ON DC.Link = GAP.AP2
		LEFT OUTER JOIN dbo.KL_REG REG ON REG.Link = P.REG
		where P.LINK = @iLinkG
		group by /*isnull(KBK1.CODE, KBK.CODE), isnull(KBK1.CODE, KBK.NAME), 
				isnull(KBK1.ADM_CODE, KBK.ADM_CODE), isnull(KBK1.ADM_NAME, KBK.ADM_NAME), 
				isnull(KBK1.DIV_CODE, KBK.DIV_CODE), isnull(KBK1.DIV_NAME, KBK.DIV_NAME), 
				isnull(KBK1.CSR_CODE, KBK.CSR_CODE), isnull(KBK1.CSR_NAME, KBK.CSR_NAME), 
				isnull(KBK1.EXP_CODE, KBK.EXP_CODE),isnull(KBK1.EXP_NAME, KBK.EXP_NAME),*/
				case when @iNotKBK = 1  or @iNotKBK = 0 and (KBK.TYPE = 1 and @iNotVKR = 0) then '' else isnull(KBK1.CODE, KBK.CODE) end, 
				case when @iNotKBK = 1  or @iNotKBK = 0 and (KBK.TYPE = 1 and @iNotVKR = 0) then '' else isnull(KBK1.CODE, KBK.NAME) end,
				case @iNotVKR when 1 then '' else isnull(KBK1.ADM_CODE, KBK.ADM_CODE) end, 
				case @iNotVKR when 1 then '' else isnull(KBK1.ADM_NAME, KBK.ADM_NAME) end, 
				case @iNotVKR when 1 then '' else isnull(KBK1.DIV_CODE, KBK.DIV_CODE) end, 
				case @iNotVKR when 1 then '' else isnull(KBK1.DIV_NAME, KBK.DIV_NAME) end, 
				case @iNotVKR when 1 then '' else isnull(KBK1.CSR_CODE, KBK.CSR_CODE) end, 
				case @iNotVKR when 1 then '' else isnull(KBK1.CSR_NAME, KBK.CSR_NAME) end, 
				case @iNotVKR when 1 then '' else isnull(KBK1.EXP_CODE, KBK.EXP_CODE) end, 
				case @iNotVKR when 1 then '' else isnull(KBK1.EXP_NAME, KBK.EXP_NAME) end,	
				isnull(SGU.CODE,''), isnull(SGU.NAME,''), isnull(EKR.CODE,''), isnull(EKR.NAME,''), isnull(DC.CODE,''), isnull(DC.NAME,''), isnull(REG.CODE,''), isnull(rtrim(REG.CODE) + isnull(@cDELIM,' '),''), isnull(REG.NAME,''), KBK.TYPE
		order by 1,3,5,7,9,11,13

		open BK_CUR
	fetch next from BK_CUR into @cKBK_CODE, @cKBK_NAME, @cADM_CODE, @cADM_NAME, @cDIV_CODE, @cDIV_NAME, @cCSR_CODE, @cCSR_NAME, @cEXP_CODE, @cEXP_NAME, @cSGU_CODE, @cSGU_NAME, @cEKR_CODE, @cEKR_NAME, @cDOP_CODE, @cDOP_NAME, @cREG_CODE, @cREG_CODE_R, @cREG_NAME, @nSUMMA, @iTypeKbk

	while @@fetch_status = 0
	begin
		--СГУ, ЭКР, Доп.Кл	
		set @cResTemp = rtrim(@cShablon)
		if isnull(@cDOP_CODE,'') = ''
			set @cResTemp = rtrim(dbo.BB_DDELIM_DEL(@cResTemp,'<Доп_кл>'))
		
		if isnull(@cREG_CODE,'') = ''
			set @cResTemp = rtrim(dbo.BB_DDELIM_DEL(@cResTemp,'<Рег_кл>'))
		
		if @iTypeKbk <> 1
			set @cResTemp =  rtrim(dbo.BB_DDELIM_DEL(rtrim(dbo.BB_DDELIM_DEL(@cResTemp,'<ЭКР>')),'<СГУ>'))
		
		--КБК
		if @bGroupBK = 0 or @cKBK_OLD <> @cKBK_CODE
		--	set @cResTemp = replace(replace(replace(@cResTemp,'<КБКР>',replace(@cKBK_CODE,'.',rtrim(case @iTypeKbk when 1 then isnull(@cDELIM,' ') else '' end))),'<КБК>',rtrim(replace(@cKBK_CODE,'.',''))),'<КБК_наим>',@cKBK_NAME)
			set @cResTemp = replace(replace(case @iTypeKbk when 1 then rtrim(replace(@cResTemp,'<КБКР>',rtrim(replace(@cKBK_CODE,'.',isnull(@cDELIM,' '))))) else replace(@cResTemp,'<КБКР>',rtrim(replace(@cKBK_CODE,'.',''))) end,'<КБК>',rtrim(replace(@cKBK_CODE,'.',''))),'<КБК_наим>',@cKBK_NAME)
		
		else
			set @cResTemp = replace(replace(replace(@cResTemp,'<КБКР>',''),'<КБК>',''),'<КБК_наим>','')
		--Администратор
		if @bGroupBK = 0 or @cADM_OLD <> @cADM_CODE
			set @cResTemp = replace(replace(@cResTemp,'<АДМ>',@cADM_CODE),'<АДМ_наим>',@cADM_NAME)
		else
			set @cResTemp = replace(replace(@cResTemp,'<АДМ>',''),'<АДМ_наим>','')
		--Раздел\подраздел
		if @bGroupBK = 0 or @cADM_OLD <> @cADM_CODE
			set @cResTemp = replace(replace(@cResTemp,'<Раздел>',@cDIV_CODE),'<Раздел_наим>',@cDIV_NAME)
		else
			set @cResTemp = replace(replace(@cResTemp,'<Раздел>',''),'<Раздел_наим>','')
		--Целевая статья				 
		if @bGroupBK = 0 or @cADM_OLD <> @cADM_CODE
			set @cResTemp = replace(replace(@cResTemp,'<ЦС>',@cCSR_CODE),'<ЦС_наим>',@cCSR_NAME)
		else
			set @cResTemp = replace(replace(@cResTemp,'<ЦС>',''),'<ЦС_наим>','')--Целевая статья				 
		--Вид расхода				 
		if @bGroupBK = 0 or @cADM_OLD <> @cADM_CODE
			set @cResTemp = replace(replace(@cResTemp,'<ВР>',@cEXP_CODE),'<ВР_наим>',@cEXP_NAME)
		else
			set @cResTemp = replace(replace(@cResTemp,'<ВР>',''),'<ВР_наим>','')
		
		
		set @cResTemp =  replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(@cResTemp,
						'<СГУ>',@cSGU_CODE),'<СГУ_наим>',@cSGU_NAME),
						'<ЭКР>',@cEKR_CODE),'<ЭКР_наим>',@cEKR_NAME),
						'<Доп_кл>',rtrim(@cDOP_CODE)),'<Доп_кл_наим>',@cDOP_NAME),
						'<Рег_кл>',rtrim(@cREG_CODE)), '<Рег_клР>',@cREG_CODE_R),'<Рег_кл_наим>',@cREG_NAME),
						'<Руб>',rtrim(ltrim(str(cast(@nSUMMA as int))))),'<Коп>', right('00' + rtrim(ltrim(str((@nSUMMA - cast(@nSUMMA as int)) * 100))),2))
		
		
	
		if @cRes = ''
			set @cRes = rtrim(@cResTemp)
		else 
			set @cRes = @cRes + isnull(@cDELIM5,'') + rtrim(@cResTemp)
		 
		select @cKBK_OLD = @cKBK_CODE, @cADM_OLD = @cADM_CODE, @cDIV_OLD = @cDIV_CODE, @cCSR_OLD = @cCSR_CODE, @cEXP_OLD = @cEXP_CODE
		fetch next from BK_CUR into @cKBK_CODE, @cKBK_NAME, @cADM_CODE, @cADM_NAME, @cDIV_CODE, @cDIV_NAME, @cCSR_CODE, @cCSR_NAME, @cEXP_CODE, @cEXP_NAME, @cSGU_CODE, @cSGU_NAME, @cEKR_CODE, @cEKR_NAME, @cDOP_CODE, @cDOP_NAME, @cREG_CODE, @cREG_CODE_R, @cREG_NAME, @nSUMMA, @iTypeKbk
	
	end
	close BK_CUR
	deallocate BK_CUR
end
RETURN @cRes
end

GO


GRANT EXECUTE ON dbo.[BB_BK_FOR_SHABLON] TO PUBLIC

GO



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

GO



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


CREATE          VIEW [dbo].AVANCE_ACCEPT_TABLE_VIEW
AS

Select 
	F.LINK, 
	F.LINK_UP, 
	F.KBK, 
	F.EKR,
	F.DOP_CLASS AS DOP,
	[RECORD_NO] = convert(NUMERIC(9), F.RECORD_NO),
	[KBK_CODE] = KBK.CODE,
	[KBK_NAME] = KBK.[NAME],
	[EKR_CODE] = EKR.CODE,
	[EKR_NAME] = EKR.[NAME],
	[DOP_CODE] = DOP.CODE,
	[DOP_NAME] = DOP.[NAME],
	f.summa,
	f.acc_dt,
	f.acc_kt,
	[codeacc_dt] = sa.code,
	[codeacc_kt] = sa1.code


From AVANCE_ACCEPT_TABLE F  
LEFT JOIN dbo.bi_diction_kbk KBK ON KBK.LINK = F.KBK
LEFT JOIN dbo.KOSGU EKR ON EKR.LINK = F.EKR
LEFT JOIN dbo.DOP_CLASSIF DOP ON DOP.LINK = F.DOP_CLASS
LEFT JOIN dbo.s_accounts sa ON sa.LINK = f.acc_dt
LEFT JOIN dbo.s_accounts sa1 ON sa1.LINK = f.acc_kt



GO


GRANT SELECT ON dbo.[AVANCE_ACCEPT_TABLE_VIEW] TO PUBLIC

GO



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

GO


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

CREATE  VIEW [dbo].ADVANCE_CASH_TABLE_VIEW
AS


Select 
	F.LINK, 
	F.LINK_UP, 
	[RECORD_NO] = convert(NUMERIC(9), F.RECORD_NO),

	[KBK] = F.KBK, 
	[KBK_CODE] = KBK.CODE,
	[KBK_NAME] = KBK.NAME,

	[EKR] = F.EKR, 
	[EKR_CODE] = EKR.CODE,
	[EKR_NAME] = EKR.NAME,

	[SYMBOL] = F.SYMBOL,
	[SUMMA] = F.SUMMA

From ADVANCE_CASH_TABLE F  
LEFT JOIN dbo.bi_diction_kbk KBK ON KBK.LINK = F.KBK
LEFT JOIN dbo.KOSGU EKR ON EKR.LINK = F.EKR



GO


GRANT SELECT ON dbo.[ADVANCE_CASH_TABLE_VIEW] 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(30),
	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),
	[DAY_VAC_O] NUMERIC(2),
	[DAY_VAC_D] NUMERIC(2)
	
)

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),
	[DAY_VAC_O] = s.days_vac_o, 
	[DAY_VAC_D] = s.days_vac_d
	
	
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.[ORDER_MONEY_PERIOD]') AND OBJECTPROPERTY(id, N'IsView') = 1)
DROP VIEW dbo.[ORDER_MONEY_PERIOD]

GO


CREATE  VIEW dbo.ORDER_MONEY_PERIOD
AS
SELECT MP.LINK,
	MP.ITEM_LINK,
	IM.EMPL_LINK,
	[TAB] = dbo.ku_GetEmplTab(im.empl_link),
	[FIO] = dbo.ku_GetEmplFIO(im.empl_link), 
	MP.PAY_LINK,
	[PAY_CODE] = P.CODE,
	[PAY_NAME] = P.NAME,
	MP.DATE_BEGIN,
	DATE_END = (CASE WHEN OT.OBJ_CODE = 'MONEY_CHANGE' THEN  IM.DATE_END2 ELSE MP.DATE_END END),
	[VALUE]	=(case when wc.ETS <> 0 AND WC.ISPERCENT = 2 then ISNULL(koef,0)
					else ISNULL(MP.SUMMA,0)
				end),
	[SUMMA]	= ISNULL(S.SUMMA,0),
	[ISOKLAD] = WC.oklad,
	[ISPERCENT] = WC.ISPERCENT,--CASE WHEN WC.ISPERCENT = 0 THEN 0 ELSE 1 END,
	P.WAY_CALC,
	IM.ORDER_LINK,
	[ORDER_NUM] = O.NUMBER,
	[DATE] = O.DATE,
	[ORDER_TYPE] = OT.CODE,
	[ORDER_NAME] = OT.NAME,
	O.DEP_LINK,
	[DOING_CODE] = case when MP.SUMMA=0 then 1 else 0 end,
	[DOING] = case when MP.SUMMA=0 then 'Отменено' else 'Назначено' end,
	IM.NEW_FACE,
	IM.ACTIVE,
	[FLAG_JC] = case when exists(SELECT * FROM pays_empl WHERE link_mp=mp.link) then 1 else 0 end,
	MP.BEFORE105,
	com = CASE WC.ISPERCENT 
				WHEN 0 THEN 'руб.'
				WHEN 1 THEN '%'
				WHEN 2 THEN 'руб.(разр.' + LTRIM(RTRIM(CONVERT(VARCHAR(20),im.ETS_RAZR)))+ ')'
				WHEN 3 THEN 'руб.(коэф.' + LTRIM(RTRIM(CONVERT(VARCHAR(20),MP.SUMMA))) + ')'
				WHEN 4 THEN 'коэф.(' + LTRIM(RTRIM(CONVERT(VARCHAR(20),MP.SUMMA))) + ')'
			END
FROM 
	dbo.MONEY_PERIOD MP 
	INNER JOIN dbo.PAYS P ON MP.PAY_LINK=P.LINK
	INNER JOIN dbo.WAY_CALC WC ON P.WAY_CALC=WC.CODE AND WC.TYPE=1
	INNER JOIN dbo.ITEM_MOVE IM ON MP.ITEM_LINK=IM.LINK
	INNER JOIN dbo.ORDERS O ON IM.ORDER_LINK=O.LINK
	INNER JOIN dbo.ORDER_TYPES OT ON O.TYPE=OT.CODE
	LEFT JOIN dbo.sa_all_pays_order_money_date(DEFAULT,DEFAULT,DEFAULT) S ON S.item_link = MP.ITEM_LINK AND S.LINK_PAY = MP.PAY_LINK
	LEFT JOIN dbo.sa_ets_actual(default) ETS on ETS.link = P.link_ets and ets.razr = im.ETS_RAZR



GO


GRANT SELECT ON dbo.[ORDER_MONEY_PERIOD] 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,
	[DAY_VAC_O] = CASE WHEN isnull(s.days_vac_o,0)=0 
						then (case when isnull(s.gossl,0)=0 then 28 else case when GG.code in (1, 2) then 35 else 30 end END)
					 	ELSE s.days_vac_o END , 
	[DAY_VAC_D] = s.days_vac_d
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.[SALARY_EMPL_SALDO_YEAR_VKR]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[SALARY_EMPL_SALDO_YEAR_VKR]
GO


CREATE          function DBO.SALARY_EMPL_SALDO_YEAR_VKR(@varKSLinkEmpl  int, @varKSYear INT,@varKSlinkVKR int, @LINK_EKR INT = 0)
RETURNS NUMERIC(18,2)
AS  
BEGIN
DECLARE @varKSResult  NUMERIC(18,2),  @varKSResultTemp  NUMERIC(18,2)

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

set  @varKSResult =isnull( dbo.SALARY_EMPL_SALDO_VKR(@varKSLinkEmpl, @varKSYear,@varKSlinkVKR,@LINK_EKR),0)

select @varKSResultTemp = sum(summa) 
from dbo.s_j_c_short
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = 'R211') R211
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = '211') T211
where 
		LINK_EMPL = @varKSLinkEmpl and typ_oper = 1 
		and (LINK_VKR = @varKSlinkVKR OR @varKSlinkVKR = 0)and year_begin = @varKSYear
		AND ((CASE WHEN R211.LINK = LINK_EKR THEN T211.LINK ELSE LINK_EKR END) = @LINK_EKR OR @LINK_EKR = 0)

set  @varKSResult =@varKSResult +isnull( @varKSResultTemp,0)


select @varKSResultTemp = sum(summa) 
from dbo.s_j_c_short 
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = 'R211') R211
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = '211') T211
where LINK_EMPL = @varKSLinkEmpl and typ_oper = 2 
		and (LINK_VKR = @varKSlinkVKR OR @varKSlinkVKR = 0) and year_begin = @varKSYear
		AND ((CASE WHEN R211.LINK = LINK_EKR THEN T211.LINK ELSE LINK_EKR END) = @LINK_EKR OR @LINK_EKR = 0)

set  @varKSResult =@varKSResult -isnull( @varKSResultTemp,0)


RETURN isnull(@varKSResult,0)
end

GO


GRANT EXECUTE ON dbo.[SALARY_EMPL_SALDO_YEAR_VKR] TO PUBLIC

GO

GO

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

GO

CREATE FUNCTION DBO.SALARY_EMPL_SALDO_MONTH_VKR
(@VARKSLINKEMPL  INT, @VARKSDATE1 DATETIME,@VARKSLINKVKR INT, @LINK_EKR INT = 0)
RETURNS NUMERIC(15,2)
AS  
BEGIN
DECLARE @VARKSRESULT  NUMERIC(15,2),  @VARKSRESULTTEMP  NUMERIC(15,2)

SET @VARKSLINKVKR = COALESCE(@VARKSLINKVKR,0)
SET @LINK_EKR = COALESCE(@LINK_EKR,0)
SET  @VARKSRESULT =ISNULL( DBO.SALARY_EMPL_SALDO_VKR(@VARKSLINKEMPL, YEAR(@VARKSDATE1),@VARKSLINKVKR, @LINK_EKR),0)

DECLARE @VEDOM_ZP TABLE (LINK INT)
INSERT INTO @VEDOM_ZP (LINK)
	Select link_up from dbo.SDOC_VEDOM where TYP_PAYMENT = 1
	union all
	Select link_up from dbo.SDOC_VEDOM_DGH where TYP_PAYMENT = 1


SELECT @VARKSRESULTTEMP = SUM(CASE WHEN  P.OBJECT = 1 THEN SUMMA ELSE 0 END) -  
							SUM(CASE WHEN  P.OBJECT =  2 THEN SUMMA ELSE 0 END)
FROM
	DBO.CALCULATE_JURNAL JC
	INNER JOIN DBO.PAYS P ON JC.LINK_PAYS = P.LINK
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = 'R211') R211
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = '211') T211	
	INNER JOIN dbo.KOSGU S ON S.LINK = (CASE WHEN R211.LINK = ISNULL(JC.LINK_EKR,P.LINK_EKR) THEN T211.LINK ELSE ISNULL(JC.LINK_EKR,P.LINK_EKR) END)
	LEFT JOIN @VEDOM_ZP A ON A.LINK = JC.LINK_DOC
WHERE 
	JC.LINK_EMPL = @VARKSLINKEMPL 
	AND (JC.LINK_VKR = @VARKSLINKVKR OR @VARKSLINKVKR = 0)
	AND (S.LINK = @LINK_EKR OR @LINK_EKR = 0)
	AND 
	(
		(COALESCE(A.LINK,0) = 0  or YEAR(JC.DATE_BEGIN) = YEAR(JC.DATE_BEGIN))AND YEAR(JC.PERIOD_BEGIN) = YEAR(@VARKSDATE1) AND MONTH(JC.PERIOD_BEGIN) < MONTH(@VARKSDATE1)
		OR --ДЛЯ ВЕДОМОСТЕЙ ОПЕРАЦИИ БЕРЕМ ПО ПЕРИОДУ РАСЧЕТА
		NOT (COALESCE(A.LINK,0) = 0  or YEAR(JC.DATE_BEGIN) = YEAR(JC.DATE_BEGIN)) AND YEAR(JC.DATE_BEGIN) = YEAR(@VARKSDATE1) AND MONTH(JC.DATE_BEGIN) < MONTH(@VARKSDATE1)
	) 

SET  @VARKSRESULT =@VARKSRESULT +ISNULL( @VARKSRESULTTEMP,0)


RETURN ISNULL(@VARKSRESULT,0)
END

GO


GRANT EXECUTE ON dbo.[SALARY_EMPL_SALDO_MONTH_VKR] TO PUBLIC

GO


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

GO

CREATE VIEW [dbo].KU_EMPL_ATTEST
AS
SELECT	
	EA.LINK,
	EA.EMPL_LINK,
	KU_EMPL.TAB,
	KU_EMPL.FIO AS EMPL_FIO,
	KU_EMPL.FM,
	KU_EMPL.IM,
	KU_EMPL.OT,
	[TYPE] = 0,
	[TYPE_TXT] = '',
	[NUMBER] = '',
	[STATUS] = ISNULL(KU_EMPL.[STATUS],0),
	[status_txt] = '', 
	[SUBDIV_LINK] = KU_EMPL.SUBDIV_LINK,
	[SUBDIV_NAME] = KU_EMPL.SUBDIV_NAME,
	[POST_NAME] = KU_EMPL.POST_NAME,
	[STAFF_HEAD] = KU_EMPL.STAFF_HEAD,
	EA.DATE,
	EA.ATT_LINK,
	ATT_CODE = CONVERT(varchar(2), D.CODE),
	ATT_NAME = CONVERT(varchar(254), D.NAME),
	EA.DOC_NUM,
	EA.DOC_DATE,
	EA.REASON,
	EA.ATT_KOM_LINK,
	A_K.NAME as ATT_KOM_NAME,
	EA.DATE_BEGIN,
	EA.DATE_END,
	EA.LINK_SKILL,
	S.[CODE] as SKILL_CODE,
	S.[NAME] as SKILL_NAME,
	EA.LINK_KV_CATEG,
	KC.[CODE] as KV_CATEG_CODE,
	KC.[NAME] as KV_CATEG_NAME,
	EA.ATT_QUESTION AS [ATT_QUESTION],
	[SHORT_COMM] = EA.SHORT_COMM,
	[COMMENT] = EA.COMMENT,
	ORDER_LINK = IM.ORDER_LINK,
	comm = ' Приказ №' + LTRIM(RTRIM(coalesce(o.number, ''))) + ' об изменении оплаты труда от ' + convert(varchar(10),o.date,104)+'' 
FROM EMPL_ATTEST EA LEFT JOIN DICTION D ON EA.ATT_LINK=D.LINK
	LEFT JOIN ATTESTAT_KOMISSION A_K ON EA.ATT_KOM_LINK = A_K.link
	LEFT JOIN KU_EMPL_PLACING KU_EMPL ON EA.EMPL_LINK = KU_EMPL.LINK
	LEFT JOIN ITEM_MOVE IM on IM.REF_ATT = EA.LINK 
	LEFT JOIN ORDERS O ON  O.LINK = IM.ORDER_LINK 
	LEFT JOIN dbo.PROFESSIONAL_SKILL S ON S.LINK = EA.LINK_SKILL
	LEFT JOIN dbo.KV_CATEGORY KC ON KC.LINK = EA.LINK_KV_CATEG
where	KU_EMPL.dep_link = (select dep_link from user_dep)


GO


GRANT SELECT ON dbo.[KU_EMPL_ATTEST] TO PUBLIC

GO



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

GO
CREATE FUNCTION dbo.sa_expected_vacation (@dDate datetime)
--НОРМА ОТПУСКА ПО ШР И ОСТАТКАМ НЕИСПОЛЬЗОВАННЫХ ОТПУСКОВ НА ДАТУ РАСЧЕТА
RETURNS TABLE
/*Возвраящает информацию по ожидаемому количеству дней отпуска в текущем году, по состоянию на дату
Расчет: {Продолжительность отпуска по штатному расписанию} + {Продолжительность по стажу} + {Остатки отпусков по состоянию на текущий год} */
RETURN

WITH 
ASL --ACTUAL_STAFF_LIST АКТУАЛЬНОЕ ШР
AS (
SELECT S.LINK, S.LINK_UP, S.DAYS_VAC_O, S.DAYS_VAC_D
FROM 
	dbo.staff s WITH (NOLOCK)
	CROSS APPLY (SELECT ISNULL(MIN(S2.DATE_BEGIN)-1,DATEADD(YEAR, DATEDIFF(YEAR, -1, @dDate), -1)) AS DATE_END 
					FROM dbo.staff S2 WITH (NOLOCK) WHERE S2.LINK_UP = S.LINK_UP AND S2.DATE_BEGIN > S.DATE_BEGIN) D
WHERE
	@dDate BETWEEN S.DATE_BEGIN AND D.DATE_END
),
GOS
AS (
	SELECT empl_link, CASE WHEN years > 10 THEN 10 ELSE years END AS VAC_DS FROM dbo.sa_EmplExpirTable(DEFAULT,@dDate,0,DEFAULT) WHERE expir_code = 'GOS_NADB' AND years > 0
),
SPR 
AS	(
SELECT 
	NU.EMPL_LINK, 
	SUM((CASE WHEN VAC_V = 3 THEN [DAYS] ELSE 0 END)) AS D_MAIN, 
	SUM((CASE WHEN VAC_V = 2 THEN [DAYS] ELSE 0 END)) AS D_ADD 
FROM
	dbo.EMPL_VAC_NOTUSED NU
	INNER JOIN dbo.VACATION_VID	VV ON VV.LINK = NU.VAC_LINK
	CROSS APPLY (SELECT ISNULL(MIN(S2.[DATE])-1,DATEADD(YEAR, DATEDIFF(YEAR, -1, '20151231'), -1)) AS DATE_END 
					FROM dbo.EMPL_VAC_NOTUSED S2 WITH (NOLOCK) 
						WHERE YEAR(NU.[DATE]) = YEAR(@dDate) 
							AND S2.EMPL_LINK = NU.EMPL_LINK AND S2.[DATE] > NU.[DATE]) D
WHERE
	@dDate BETWEEN NU.[DATE] AND D.DATE_END
	AND
	(VAC_V = 2 OR VAC_V = 3)
	AND
	YEAR(NU.[DATE]) = YEAR(@dDate)
GROUP BY
	NU.EMPL_LINK
)
--НОРМА ОТПУСКА
SELECT
	IM.EMPL_LINK,
	STAFF_HEAD = IM.STAFF_LINK,
	STAFF_LINK = ASL.LINK,
	VAC_MAIN = ASL.DAYS_VAC_O + ISNULL(SPR.D_MAIN,0),
	VAC_ADD = ISNULL(ASL.DAYS_VAC_D,0) + ISNULL(GOS.VAC_DS,0) + ISNULL(SPR.D_ADD,0)
FROM 
	dbo.sa_item_move IM WITH (NOLOCK)
	INNER JOIN ASL ON ASL.LINK_UP = IM.STAFF_LINK
	LEFT JOIN DBO.ITEM_DIS_FACE IDF with (nolock) ON IDF.EMPL_LINK = IM.EMPL_LINK AND IDF.ACTIVE=1
	LEFT JOIN GOS WITH (NOLOCK) ON GOS.EMPL_LINK = IM.EMPL_LINK
	LEFT JOIN SPR WITH (NOLOCK) ON SPR.EMPL_LINK = IM.EMPL_LINK
WHERE
	@dDate BETWEEN (CASE WHEN IM.DATE_BEGIN < DATEADD(YEAR, DATEDIFF(YEAR, 0, @dDate), 0) THEN DATEADD(YEAR, DATEDIFF(YEAR, 0, @dDate), 0) ELSE IM.DATE_BEGIN END)
				AND (CASE WHEN ISNULL(IDF.DIS_DATE,DATEADD(YEAR, DATEDIFF(YEAR, -1, @dDate), -1)) < IM.date_end3 THEN ISNULL(IDF.DIS_DATE,DATEADD(YEAR, DATEDIFF(YEAR, -1, @dDate), -1)) ELSE IM.date_end3 END)
GO

GRANT SELECT ON dbo.[sa_expected_vacation] TO PUBLIC

GO


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

GO


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

CREATE   VIEW [dbo].MONEY_CHANGE
AS
SELECT im.link, o.number, o.date, o.dep_link, im.empl_link, 
	[tab_num] = dbo.ku_GetEmplTab(im.empl_link), [fio] = dbo.ku_GetEmplFIO(im.empl_link), 
	[subdiv] = dbo.ku_GetEmplSubdivName(im.empl_link, im.date_begin-1), 
	[post] = dbo.ku_GetEmplPostName(im.empl_link, im.date_begin-1),
	im.date_begin, im.date_end2, im.new_face, im.order_link, im.REF_ATT
FROM item_move im inner join orders o on im.order_link=o.link and im.new_face=3
	INNER JOIN USER_INFO UI ON (UI.CODE_TASK = 'KADRY' OR UI.DEP_LINK = O.DEP_LINK)



GO


GRANT SELECT ON dbo.[MONEY_CHANGE] TO PUBLIC

GO



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

GO

/*
© Кейсистемс (Keysystems), 2007
*/
CREATE       FUNCTION dbo.ku_EmplNormVacation (
	@dDate datetime = null)
RETURNS @T TABLE (link int, dep_link int, tab varchar(10), fio varchar(254),vid_link int, post_name varchar(254), gossl int,
	gr_gos_code char(1), per_beg datetime, per_end datetime,  vid_name varchar(254),
	days int, used int, not_used int, itogUs int, itogNotUs int)
AS
BEGIN

DECLARE @dBeginYear datetime, @dEndYear datetime, @ezh_link int, @dop_link int, @countDate datetime
SELECT @ezh_link = link FROM vacation_vid WHERE code='01'
SELECT @dop_link = link FROM vacation_vid WHERE code='24'

--добавляем записи из остатков
INSERT INTO @T (link, dep_link, tab, fio, post_name, gossl, gr_gos_code, per_beg, per_end,
		 vid_link, vid_name, days, used)
SELECT empl_link, dep_link, tab, fio, dbo.ku_GetEmplPostName(empl_link, @dDate), 0, '', 
	period_begin, period_end, vac_link, vac_name, days, 0
FROM vac_notused


SELECT @countDate = min(date) FROM empl_vac_notused

WHILE @countDate<@dDate BEGIN
	SELECT @dBeginYear = dbo.DateBeginOfYear(@countDate), @dEndYear = dbo.DateEndOfYear(@countDate)
	
	INSERT INTO @T (link, dep_link, tab, fio, post_name, gossl, gr_gos_code, per_beg, per_end, vid_link, vid_name)
	SELECT e.link, e.dep_link, e.tab, e.fio, e.post_name, isnull(s.gossl, 0), s.gr_gos_code, @dBeginYear, @dEndYear, vv.link, vv.name
	FROM dbo.ku_empl_placing_fn(@countDate) e
	INNER JOIN dbo.dictionary_staff_fn(@countDate) s ON s.link=e.staff_head
	INNER JOIN vacation_vid vv ON vv.code='01' or vv.code='24'-- and s.gossl>0
	WHERE 0 = (SELECT top 1 sack FROM dbo.ku_empl_placing_fn(@dDate) ku WHERE ku.tab = e.tab) -- не включаем уволенных в отчет

	--норма основного отпуска
	UPDATE @T SET days = case when gossl=0 then 28 else case when gr_gos_code in (1, 2) then 35 else 30 end end
	WHERE vid_link=@ezh_link and per_beg=@dBeginYear
	
	--норма дополнительного отпуска - день за год стажа
	UPDATE @T SET days = dbo.ku_GetEmplExpir(link, 'YEAR', 'GOS_NADB', @countDate)
	WHERE vid_link=@dop_link and per_beg=@dBeginYear

	--дополнительный отпуск не может быть более 10 дней
	UPDATE @T SET days = 10
	WHERE vid_link=@dop_link and days>10 and per_beg=@dBeginYear

	--удаляем те записи, где нормы отпусков=0
	DELETE FROM @T WHERE days=0
	
	--вычисляем количество использованных дней из использованных отпусков
	UPDATE @T SET used = 
			isnull((SELECT sum(dbo.ku_WithoutHolidayCount(date_begin, date_end)) 
			FROM item_vacation 
			WHERE empl_link=t.link and type_link=t.vid_link and active=1
				and per_beg between @dBeginYear and @dEndYear), 0)
	FROM @T t
	WHERE per_beg=@dBeginYear


	SET @countDate = dateadd(year, 1, @countDate)

--вычисляем неиспользованные дни
UPDATE @T SET not_used = days-used
END

--вычисляем итого использованных/неиспользов.отпусков по каждому виду отпуска
UPDATE T
SET itogUs = (SELECT sum(N.used)
				FROM @T N
				WHERE N.link = T.link and N.tab = T.tab and N.vid_name = T.vid_name),

	itogNotUs = (SELECT sum(N.not_used)
				FROM @T N
				WHERE N.link = T.link and N.tab = T.tab and N.vid_name = T.vid_name)
FROM @T T

RETURN
END




GO


GRANT SELECT ON dbo.[ku_EmplNormVacation] TO PUBLIC

GO



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

GO

/*
© Кейсистемс (Keysystems), 2007
*/
--SELECT * FROM dbo.ku_EmplNormVacationR('20061201') where year(per_beg) = year('20061201') order by tab, per_beg 
CREATE       FUNCTION dbo.ku_EmplNormVacationR (@DATE datetime)
RETURNS TABLE 

RETURN

WITH SUB AS
(
SELECT S.LINK_UP, S.NAME, S.DATE_BEGIN, D.DATE_END
FROM
	dbo.SUBDIV S
	CROSS APPLY (SELECT ISNULL(MIN(S2.DATE_BEGIN)-1,DATEADD(YEAR, DATEDIFF(YEAR, -1, @DATE), -1)) AS DATE_END 
		FROM dbo.SUBDIV S2 WITH (NOLOCK) WHERE S2.LINK_UP = S.LINK_UP AND S2.DATE_BEGIN > S.DATE_BEGIN) D
WHERE
	@DATE BETWEEN S.DATE_BEGIN AND D.DATE_END	
)

SELECT 
	EV.EMPL_LINK AS LINK
	,E.DEP_LINK
	,E.TAB
	,LTRIM(RTRIM(P.FM)) + ' ' + LTRIM(RTRIM(P.IM)) + ' ' + LTRIM(RTRIM(P.OT)) AS FIO
	,SUB.NAME AS SUB_NAME
	,PT.NAME AS post_name
	,ST.GOSSL
	,GG.CODE AS gr_gos_code
	,DATEADD(YEAR, DATEDIFF(YEAR, 0, @DATE), 0) AS per_beg
	,DATEADD(YEAR, DATEDIFF(YEAR, -1, @DATE), -1) AS per_end
	,(EV.VAC_MAIN + EV.VAC_ADD) AS [DAYS]
	,(ISNULL(UV.DVM,0) - ISNULL(UV.DHM,0)) +  (ISNULL(UV.DVA,0) - ISNULL(UV.DHM,0)) AS [USED]
	,EV.VAC_MAIN AS [day_vac_o]
	,EV.VAC_ADD AS [day_vac_d]
	,(ISNULL(UV.DVM,0) - ISNULL(UV.DHM,0)) AS [USED_O] 
	,(ISNULL(UV.DVA,0) - ISNULL(UV.DHA,0)) AS [USED_D] 
	,EV.VAC_MAIN - (ISNULL(UV.DVM,0) - ISNULL(UV.DHM,0)) AS [not_us_o] 
	,EV.VAC_ADD - (ISNULL(UV.DVA,0) - ISNULL(UV.DHA,0)) AS [not_us_D] 	
FROM
	dbo.sa_expected_vacation(@DATE) EV
	INNER JOIN dbo.EMPL E ON E.LINK = EV.EMPL_LINK
	INNER JOIN dbo.PERSON P ON P.LINK = E.PERS_LINK
	INNER JOIN dbo.STAFF ST ON ST.LINK = STAFF_LINK
	INNER JOIN SUB ON ST.SUBDIV_LINK = SUB.LINK_UP
	INNER JOIN dbo.POST PT ON ST.POST_LINK = PT.LINK
	INNER JOIN dbo.GR_GOS GG ON GG.LINK = ST.gr_gos_link
	LEFT JOIN dbo.sa_used_vacation(@DATE) UV ON EV.EMPL_LINK = UV.EMPL_LINK


GO


GRANT SELECT ON dbo.[ku_EmplNormVacationR] 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.[CalcNalogBalanceOS]') AND xtype in (N'FN', N'IF', N'TF'))
DROP FUNCTION dbo.[CalcNalogBalanceOS]
GO

--- Функция вычисляет объекты для налога на имущества ---
CREATE FUNCTION dbo.CalcNalogBalanceOS (@dDate DATETIME = NULL, @intDepLink INT = NULL)
-- Если @intDepLink = NULL то расчет без учета DEP_LINK, т.е. для всех организаций
-- NO_NALOG = 0 Включается в базу по налогу на имущество
-- NO_NALOG = 1 Не включается в базу по налогу на имущество (льготируемое имущесвто)
-- NO_NALOG = 2 Включается в базу по налогу на имущество ставка налога = 0 
RETURNS @varKSOUT_TABLE TABLE
	(	DEP_LINK	INT,
		[ACCOUNT] [INT],
		[GRP_CODE] [CHAR] (8) NOT NULL,
		[INV]	[INT] NOT NULL,
		[OST_SUM] [NUMERIC] (20,2) NULL,
		[BALANS] [NUMERIC] (20,2) NULL,
		[AMORT] [NUMERIC] (20,2) NULL,
		[NO_NALOG] TINYINT NOT NULL,
		[DATE_BEGIN] DATETIME NULL,
		FIRST_BALANS	NUMERIC (20,2) NULL,
		FIRST_AMORT		NUMERIC (20,2) NULL,
		AM_GRP	VARCHAR (5),
		YEAR_BEGIN	INT
	)
AS
BEGIN
	DECLARE
		@AMORT_FULL NUMERIC (28,2),
		@DATE_BEGIN	DATETIME,
		@intNOT_USE_NASTR	INT,
		@intACCOUNT	INT,
		@dDATE_REST	DATETIME,
		@YEAR_CALC	INT,
		@ADD_REST	TINYINT

	IF @dDate IS NULL
		SELECT @dDate = WORKDATE FROM dbo.USER_INFO

	SET @intNOT_USE_NASTR = ISNULL (dbo.XK_GET_NASTR_INT ('XK_NASTR_ND_AV_ASS_ALL_OS'), 0)
	
	IF @intNOT_USE_NASTR = 0
	BEGIN
		SELECT @AMORT_FULL = dbo.BK_GET_AMORT_FULL_TAX (@dDate)

		SELECT @DATE_BEGIN = MAX (DATE_BEGIN) FROM dbo.AMORT_FULL_TAX T2
		WHERE T2.DATE_BEGIN <= @dDate
	END
	ELSE 
		SET @AMORT_FULL = 0

	SET @ADD_REST = CASE
						WHEN dbo.DateBeginOfMonth (@dDate) = @dDate THEN 0
						ELSE 1
					END	

	SET @YEAR_CALC = YEAR (@dDate) 

	---	Изменения в НК в 2013 (с учетом изменеий в 2014) ---
	DECLARE @TAB_INPUT_INV TABLE
		(INV	INT,
		DEP_LINK	INT,
		DATE_OPER	DATETIME
		)

	IF @YEAR_CALC >= 2013 
		INSERT INTO @TAB_INPUT_INV
		SELECT
			INV.LINK,
			INV.DEP_LINK,
			ISNULL (A1.DATE_BEGIN, T1.DATE_OPER)
		FROM dbo.INVENTORY INV 
		INNER JOIN dbo.NOMENCLATURE NOMEN ON (NOMEN.LINK = INV.NOMENCLATURE)	
		LEFT JOIN (
					SELECT 
						TTT.INV,
						DATE_OPER = MIN (TTT.DATE_OPER)
					FROM dbo.BK_GetTableOperINV
						(DEFAULT,
						'20130101',
						@dDATE,
						2,
						@intDepLink) TTT
					GROUP BY
						TTT.INV) AS T1 ON (T1.INV = INV.LINK)
		LEFT JOIN dbo.ASSETS A1 ON (A1.LINK_UP = INV.LINK)
		GROUP BY
			INV.LINK,
			INV.DEP_LINK,
			ISNULL (A1.DATE_BEGIN, T1.DATE_OPER)
		HAVING
			ISNULL (YEAR (ISNULL (A1.DATE_BEGIN, T1.DATE_OPER)), 0) >= 2013

	SET @dDATE_REST	= @dDate

	-- Балансовая стоимость --
	DECLARE @T_BALANS TABLE
		(
		DEP_LINK	INT,
		ACCOUNT		INT,
		INV			INT,
		TAX_MODE	TINYINT,
		DATE_IN		DATETIME,
		BALANS		NUMERIC (28,4),
		QTY			NUMERIC (28,4)
		)

	SELECT
		@intACCOUNT = LINK
	FROM dbo.S_ACCOUNTS
	WHERE CODE = '101'	

	INSERT INTO @T_BALANS 
		(
		DEP_LINK,
		ACCOUNT,
		INV,
		TAX_MODE,
		DATE_IN,
		BALANS,
		QTY
		)
	SELECT
		R.DEP_LINK,
		R.ACCOUNT,
		ISNULL (R.INV, 0),
		CASE
			WHEN R.INV IS NULL THEN 0
			ELSE 2
		END,
		T1.DATE_OPER,
		SUM (R.D_SUMMA),
		SUM (R.D_QUANTITY)
	FROM (
		SELECT
			TR.DEP_LINK,
			TR.ACCOUNT,
			TR.INV, 
			TR.D_SUMMA,
			TR.D_QUANTITY
		FROM dbo.ARestTableByDate (@dDATE_REST, @intACCOUNT) TR
		
		UNION ALL
		
		SELECT
			TS.DEP_LINK,
			TS.ACCOUNT,
			TS.INV, 
			TS.D_SUMMA,
			TS.D_QUANTITY
		FROM dbo.SALDO_CLEARED TS
		INNER JOIN dbo.S_ACCOUNTS SA ON
			(SA.cSINTH = '101'
			AND SA.LINK = TS.ACCOUNT)
		WHERE @ADD_REST = 1
			AND TS.ISOBOROT = 1
			AND TS.[DATE] = @dDATE_REST 
		) AS R
	LEFT JOIN @TAB_INPUT_INV T1 ON (T1.INV = R.INV)
	WHERE (@intDepLink IS NULL OR @intDepLink IS NOT NULL AND R.DEP_LINK = @intDepLink)
	GROUP BY 
		R.DEP_LINK,
		R.ACCOUNT,
		R.INV,
		CASE
			WHEN T1.INV IS NULL THEN 0
			ELSE 2
		END,
		T1.DATE_OPER
	HAVING
		SUM (R.D_QUANTITY) <> 0 OR SUM (R.D_SUMMA) <> 0		

	-- Амортизация --
	DECLARE @T_AMORT TABLE
		(
		DEP_LINK	INT,
		INV			INT,
		SUMMA		NUMERIC (28,4)
		)

	SELECT
		@intACCOUNT = LINK
	FROM dbo.S_ACCOUNTS
	WHERE CODE = '104'	

	INSERT INTO @T_AMORT 
		(
		DEP_LINK,
		INV,
		SUMMA
		)
	SELECT
		T1.DEP_LINK,
		ISNULL (T1.INV, 0),
		SUM (T1.K_SUMMA)
	FROM (
		SELECT
			TR.DEP_LINK,
			TR.INV, 
			TR.K_SUMMA,
			TR.K_QUANTITY
		FROM dbo.ARestTableByDate (@dDATE_REST, @intACCOUNT) TR
		
		UNION ALL
		
		SELECT
			TS.DEP_LINK,
			TS.INV, 
			TS.K_SUMMA,
			TS.K_QUANTITY
		FROM dbo.SALDO TS
		INNER JOIN dbo.S_ACCOUNTS SA ON
			(SA.cSINTH = '104'
			AND SA.LINK = TS.ACCOUNT)
		WHERE @ADD_REST = 1
			AND TS.ISOBOROT = 1
			AND TS.[DATE] = @dDATE_REST 
		) AS T1
	WHERE (@intDepLink IS NULL OR T1.DEP_LINK = @intDepLink)
	GROUP BY 
		T1.DEP_LINK,
		T1.INV

	--- !!!Результат!!! ---
	INSERT @varKSOUT_TABLE
		(DEP_LINK,
		ACCOUNT,
		INV,
		BALANS,
		GRP_CODE,
		NO_NALOG,
		DATE_BEGIN,
		AMORT,
		OST_SUM,
		FIRST_BALANS,
		FIRST_AMORT,
		AM_GRP,
		YEAR_BEGIN
		)
	SELECT
		T1.DEP_LINK,
		T1.ACCOUNT,
		ISNULL (T1.INV, 0),
		T1.BALANS,
		GRI.CODE,
		ISNULL(ASS.NO_TAX, 0),
		ISNULL (T1.DATE_IN, ASS.DATE_BEGIN),
		ISNULL (T2.SUMMA, 0),
		T1.BALANS - ISNULL (T2.SUMMA, 0),
		ISNULL (INV.COST, 0),
		ISNULL (ASS.DEPRE_SUM, 0),
		ISNULL (DGR.CODE, ''),
		ISNULL (YEAR (ISNULL (T1.DATE_IN, ASS.DATE_BEGIN)), 0)

	FROM @T_BALANS T1
	INNER JOIN dbo.INVENTORY INV ON (INV.LINK = T1.INV)	
	INNER JOIN dbo.NOMENCLATURE NOMEN ON (NOMEN.LINK = INV.NOMENCLATURE)	
	INNER JOIN dbo.GROUP_INV GRI ON (GRI.LINK = NOMEN.GROUP_INV)	
	LEFT JOIN dbo.ASSETS ASS ON (ASS.LINK_UP = INV.LINK)
	LEFT JOIN dbo.DEPRE_GROUP DGR ON (DGR.LINK = ASS.DEPRE_GROUP) 
	LEFT MERGE JOIN @T_AMORT T2 ON (T2.INV = T1.INV
		AND T2.DEP_LINK = T1.DEP_LINK)

	UPDATE T1
	SET NO_NALOG = CASE
						WHEN @YEAR_CALC > 2014 AND T1.YEAR_BEGIN > 2012 AND T1.GRP_CODE LIKE '101[2-3]%' AND T1.AM_GRP NOT LIKE '0[1-2]' THEN 1
						WHEN @YEAR_CALC BETWEEN 2013 AND 2014 AND T1.YEAR_BEGIN BETWEEN 2013 AND 2014 AND T1.GRP_CODE LIKE '101[2-3]%' 
													OR @YEAR_CALC > 2014 AND T1.AM_GRP LIKE '0[1-2]' THEN 2
						ELSE 0
					END
	FROM @varKSOUT_TABLE T1
	WHERE T1.NO_NALOG = 0

	RETURN
END
GO


GRANT SELECT ON dbo.[CalcNalogBalanceOS] TO PUBLIC
GO



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

GO


CREATE  
       
VIEW dbo.BV_DOC_AVANSE_REP
AS
  SELECT  
    G.LINK,
    G.NUMBER,
    [SUMMA] = ISNULL(dbo.CalcDocSumma(G.LINK), G.SUMMA),
    G.COMMENT,
    G.DATE, 
    G.DATE_PROV,
    [FLAG_JC] = CASE WHEN DATE_PROV IS NULL THEN 0 ELSE 1 END,

    [DEP_LINK]  = G.DEP,
    [DEP_CODE]  = CONVERT(VARCHAR(10),(SELECT CODE FROM dbo.DEPARTMENTS AS D WHERE D.LINK = G.DEP)),
    [DEP_NAME]  = CONVERT(varchar(100),(SELECT NAME FROM dbo.DEPARTMENTS AS D WHERE D.LINK = G.DEP)),


    [AVANSESUMMA] = CONVERT(numeric(13,2), (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_AVANSESUMMA'))),
    [DOC] = CONVERT(int, (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_DOC'))),
    [OPTION] = CONVERT (INT, G_OPT.VALUE),
  [EMP_CODE]= CASE WHEN CONVERT (INT, G_OPT.VALUE) = 2 THEN '' ELSE
      (SELECT TAB FROM dbo.EMPL as D WITH (NOLOCK), dbo.G_PROV_EMPL GPE WHERE GPE.DOC_LINK = G.LINK AND GPE.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_EMP_LINK') AND D.LINK = GPE.EMPL)
    END,
  [EMP_LINK]= CASE WHEN CONVERT (INT, G_OPT.VALUE) = 2 THEN
        (SELECT CONVERT (INT, GPEM.VALUE) FROM dbo.G_PROV_VALUE GPEM WHERE GPEM.DOC_LINK = G.LINK AND GPEM.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_PERS_LINK'))
      ELSE
        (SELECT GPEM.EMPL FROM dbo.G_PROV_EMPL GPEM WHERE GPEM.DOC_LINK = G.LINK AND GPEM.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_EMP_LINK'))
    END,
  [EMP_NAME]= CASE WHEN CONVERT (INT, G_OPT.VALUE) = 2 THEN
        CONVERT(Varchar(100), (SELECT dbo.BK_GetPersonName (CONVERT (INT, GPE.VALUE)) FROM dbo.G_PROV_VALUE GPE WHERE GPE.DOC_LINK = G.LINK AND GPE.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_PERS_LINK')))        
      ELSE
        CONVERT(Varchar(100), (SELECT dbo.sd_GetEmplName (GPE.EMPL) FROM dbo.G_PROV_EMPL GPE WHERE GPE.DOC_LINK = G.LINK AND GPE.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_EMP_LINK')))
    END,
    [ITOG_SUM] = CONVERT(numeric(13,2), (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_ITOG_SUM'))),
  [KBK_CODE]= CONVERT(varchar(30),  (SELECT CODE FROM dbo.KL_KBK as D WITH (NOLOCK), dbo.G_PROV_KBK GPKBK WHERE GPKBK.DOC_LINK = G.LINK AND GPKBK.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_KBK_LINK') AND D.LINK = GPKBK.KBK)),
  [KBK_LINK]=   (SELECT GPKBK.KBK FROM dbo.G_PROV_KBK GPKBK WHERE GPKBK.DOC_LINK = G.LINK AND GPKBK.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_KBK_LINK')),
  [KBK_NAME]= CONVERT(varchar(250), (SELECT NAME FROM dbo.KL_KBK as D WITH (NOLOCK), dbo.G_PROV_KBK GPKBK WHERE GPKBK.DOC_LINK = G.LINK AND GPKBK.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_KBK_LINK') AND D.LINK = GPKBK.KBK)),
  [KO_LINK] = convert(INT, dbo.BK_GetKOLinkByAO (LINK)),
    [KODATE] = CONVERT(DateTime, (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_KODATE')),104),
    [KONUM] = CONVERT(varchar(8), (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_KONUM'))),
    [KOSUMMA] = CONVERT(numeric(13,2), (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_KOSUMMA'))),
    [KTACCOUNT] = CONVERT(VARCHAR(13), (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_KTACCOUNT'))),
  [OTDEL_LINK]=   (SELECT GPDA.SUBDIV FROM dbo.G_PROV_SUBDIV GPDA WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_OTDEL_LINK')),
  [OTDEL_NAME]= CONVERT(varchar(250), (SELECT NAME FROM dbo.SUBDIV as D WITH (NOLOCK), dbo.G_PROV_SUBDIV GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_OTDEL_LINK') AND D.LINK = GPD.SUBDIV)),
    [PAGES] = CONVERT(int, (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_PAGES'))),
    [PREVSUMMA] = CONVERT(numeric(13,2), (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_PREVSUMMA'))),
    [RASHOD_SUM] = CONVERT(numeric(13,2), (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_RASHOD_SUM'))),
    [REST_SUM] = CONVERT(numeric(13,2), (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_REST_SUM'))),
  [OTDEL_CODE]= CONVERT(varChar(5), (SELECT CODE FROM dbo.SUBDIV as D WITH (NOLOCK), dbo.G_PROV_SUBDIV GPD WHERE GPD.DOC_LINK = G.LINK AND GPD.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_OTDEL_LINK') AND D.LINK = GPD.SUBDIV)),
    [TARGET] = CONVERT(varchar(100), (SELECT VALUE FROM G_PROV_VALUE as GPV WITH (NOLOCK)  WHERE GPV.DOC_LINK = G.LINK AND GPV.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AO_TARGET')))
  
  FROM dbo.G_PROV as G WITH (NOLOCK)
  LEFT OUTER JOIN dbo.G_PROV_VALUE G_OPT ON (DOC_LINK = G.LINK
    AND G_OPT.OBJECT = (SELECT LINK FROM dbo.S_OBJECTS S_OPT WHERE S_OPT.CODE = 'BV_DOC_AO_OPTION'))
  WHERE G.OBJECT=(SELECT LINK FROM S_OBJECTS WHERE CODE = 'BV_DOC_AVANSE_REP')





GO


GRANT SELECT ON dbo.[BV_DOC_AVANSE_REP] TO PUBLIC

GO




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

GO

CREATE FUNCTION DBO.DICTIONARY_PAYS_EMPL_FN
(
	@DATE DATETIME = NULL, --ВЫЧИСЛЯТЬ НА ДАННУЮ ДАТУ
	@LINK_EMPL INT = -1, -- ССЫЛКА НА СОТРУДНИКА. -1 ЗНАЧИТ НА ВСЕХ
	@LINK_SOVM INT = -1, --ССЫЛКА НА ДОП. РАБОТУ. - 1 ЗНАЧИТ НА ВСЕХ
	@BUFF_ID VARCHAR(20) = NULL, --РАССЧЕТ ДЛЯ СОТРУДНИКОВ ИЗ ЗАДАННОГО СПИСКА, КОТОРЫЙ В ЭТОМ БУФЕРЕ
	@DEP_LINK INT = NULL, -- ССЫЛКА НА ОРГАНИЗАЦИЮ	
	@MODE TINYINT = 0 -- 1 - ЗНАЧИТ НЕ РАССЧИТЫВАТЬ ПРОЦЕНТ ЗА СТАЖ.
) 
RETURNS @RES TABLE
(
	LINK INT,
	LINK_EMPL INT,
	LINK_SOVM INT,
	[LINK_PAYS] INT,
	[CODE_PAYS] VARCHAR(10),
	[NAME_PAYS] VARCHAR(60),
	[DATE_BEGIN] DATETIME,
	[DATE_END] DATETIME,
	WAY_CALC TINYINT,
	[BASE] NUMERIC(15,4),
	[VALUE] NUMERIC(15,4),
	[SUMMA]	NUMERIC(18,2),
	[ACTUAL] TINYINT,
	ISPERCENT TINYINT,
	ISPERCENT_NAME VARCHAR(8),
	OMP_LINK INT,
	ORDER_LINK INT,
	ORDER_NUM VARCHAR(30),
	ORDER_DATE DATETIME, 
	ORDER_TYPE INT,  
	ORDER_NAME VARCHAR(60),
	ORDER_INFO VARCHAR(100),
	LINK_KBK INT,
	CODE_KBK VARCHAR(30),
	NAME_KBK VARCHAR(120),
	LINK_ETS INT, 
	LINK_PKG INT,
	OBJ_CODE  VARCHAR(30),
	NOSUM TINYINT,
	PROPORC TINYINT
)

BEGIN

IF @DATE IS NULL
	SET @DATE = DBO.SalaryCalcPeriod()

DECLARE	@MINROT NUMERIC(15,2)
SET @MINROT = DBO.MINROT1(@DATE)

DECLARE @DATE_MAX DATETIME
SET @DATE_MAX = '29990101'

	
DECLARE @PE	TABLE 
(
		LINK INT,
		LINK_EMPL INT,
		LINK_SOVM INT,
		LINK_PAYS INT,
		DATE_BEGIN DATETIME,
		DATE_END DATETIME,
		BASE NUMERIC(15,4),
		VALUE NUMERIC(15,4),
		LINK_KBK INT,
		LINK_MP INT,
		LINK_ETS INT,
		LINK_PKG INT,
		NO_CALC TINYINT
)

INSERT INTO @PE (LINK, LINK_EMPL, LINK_SOVM, LINK_PAYS, DATE_BEGIN, DATE_END, BASE, VALUE, LINK_KBK, LINK_MP, LINK_ETS, LINK_PKG, NO_CALC)
SELECT LINK, LINK_EMPL, LINK_SOVM, LINK_PAYS, DATE_BEGIN, DATE_END, BASE, VALUE, LINK_KBK, LINK_MP, LINK_ETS, LINK_PKG, NO_CALC
FROM DBO.SA_DICT_PAYS_EMPL(@DATE, @LINK_EMPL, @LINK_SOVM, @BUFF_ID)	

DECLARE @DATE_END_OF_MONTH DATETIME
SET @DATE_END_OF_MONTH = DBO.DATEBEGINOFMONTH(@DATE)

--
DECLARE @OMP TABLE (
LINK INT,
ORDER_LINK INT,
[ORDER_NUM] VARCHAR(30),
[DATE] DATETIME,
[ORDER_TYPE] INT,
[ORDER_NAME] VARCHAR(60)
)

IF @LINK_EMPL = -1 AND @BUFF_ID IS NOT NULL

	INSERT INTO @OMP (LINK, ORDER_LINK, ORDER_NUM, [DATE], ORDER_TYPE, ORDER_NAME)
	SELECT MP.LINK, IM.ORDER_LINK, O.NUMBER, [DATE], OT.CODE, OT.NAME
	FROM
		(SELECT DISTINCT LINK_MP FROM dbo.PAYS_EMPL WHERE LINK_MP IS NOT NULL) P
		INNER JOIN dbo.MONEY_PERIOD MP ON P.LINK_MP = MP.LINK
		INNER JOIN dbo.ITEM_MOVE IM ON MP.ITEM_LINK=IM.LINK
		INNER JOIN DBO.BUFFER B ON B.LINK = IM.EMPL_LINK
		INNER JOIN dbo.ORDERS O ON IM.ORDER_LINK=O.LINK
		INNER JOIN dbo.ORDER_TYPES OT ON O.[TYPE]=OT.CODE		
	WHERE
		B.ID = @BUFF_ID AND @LINK_EMPL = -1 AND @BUFF_ID IS NOT NULL
ELSE
	INSERT INTO @OMP (LINK, ORDER_LINK, ORDER_NUM, [DATE], ORDER_TYPE, ORDER_NAME)
	SELECT MP.LINK, IM.ORDER_LINK, O.NUMBER, [DATE], OT.CODE, OT.NAME
	FROM
		(SELECT DISTINCT LINK_MP FROM dbo.PAYS_EMPL WHERE LINK_MP IS NOT NULL) P
		INNER JOIN dbo.MONEY_PERIOD MP ON P.LINK_MP = MP.LINK
		INNER JOIN dbo.ITEM_MOVE IM ON MP.ITEM_LINK=IM.LINK
		INNER JOIN dbo.ORDERS O ON IM.ORDER_LINK=O.LINK
		INNER JOIN dbo.ORDER_TYPES OT ON O.[TYPE]=OT.CODE		
	WHERE
		(@LINK_EMPL = -1 AND @BUFF_ID IS NULL) OR (@LINK_EMPL > 0 AND IM.EMPL_LINK = @LINK_EMPL)	

--ПОСТОЯННОЕ НАЧИСЛЕНИЯ

INSERT INTO @RES (LINK, LINK_EMPL, LINK_SOVM, LINK_PAYS, CODE_PAYS, NAME_PAYS, DATE_BEGIN, DATE_END, WAY_CALC, BASE, VALUE, SUMMA, ACTUAL, ISPERCENT, ISPERCENT_NAME, OMP_LINK, ORDER_LINK, ORDER_NUM, ORDER_DATE, ORDER_TYPE, ORDER_NAME, ORDER_INFO, LINK_KBK, CODE_KBK, NAME_KBK, LINK_ETS, LINK_PKG, OBJ_CODE, NOSUM, PROPORC)
SELECT 
	PE.LINK,
	PE.LINK_EMPL,
	PE.LINK_SOVM,
	[LINK_PAYS] = P.LINK,
	[CODE_PAYS] = P.CODE,
	[NAME_PAYS] = P.NAME,
	PE.[DATE_BEGIN],
	PE.[DATE_END],
	P.WAY_CALC,
	[BASE]	= PE.BASE,
	[VALUE] = PE.[VALUE],
	[SUMMA]	= 0, --AP.SUMMA,
	[ACTUAL]  = CASE 
		WHEN (PE.[DATE_BEGIN] <= @DATE) AND PE.VALUE > 0 AND
        	(ISNULL(PE.[DATE_END],@DATE_MAX) >= @DATE_END_OF_MONTH)
			THEN 1
		ELSE 0
	END,
	WC.ISPERCENT,
	ISPERCENT_NAME = CASE WC.ISPERCENT WHEN 0 THEN 'СУММА' 
										WHEN 1 THEN 'ПРОЦЕНТ' 
										WHEN 2 THEN 'КОЭФ.ЕТС' 
										WHEN 3 THEN 'КОЭФ.ПКГ' 
										WHEN 4 THEN 'КОЭФ.' 
					END,
	OMP_LINK = OMP.LINK,
	OMP.ORDER_LINK,
	ORDER_NUM,
	ORDER_DATE = OMP.[DATE] , 
	ORDER_TYPE,  
	ORDER_NAME,
	ORDER_INFO = 
		CASE WHEN (CASE WHEN P.NOSUM = 1 THEN P.NOSUM ELSE PE.NO_CALC END) = 1 THEN 'Не начисляется ' ELSE '' END 
		+
		CASE WHEN PE.LINK_MP IS NULL THEN ''
			ELSE 'ПРИКАЗ ' + LTRIM(ORDER_NAME) + ' №' + RTRIM(LTRIM(ORDER_NUM)) + ' ОТ ' + CONVERT(VARCHAR(10),OMP.DATE, 104 )
		END,
	LINK_KBK = CASE WHEN P.PROPORC = 0 OR ISPERCENT NOT IN (1,4) THEN PE.LINK_KBK ELSE NULL END,
	CODE_KBK = CASE WHEN P.PROPORC = 0 OR ISPERCENT NOT IN (1,4) THEN KBK.CODE ELSE 'Пропорционально' END,
	NAME_KBK = CASE WHEN P.PROPORC = 0 OR ISPERCENT NOT IN (1,4) THEN KBK.[NAME] ELSE 'Пропорционально источникам базовых начислений' END,
	PE.LINK_ETS, 
	PE.LINK_PKG,
	OBJ_CODE  = 'DICTIONARY_PAYS_EMPL',
	NOSUM = (CASE WHEN P.NOSUM = 1 THEN P.NOSUM ELSE PE.NO_CALC END),
	P.PROPORC
FROM
	dbo.WAY_CALC WC
	INNER JOIN DBO.PAYS P ON P.WAY_CALC = WC.CODE
	INNER JOIN @PE PE ON P.LINK = PE.LINK_PAYS
	INNER JOIN DBO.SAL_SFIN KBK ON KBK.LINK = PE.LINK_KBK
	LEFT JOIN @OMP OMP ON OMP.LINK = PE.LINK_MP
WHERE
	WC.[TYPE] = 1
	AND
	P.[OBJECT] = 1	


----
DECLARE @WH_PAYS TABLE
(
	date_begin DATETIME,
	date_end DATETIME,
	link_wh INT,
	link_empl INT,
	link_tar_empl INT,
	link_pay	INT,
	summa NUMERIC(18,2),
	link_sfin INT,
	link_ets INT,
	link_pkg INT,
	NO_CALC TINYINT,
	link_les INT,
	link_paral INT,
	t TINYINT
)

INSERT INTO @WH_PAYS (date_begin, date_end, link_wh, link_empl, link_tar_empl, link_pay, summa, link_sfin, link_ets, link_pkg, NO_CALC, link_les, link_paral, t)
SELECT date_begin, date_end, link_wh, link_empl, link_tar_empl, link_pay, summa, link_sfin, link_ets, link_pkg, NO_CALC, link_les, link_paral, t
FROM DBO.SA_DICT_WH_PAYS_EMPL(@DATE, @LINK_EMPL, @LINK_SOVM, @BUFF_ID, @DEP_LINK)
	
------ПОСТОЯННОЕ НАЧИСЛЕНИ ПО НАГРУЗКАМ
INSERT INTO @RES (LINK, LINK_EMPL, LINK_SOVM, LINK_PAYS, CODE_PAYS, NAME_PAYS, DATE_BEGIN, DATE_END, WAY_CALC, BASE, VALUE, SUMMA, ACTUAL, ISPERCENT, ISPERCENT_NAME, OMP_LINK, ORDER_LINK, ORDER_NUM, ORDER_DATE, ORDER_TYPE, ORDER_NAME, ORDER_INFO, LINK_KBK, CODE_KBK, NAME_KBK, LINK_ETS, LINK_PKG, OBJ_CODE, NOSUM, PROPORC)
SELECT 
	LINK = PE.LINK_WH,
	PE.LINK_EMPL,
	LINK_SOVM = PE.LINK_TAR_EMPL,
	[LINK_PAYS] = P.LINK,
	[CODE_PAYS] = P.CODE,
	[NAME_PAYS] = P.NAME,
	PE.[DATE_BEGIN],
	PE.[DATE_END],
	P.WAY_CALC,
	[BASE]	= 0, --AP.SUMMA_BASE,
	[VALUE] = CONVERT(NUMERIC(18,4), PE.SUMMA),
	[SUMMA]	= 0, --AP.SUMMA,
	[ACTUAL]  = CASE 
		WHEN (PE.[DATE_BEGIN] <= @DATE) AND
        	(ISNULL(PE.[DATE_END],@DATE_MAX) >= @DATE_END_OF_MONTH)
			THEN 1
		ELSE 0
	END,
	ISPERCENT = 0,
	ISPERCENT_NAME = 'СУММА',
	OMP_LINK = NULL,
	ORDER_LINK = NULL,
	ORDER_NUM = '',
	ORDER_DATE = NULL, 
	ORDER_TYPE = NULL,  
	ORDER_NAME = '',
	ORDER_INFO = CASE WHEN (CASE WHEN P.NOSUM = 1 THEN P.NOSUM ELSE PE.NO_CALC END) = 1 THEN 'Не начисляется' ELSE '' END,
	LINK_KBK = CASE WHEN P.PROPORC = 0 OR ISPERCENT NOT IN (1,4)  THEN PE.LINK_SFIN ELSE NULL END,
	CODE_KBK = CASE WHEN P.PROPORC = 0 OR ISPERCENT NOT IN (1,4)  THEN KBK.CODE ELSE 'Пропорционально' END,
	NAME_KBK = CASE WHEN P.PROPORC = 0 OR ISPERCENT NOT IN (1,4)  THEN KBK.[NAME] ELSE 'Пропорционально источникам базовых начислений' END,
	PE.LINK_ETS, 
	PE.LINK_PKG,
	OBJ_CODE  = 'STO_W_HOURS_TABLE',
	NOSUM = (CASE WHEN P.NOSUM = 1 THEN P.NOSUM ELSE PE.NO_CALC END),
	P.PROPORC
FROM 
	DBO.WAY_CALC WC
	INNER JOIN DBO.PAYS P ON P.WAY_CALC = WC.CODE
	INNER JOIN @WH_PAYS PE ON P.LINK = PE.LINK_PAY
	INNER JOIN DBO.SAL_SFIN KBK ON KBK.LINK = PE.LINK_SFIN
WHERE
	WC.[TYPE] = 1
	AND
	P.[OBJECT] = 1	

---НАДБАВКИ ЗА ПРЕДМЕТ
INSERT INTO @RES (LINK, LINK_EMPL, LINK_SOVM, LINK_PAYS, CODE_PAYS, NAME_PAYS, DATE_BEGIN, DATE_END, WAY_CALC, BASE, VALUE, SUMMA, ACTUAL, ISPERCENT, ISPERCENT_NAME, OMP_LINK, ORDER_LINK, ORDER_NUM, ORDER_DATE, ORDER_TYPE, ORDER_NAME, ORDER_INFO, LINK_KBK, CODE_KBK, NAME_KBK, LINK_ETS, LINK_PKG, OBJ_CODE, NOSUM, PROPORC)
SELECT 
	LINK = LP.LINK,
	PE.LINK_EMPL,
	LINK_SOVM = PE.LINK_TAR_EMPL,
	[LINK_PAYS] = P.LINK,
	[CODE_PAYS] = P.CODE,
	[NAME_PAYS] = P.NAME,
	PE.[DATE_BEGIN],
	PE.[DATE_END],
	P.WAY_CALC,
	[BASE]	= 0, 
	[VALUE] = CONVERT(NUMERIC(18,4), (CASE WHEN LP.BASE = 1 THEN PE.SUMMA ELSE @MINROT END) * LP.VALUE / 100),
	[SUMMA]	= 0,	
	[ACTUAL]  = CASE WHEN PE.[DATE_BEGIN] <= @DATE AND (ISNULL(PE.[DATE_END],@DATE_MAX) >= @DATE_END_OF_MONTH)
			THEN 1
		ELSE 0
	END,
	ISPERCENT = 0,
	ISPERCENT_NAME = 'СУММА',
	OMP_LINK = NULL,
	ORDER_LINK = NULL,
	ORDER_NUM = '',
	ORDER_DATE = NULL, 
	ORDER_TYPE = NULL,  
	ORDER_NAME = '',
	ORDER_INFO = CASE WHEN (CASE WHEN P.NOSUM = 1 THEN P.NOSUM ELSE 0 END) = 1 THEN 'Не начисляется' ELSE '' END,
	LINK_KBK = CASE WHEN P.PROPORC = 0 OR ISPERCENT NOT IN (1,4)  THEN PE.LINK_SFIN ELSE NULL END,
	CODE_KBK = CASE WHEN P.PROPORC = 0 OR ISPERCENT NOT IN (1,4)  THEN KBK.CODE ELSE 'Пропорционально' END,
	NAME_KBK = CASE WHEN P.PROPORC = 0 OR ISPERCENT NOT IN (1,4)  THEN KBK.[NAME] ELSE 'Пропорционально источникам базовых начислений' END,
	PE.LINK_ETS, 
	PE.LINK_PKG,
	OBJ_CODE  = 'STO_LES_PAYS',
	NOSUM = (CASE WHEN P.NOSUM = 1 THEN P.NOSUM ELSE 0 END),
	P.PROPORC
FROM
	DBO.WAY_CALC WC
	INNER JOIN DBO.PAYS P ON P.WAY_CALC = WC.CODE
	INNER JOIN DBO.STO_LES_PAYS AS LP ON P.LINK = LP.LINK_PAY
	INNER JOIN @WH_PAYS PE ON PE.LINK_LES = LP.LINK_LES AND ( (PE.LINK_PARAL = LP.LINK_PARAL AND PE.T IN (1,2)) OR PE.T = 4 )
	INNER JOIN DBO.SAL_SFIN KBK ON KBK.LINK = LP.LINK_KBK
WHERE
	WC.[TYPE] = 1	
	AND 
	P.[OBJECT] = 1

--ПОСТОЯННОЕ НАДБАВКИ К НАГРУЗКАМ
DECLARE @ADD TABLE
(
		LINK INT,
		LINK_EMPL INT,
		LINK_TAR_EMPL INT,
		LINK_PAY INT,
		DATE_BEGIN DATETIME,
		DATE_END DATETIME,
		SUMMA NUMERIC(18, 2), 
		CALC_PERC NUMERIC(12, 4), 
		LINK_KBK INT,
		NO_CALC TINYINT
)

INSERT INTO @ADD (LINK, LINK_EMPL, LINK_TAR_EMPL, LINK_PAY, DATE_BEGIN, DATE_END, SUMMA, CALC_PERC, LINK_KBK, NO_CALC)
SELECT LINK, LINK_EMPL, LINK_TAR_EMPL, LINK_PAY, DATE_BEGIN, DATE_END, SUMMA, CALC_PERC, LINK_KBK, NO_CALC
FROM DBO.STO_ADD_PAYS_FN(@DATE, @LINK_EMPL, @LINK_SOVM, @BUFF_ID, @DEP_LINK, @MODE)

INSERT INTO @RES (LINK, LINK_EMPL, LINK_SOVM, LINK_PAYS, CODE_PAYS, NAME_PAYS, DATE_BEGIN, DATE_END, WAY_CALC, BASE, VALUE, SUMMA, ACTUAL, ISPERCENT, ISPERCENT_NAME, OMP_LINK, ORDER_LINK, ORDER_NUM, ORDER_DATE, ORDER_TYPE, ORDER_NAME, ORDER_INFO, LINK_KBK, CODE_KBK, NAME_KBK, LINK_ETS, LINK_PKG, OBJ_CODE, NOSUM, PROPORC)
SELECT 
	AP.LINK,
	AP.LINK_EMPL,
	LINK_SOVM = AP.LINK_TAR_EMPL,
	[LINK_PAYS] = P.LINK,
	[CODE_PAYS] = P.CODE,
	[NAME_PAYS] = P.NAME,
	AP.[DATE_BEGIN],
	AP.[DATE_END],
	P.WAY_CALC,
	[BASE]	= 0,
	[VALUE] = CONVERT(NUMERIC(18,4), CASE WHEN ISNULL(AP.SUMMA,0) > 0 THEN ISNULL(AP.SUMMA,0) ELSE ISNULL(AP.CALC_PERC,0) END),
	[SUMMA]	= 0,
	[ACTUAL]  = CASE 
		WHEN (AP.[DATE_BEGIN] <= @DATE) AND
        	(ISNULL(AP.[DATE_END],@DATE_MAX) >= @DATE_END_OF_MONTH)
			THEN 1
		ELSE 0
	END,
	ISPERCENT = CASE WHEN AP.SUMMA > 0 THEN 0 ELSE WC.ISPERCENT END,
	ISPERCENT_NAME = CASE (CASE WHEN AP.SUMMA > 0 THEN 0 ELSE WC.ISPERCENT END) WHEN 0 THEN 'СУММА' 
										WHEN 1 THEN 'ПРОЦЕНТ' 
										WHEN 2 THEN 'КОЭФ.ЕТС' 
										WHEN 3 THEN 'КОЭФ.ПКГ' 
										WHEN 4 THEN 'КОЭФ.' 
					END,
	OMP_LINK = NULL,
	ORDER_LINK = NULL,
	ORDER_NUM = '',
	ORDER_DATE = NULL, 
	ORDER_TYPE = NULL,  
	ORDER_NAME = '',
	ORDER_INFO = CASE WHEN (CASE WHEN P.NOSUM = 1 THEN P.NOSUM ELSE AP.NO_CALC END) = 1 THEN 'Не начисляется' ELSE '' END,
	LINK_KBK = CASE WHEN P.PROPORC = 0 OR ISPERCENT NOT IN (1,4)  THEN AP.LINK_KBK ELSE NULL END,
	CODE_KBK = CASE WHEN P.PROPORC = 0 OR ISPERCENT NOT IN (1,4)  THEN KBK.CODE ELSE 'Пропорционально' END,
	NAME_KBK = CASE WHEN P.PROPORC = 0 OR ISPERCENT NOT IN (1,4)  THEN KBK.[NAME] ELSE 'Пропорционально источникам базовых начислений' END,
	P.LINK_ETS, 
	LINK_PKG = NULL,
	OBJ_CODE  = 'STO_ADD_PAYS',
	NOSUM = (CASE WHEN P.NOSUM = 1 THEN P.NOSUM ELSE AP.NO_CALC END),
	P.PROPORC
FROM
	DBO.WAY_CALC WC
	INNER JOIN DBO.PAYS P ON P.WAY_CALC = WC.CODE
	INNER JOIN @ADD AP ON P.LINK = AP.LINK_PAY
	INNER JOIN DBO.SAL_SFIN KBK ON KBK.LINK = AP.LINK_KBK
WHERE
	WC.[TYPE] = 1
	AND
	P.[OBJECT] = 1	

RETURN

END





GO


GRANT SELECT ON dbo.[DICTIONARY_PAYS_EMPL_FN] TO PUBLIC

GO



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

GO
CREATE FUNCTION [dbo].SCRIPTSNAVIGATOROBJ(@LINK INT)
RETURNS @TASK_OPTIONS TABLE (TXT VARCHAR(7000) )
AS
BEGIN

INSERT INTO @TASK_OPTIONS( TXT )
SELECT 
'
/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "' + RTRIM(NAME) + '"*************/ 
 ' + CASE WHEN EXISTS (SELECT RTRIM(CODE) FROM OBJECT_VAR WHERE LINK = N.LINK_VAR) THEN
+ '
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = ''' + COALESCE((SELECT RTRIM(CODE) FROM OBJECT_VAR WHERE LINK = N.LINK_VAR),'')	+ ''')
' ELSE '
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL
' END + 
(CASE WHEN COALESCE((SELECT RTRIM(CODE) FROM S_NAVIGATOR WHERE LINK = N.LINK_SELF),'') <> '' THEN
'
DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = ''' 
	+ COALESCE((SELECT RTRIM(CODE) FROM S_NAVIGATOR WHERE LINK = N.LINK_SELF),'') 
	+ ''''
	+ ' AND NAME = '''
	+ COALESCE((SELECT RTRIM(NAME) FROM S_NAVIGATOR WHERE LINK = N.LINK_SELF),'') 
	+ ''')
' ELSE '' END)
+ 
(CASE WHEN COALESCE((SELECT RTRIM(CODE) FROM S_OBJECTS WHERE LINK = N.OBJECT),'') <> '' THEN
'
DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = ''' + COALESCE((SELECT RTRIM(CODE) FROM S_OBJECTS WHERE LINK = N.OBJECT),'') + ''')
'
ELSE '' END)
+ '
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 = ''' 
	+ (SELECT RTRIM(CODE) FROM S_NAVIGATOR WHERE LINK = N.LINK_SELF) 
	+ ''''
	+ ' AND NAME = '''
	+ COALESCE((SELECT RTRIM(NAME) FROM S_NAVIGATOR WHERE LINK = N.LINK_SELF),'') 
	+ '''))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = ''' + RTRIM(CODE) + '''),0)

IF COALESCE(@LINK_SELF,0) > 0 '  + 
(CASE WHEN COALESCE((SELECT RTRIM(CODE) FROM S_OBJECTS WHERE LINK = N.OBJECT),'') <> '' THEN ' AND COALESCE(@OBJECT,0) > 0 ' ELSE '' END)
+ ' 
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, ''' + RTRIM(CODE) + ''', ''' + RTRIM(NAME) +''', @ORD, NULL, 1, @LINK_SELF, ''' + RTRIM(IMAGE_KEY) + ''', '
	+ (CASE WHEN COALESCE((SELECT RTRIM(CODE) FROM S_OBJECTS WHERE LINK = N.OBJECT),'') <> '' THEN '@OBJECT' ELSE 'NULL' END) + ', @LINK_VAR, ' + CONVERT(VARCHAR(2), VISIBLE)

 + CHAR(13) + CHAR(10) + 'GO' + CHAR(13) + CHAR(10)
FROM S_NAVIGATOR N WHERE LINK = @LINK


--ДЕТИ

DECLARE SOCUR CURSOR FOR SELECT LINK FROM DBO.S_NAVIGATOR WHERE LINK_SELF = @LINK AND COALESCE(@LINK,0) <> 0
DECLARE @INTCHILD VARCHAR(30)
OPEN SOCUR
FETCH NEXT FROM SOCUR INTO @INTCHILD
WHILE @@FETCH_STATUS = 0
BEGIN
	INSERT INTO @TASK_OPTIONS( TXT )
	SELECT * FROM DBO.SCRIPTSNAVIGATOROBJ(@INTCHILD)
	FETCH NEXT FROM SOCUR INTO @INTCHILD
END
CLOSE SOCUR
DEALLOCATE SOCUR


RETURN 

END


GO


GRANT SELECT ON dbo.[SCRIPTSNAVIGATOROBJ] TO PUBLIC

GO


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

GO
CREATE FUNCTION dbo.BK_DOC_TABLE_MZ_NDS_FN
	(@intLINK_DOC	INT = NULL)

RETURNS @RETURN_TAB TABLE 
	(LINK		INT,
	LINK_UP		INT,
	OBJECT		INT,
	ORDERS		INT,
	LINK_OPER	INT,
	
	INV_TYPE	VARCHAR (30),
	INV_LINK	INT,
	INV_CODE	VARCHAR (20),
	INV_NAME	VARCHAR (254),
	UM_LINK		INT,
	UM_CODE		VARCHAR (6),
	UM_NAME		VARCHAR (254),
	PRICE		NUMERIC (18, 2),
	QTY		NUMERIC (18, 4),
	SUMMA		NUMERIC (18, 2),
	STAVKA_NDS	NUMERIC (18, 2),
	SUMMA_NDS	NUMERIC (18, 2), 
	SUMMA_ALL	NUMERIC (18, 2), 
	AKCIZ		NUMERIC (18, 2),
	NUM_TD		VARCHAR (30),
	EKR_LINK	INT,
	EKR_CODE	VARCHAR (3),
	SFIN_CODE	VARCHAR (1),
	SFIN_NAME	VARCHAR (30),
	NO_NDS		TINYINT,
	STATE_LINK	INT,
	STATE_CODE	VARCHAR (3),
	STATE_NAME	VARCHAR (60),

	FS_LINK		INT,
	FS_CODE		VARCHAR (2),
	FS_NAME		VARCHAR (20),

	TNDS_LINK	INT,
	TNDS_CODE	VARCHAR (2),
	COMMENT		VARCHAR (254)
	)
AS
BEGIN
	DECLARE
		@intTAB_LINK	INT,
		@intFS_OBJ_LINK	INT,
		@int@OBJ_COM	INT

	SET @intTAB_LINK = dbo.GetObjLink ('DOC_TABLE_MZ_NDS')
	SET @intFS_OBJ_LINK = dbo.GetObjLink ('DOC_TABLE_MZ_NDS_FS_LINK')
	SET @int@OBJ_COM = dbo.GetObjLink ('DOC_TABLE_MZ_NDS_COMMENT')

	-- Выборка требуемых записей таблицы --
	DECLARE @TAB0 TABLE
		(LINK	INT,
		LINK_UP	INT,
		OBJECT	INT,
		ORDERS	INT,
		LINK_OPER INT
		)

	INSERT @TAB0
	SELECT OTR.LINK,
		OTR.LINK_UP,
		OTR.OBJECT,
		OTR.ORDERS,
		OTR.LINK_OPER
	FROM dbo.OUT_TABLE_ROW OTR 
	WHERE OTR.OBJECT = @intTAB_LINK
		AND (OTR.LINK_UP = @intLINK_DOC
			OR @intLINK_DOC IS NULL)

	-- Выборка МЦ таблицы --
	DECLARE @TAB1	TABLE
		(LINK_UP	INT, 
		INV_TYPE	VARCHAR (30),
		INV_LINK	INT,
		INV_CODE	VARCHAR (20),
		INV_NAME	VARCHAR (254),
		UM_LINK		INT)

	-- Услуги, МЗ --
	INSERT INTO @TAB1
	SELECT OTR.LINK,

		OTMS.INV_TYPE,
		SMWT.LINK, 
		SMWT.INV_CODE,
		SMWT.INV_NAME,

		SMWT.UM_LINK

	FROM @TAB0 OTR
	LEFT JOIN dbo.OUT_TABLE_MZ_SUMMA OTMS ON (OTMS.LINK_ROW = OTR.LINK)
	LEFT JOIN dbo.SELECT_MZ_WITH_TYPE SMWT ON (SMWT.LINK = OTMS.NOMEN
				AND SMWT.INV_TYPE = OTMS.INV_TYPE)
	WHERE OTMS.INV_TYPE = 'BV_NOMENCLATURE'
		OR OTMS.INV_TYPE = 'DICTIONARY_SERV'			

	-- Основные средства --
--	INSERT INTO @TAB1
	UNION ALL

	SELECT OTR.LINK,

		OTMS.INV_TYPE,
		SMWT.LINK, 
		SMWT.INV_CODE,
		SMWT.INV_NAME,

		SMWT.UM_LINK

	FROM @TAB0 OTR
	LEFT JOIN dbo.OUT_TABLE_MZ_SUMMA OTMS ON (OTMS.LINK_ROW = OTR.LINK)
	LEFT JOIN dbo.SELECT_MZ_WITH_TYPE SMWT ON (SMWT.LINK = OTMS.INV
				AND SMWT.INV_TYPE = OTMS.INV_TYPE)
	WHERE OTMS.INV_TYPE = 'INVENTORY_CARD'

	-- ТМЦ --
--	INSERT INTO @TAB1
	UNION ALL

	SELECT OTR.LINK,

		OTMS.INV_TYPE,
		SMWT.LINK, 
		SMWT.INV_CODE,
		SMWT.INV_NAME,

		SMWT.UM_LINK

	FROM @TAB0 OTR
	LEFT JOIN dbo.OUT_TABLE_MZ_SUMMA OTMS ON (OTMS.LINK_ROW = OTR.LINK)
	LEFT JOIN dbo.SELECT_MZ_WITH_TYPE SMWT ON (SMWT.LINK = OTMS.TMC
				AND SMWT.INV_TYPE = OTMS.INV_TYPE)
	WHERE OTMS.INV_TYPE = 'DICTIONARY_TMC'

	-- Результат --
	INSERT INTO @RETURN_TAB
	SELECT T0.LINK,
		T0.LINK_UP,
		T0.OBJECT,
		T0.ORDERS,
		T0.LINK_OPER,

		
		T1.INV_TYPE,
		T1.INV_LINK,
		T1.INV_CODE,
		T1.INV_NAME,

		UM.LINK,
		UM.CODE AS UM_CODE,
		UM.[NAME] AS UM_NAME,

		CONVERT (NUMERIC (18, 2), OTMS.PRICE) AS PRICE,
		CONVERT (NUMERIC (18, 4), OTMS.QTY) AS QTY,
		CONVERT (NUMERIC (18, 2), OTMS.SUMMA) AS SUMMA,
		CONVERT (NUMERIC (18, 2), OTMS.STAVKA_NDS) AS STAVKA_NDS,
		CONVERT (NUMERIC (18, 2), OTMS.SUMMA_NDS) AS SUMMA_NDS,
		CONVERT (NUMERIC (18, 2), OTMS.SUMMA_ALL) AS SUMMA_ALL,
		OTMS.AKCIZ,
		OTMS.NUM_TD,

		EKR.LINK AS EKR_LINK,
		EKR.CODE AS EKR_CODE,
		FS.CODE,
		CONVERT (VARCHAR (20), FS.SHORT_NAME),
		OTMS.NO_NDS,
		
		KC.LINK,
		CONVERT (VARCHAR (3), KC.CODE1),
		CONVERT (VARCHAR (60), KC.[NAME]),

		FS.LINK,
		FS.CODE,
		CONVERT (VARCHAR (20), FS.SHORT_NAME),

		TO_NDS.LINK,
		TO_NDS.CODE,
		CONVERT (VARCHAR (254), OTS_COM.STRING)
	
	FROM @TAB0 T0 
	LEFT MERGE JOIN @TAB1 T1 ON (T1.LINK_UP = T0.LINK)
	LEFT JOIN dbo.OUT_TABLE_MZ_SUMMA OTMS ON (OTMS.LINK_ROW = T0.LINK)

	LEFT JOIN dbo.OUT_TABLE_STRING OTS_COM ON 
		(OTS_COM.[OBJECT] = @int@OBJ_COM
		AND OTS_COM.LINK_UP = T0.LINK)

	LEFT JOIN dbo.DICTIONARY_DIGIT UM ON (UM.LINK = T1.UM_LINK)
	LEFT JOIN dbo.KOSGU EKR ON (EKR.LINK = OTMS.EKR)	
	LEFT JOIN dbo.FIN_SOURCE FS ON (FS.CODE = OTMS.FIN_SOURCE)
	LEFT JOIN dbo.KL_COUNTRY KC ON (KC.LINK = OTMS.COUNTRY_LINK)
	LEFT JOIN dbo.TYPE_OPER_NDS TO_NDS ON (TO_NDS.LINK = OTMS.TYPE_NDS)

	RETURN 
END


GO


GRANT SELECT ON dbo.[BK_DOC_TABLE_MZ_NDS_FN] TO PUBLIC

GO


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


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

GO
CREATE PROCEDURE [dbo].BK_TEST_EXP_F1152028 (@Res tinyint output, @link int, @m int) 
AS
BEGIN
	DECLARE @INN VARCHAR (12),
			@KPP VARCHAR (10),
			@IMNS	INT,
			@OKATO VARCHAR (20),
			@OKVED	VARCHAR (10),
			@iLINK_TABLE INT,
			@KBK VARCHAR (30)

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


	SELECT 	@INN = INN,
			@KPP = KPP,
			@IMNS = IMNS_LINK,
			@OKATO = OKATO,
			@OKVED = RTRIM (REPLACE (OKVED, '.', ''))
	FROM dbo.DEPARTMENTS D
	INNER JOIN dbo.REPORT_SAVED_FORMS R ON R.LINK_ORGANIZATION = D.LINK
	WHERE LINK_SAVED_FORM = @link



	--- !!!РАСЧЕТ!!! ---
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM 	(select *, CASE WHEN ORDERS = 1 THEN 2 WHEN ORDERS = 2 THEN 3
		WHEN ORDERS = 3 THEN 1 END AS REAL_ORD
		from report_tables
		where link_form = (select link_form
							from report_saved_forms
							where link_saved_form = @link)) AS T
	WHERE REAL_ORD = 1

	SELECT @KBK = KBK, @OKATO = ISNULL (@OKATO, OKATO)
	FROM
	(SELECT (SELECT CONVERT (VARCHAR (30), Str_Val) FROM dbo.REPORT_STRING
				WHERE LINK_SAVED_FORM = @link
				AND LINK_COL = (SELECT RC1.LINK_COL FROM dbo.REPORT_COLOUMNS RC1 WHERE RC1.LINK_TABLE = @iLINK_TABLE
									AND UPPER (RC1.[NAME]) = 'КОД БК')
				) AS KBK,
		(SELECT CONVERT (VARCHAR (20), Str_Val) FROM dbo.REPORT_STRING
					WHERE LINK_SAVED_FORM = @link
					AND LINK_COL = (SELECT RC1.LINK_COL FROM dbo.REPORT_COLOUMNS RC1 WHERE RC1.LINK_TABLE = @iLINK_TABLE
										AND UPPER (RC1.[NAME]) = 'КОД ПО ОКАТО')
					) AS OKATO
	FROM dbo.REPORT_ROWS RR
	WHERE RR.LINK_TABLE = @iLINK_TABLE) AS T


	IF ISNULL (@INN, '') = '' OR ISNULL (@KPP, '') = '' OR ISNULL (@IMNS, 0) = 0
			 OR ISNULL (@OKATO, '') = '' OR ISNULL (@KBK, '') = '' OR ISNULL (@OKVED, '') = ''
		SET @Res = 0
	ELSE
		SET @Res = 1

	SELECT MSG_BEFORE = 'Не указаны следующие реквизиты:', Msg = 'Не указан ИНН организации.',
			msg_after  = 'Необходимо указать ИНН в настройках организации.'
	WHERE ISNULL (@INN, '') = '' 
	UNION
	SELECT MSG_BEFORE = 'Не указаны следующие реквизиты:', Msg = 'Не указан КПП организации.',
			msg_after  = 'Необходимо указать КПП в настройках организации.'
	WHERE ISNULL (@KPP, '') = '' 
	UNION
	SELECT MSG_BEFORE = 'Не указаны следующие реквизиты:', Msg = 'Не указан ОКАТО организации.',
			msg_after  = 'Необходимо указать ОКАТО в настройках организации.'
	WHERE ISNULL (@OKATO, '') = '' 
	UNION
	SELECT MSG_BEFORE = 'Не указаны следующие реквизиты:', Msg = 'Не указан код налогового органа.',
			msg_after  = 'Укажите налоговый орган в настройках организации на вкладке реквизиты "ИМНС".'
	WHERE ISNULL (@IMNS, '') = '' 
	UNION
	SELECT MSG_BEFORE = 'Не указаны следующие реквизиты:', Msg = 'Не указан ОКВЭД.',
			msg_after  = 'Укажите ОКВЭД в настройках организации на вкладке Прочие "ОКВЭД".'
	WHERE ISNULL (@OKVED, '') = '' 
	UNION
	SELECT MSG_BEFORE = 'Не указаны следующие реквизиты:', Msg = 'Не указан КБК.',
			msg_after  = 'Укажите КБК в расчитанной форме на вкладке Раздел1 или в настройках деклараций.'
	WHERE ISNULL (@KBK, '') = '' 
END


GO


GRANT EXECUTE ON dbo.[BK_TEST_EXP_F1152028] TO PUBLIC

GO


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

GO



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

CREATE	PROCEDURE dbo.BI_SAVE_KBK_IVF
	@varKSparLINK	int	OUTPUT,
	@varKSparNAME	VARCHAR(250) = '',
	@varKSLink_Adm	int = null,
	@varKSLink_IVF	int,
	@iProgLink		int,
	@varKSLink_SGU  INT,
	@iUsed			tinyint,
	@iType			tinyint,
	@cDelim			char(1)
AS
DECLARE @varKSERROR	tinyint,
	@varKSRowCount	INT,
	@varKSstrVALUE	varchar(7000),
	@varKStrancount	int,
	@varKSEventText	varchar(254),
	@varKSintObj	int,
	@varKSCode	char(30)
SET LOCK_TIMEOUT 30000
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

	IF @varKSparNAME IS NULL OR @varKSparNAME = ''
	BEGIN
		ROLLBACK
		RETURN 5
	END
	IF @varKSLink_IVF IS NULL OR @varKSLink_IVF = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END
	IF @iProgLink IS NULL OR @iProgLink = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END
	IF @varKSLink_Adm IS NULL OR @varKSLink_Adm = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END
/*	IF @varKSLink_SGU IS NULL OR @varKSLink_SGU = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END*/

	if (select count(*) from KL_IVF where link = @varKSLink_IVF)<>1
	OR (select count(*) from KL_ADMIN_BS where link = @varKSLink_Adm)<>1
	OR (select count(*) from KL_PROG where link = @iProgLink)<>1
	BEGIN
		ROLLBACK
		RETURN 5
	END
	
	SET @varKSCode = coalesce ((SELECT code FROM KL_ADMIN_BS WHERE link = @varKSLink_Adm),'000') + @cDelim +
			coalesce ((SELECT code FROM KL_IVF WHERE link = @varKSLink_IVF),'0000000000') + @cDelim +
			coalesce ((SELECT code FROM KL_PROG WHERE link = @iProgLink),'0000') +
			coalesce ((SELECT code FROM KOSGU WHERE link = @varKSLink_SGU),'')
	
	If (select count(*) from KL_KBK WHERE LINK <> @varKSparLINK and CODE = @varKSCode
		and TYPE = @iType) <> 0 
	BEGIN
		ROLLBACK
		RETURN 4
	END
	
	If (Select count(*) from KL_KBK where link = @varKSparLINK) > 0
	BEGIN
		UPDATE KL_KBK
		SET	TYPE = @iType,
			CODE = @varKSCode,
			NAME = @varKSparNAME,
			Link_Adm = @varKSLink_Adm,
			USED = @iUsed	 
		WHERE LINK = @varKSparLINK
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		DELETE FROM KL_KBK_KD WHERE LINK_KBK = @varKSparLINK
		DELETE FROM KL_VKR WHERE LINK_KBK = @varKSparLINK
	END
	ELSE
	BEGIN
		INSERT INTO KL_KBK(Type, code, name, link_adm, USED)
			VALUES(@iType, @varKSCode, @varKSparNAME, @varKSLink_Adm, @iUsed)
		SELECT @varKSERROR = @@ERROR, @varKSparLINK = @@IDENTITY
		IF @varKSERROR <> 0 or coalesce(@varKSparLINK,0) <= 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END

	IF (select count(*) from KL_KBK_IVF where link_kbk = @varKSparLINK) = 1
	BEGIN
		UPDATE KL_KBK_IVF
			SET LINK_IVF = @varKSLink_IVF,
				LINK_PROG = @iProgLink,
				LINK_SGU = @varKSLink_SGU
			WHERE LINK_KBK = @varKSparLINK
		
		SELECT @varKSERROR = @@ERROR
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	ELSE
	BEGIN
		INSERT INTO KL_KBK_IVF 
			(Link_KBK, Link_IVF, LINK_PROG,LINK_SGU)
		VALUES (@varKSparLINK, @varKSLink_IVF, @iProgLink,@varKSLink_SGU)
		SELECT @varKSERROR = @@ERROR
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	
	SELECT @varKSEventText = 'КБК. Источник финанс. ' + @varKSCode + ' ' + @varKSparNAME, @varKSintObj = LINK FROM S_OBJECTS WHERE CODE = 'BI_DICTION_KBK'
	EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @varKSEventText, @varKSintObj, 'KL_KBK', @varKSparLINK
IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0





GO


GRANT EXECUTE ON dbo.[BI_SAVE_KBK_IVF] TO PUBLIC

GO


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

GO

CREATE PROCEDURE dbo.SA_CALENDAR_DAYS_INFO (@linkEmpl int, @Month int, @Year int)
AS

DECLARE @INFO TABLE (
	ORD TINYINT, 
	NAME VARCHAR(254), 
	DATE_BEG DATETIME, 
	DATE_END DATETIME, 
	COMMENT VARCHAR(254), 
	LINK_OBJ INT, 
	CODE_OBJ VARCHAR(254)
)

/* Расшифровка рассчёта календарных дней */

declare @DateBegin datetime, @DateEnd datetime

SET @DateBegin = dbo.ConvertDMY2Date(1,@Month,@Year) 
SET @DateEnd 	= dbo.DateEndOfMonth(@DateBegin)

DECLARE @DateAccept datetime, @DateSack datetime
SET @DateAccept = ISNULL(dbo.kd_DateBeginWork(@linkEmpl,@DateEnd),'19000101')
SET @DateSack   = ISNULL(dbo.kd_DateEndWork(@linkEmpl,@DateEnd),'30000101')

SET @DateBegin = (case when @DateAccept < @DateBegin then @DateBegin else @DateAccept end)
SET @DateEnd = (case when @DateSack < @DateEnd then @DateSack else @DateEnd end)  

DECLARE @RealCount NUMERIC(18,2)
SET @RealCount = DBO.SA_CALENDAR_DAYS_FN(@linkEmpl,@Month,@Year)

INSERT INTO @INFO (ORD, NAME, DATE_BEG, DATE_END, COMMENT, LINK_OBJ, CODE_OBJ)
SELECT 
	1, 'Период работы', @DateBegin, @DateEnd, 'Приказ о приёме/увольнениии',
	(SELECT ORDER_LINK FROM ITEM_MOVE WHERE NEW_FACE = 1 AND EMPL_LINK = @linkEmpl AND ACTIVE = 1),
	'ORDERS_REESTR'

UPDATE @INFO
SET LINK_OBJ = (SELECT TOP 1 ORDER_LINK FROM ITEM_DIS_FACE IM WHERE EMPL_LINK = @linkEmpl AND  ACTIVE = 1)
WHERE @DateSack = @DateEnd

DECLARE @S TABLE 
([TYPE] int,
 [PRIOR] int,
 [HOUR]  numeric(6,2),
 [DATE_1] datetime,
 [DATE_2] datetime,
 [DOC]	int,
 [H] int,
 LINK_DOC INT 	 	
)


--Учёт периодов с предыдущих мест работы, которые не должны включаться в расчёт календарных дней
DECLARE @TYPE_OTHER_DEP_PERIOD INT, @PRIOR_OTHER_DEP_PERIOD INT, @HOUR_OTHER_DEP_PERIOD NUMERIC(18,2)
SELECT TOP 1 @TYPE_OTHER_DEP_PERIOD = N.LINK, @PRIOR_OTHER_DEP_PERIOD = TD.PRIORITET, @HOUR_OTHER_DEP_PERIOD = TD.[HOUR]
FROM 
	dbo.NETRUD N
	INNER JOIN dbo.TYP_DAYS TD ON TD.LINK = N.TYPE_LINK
ORDER BY
	(CASE WHEN WORK_D = 13 THEN 1 ELSE 2 END), N.CODE

IF @TYPE_OTHER_DEP_PERIOD IS NOT NULL
	--INSERT INTO @S ([TYPE],[PRIOR],[HOUR],[DATE_1],[DATE_2],[DOC], [H], LINK_DOC)
	SELECT 
		[TYPE] = @TYPE_OTHER_DEP_PERIOD, 
		[PRIOR] = @PRIOR_OTHER_DEP_PERIOD, 
		[HOUR] = @HOUR_OTHER_DEP_PERIOD,
		[DATE_1] = (CASE WHEN P.DATE1 < @DateBegin THEN @DateBegin ELSE P.DATE1 END),
		[DATE_2] = (CASE WHEN P.DATE2 > @DateEnd  THEN @DateEnd ELSE P.DATE2 END),
		[DOC]	= 4,--периоды с предыдущих мест работы
		[H] = 0,
		D.LINK
	FROM
		dbo.SAL_OTHER_DEP D
		INNER JOIN dbo.SAL_OTHER_DEP_PERIOD_DATES P ON D.LINK = P.LINK_DOC
	WHERE
		LINK_EMPL = @linkEmpl
		AND
		(
			P.DATE1 BETWEEN @DateBegin AND @DateEnd 
			OR P.DATE2 BETWEEN @DateBegin AND @DateEnd 
			OR (P.DATE1 < @DateBegin AND P.DATE2 > @DateEnd)
		)		
-----------------------------------------------------------------------

INSERT INTO @S ([TYPE],[PRIOR],[HOUR],[DATE_1],[DATE_2],[DOC], [H], LINK_DOC)
--больничные
SELECT [TYPE],[PRIOR],[HOUR],[DATE_1],[DATE_2],[DOC], H, LINK FROM 
(SELECT 
	[TYPE] = SD.[TYPE],
	[PRIOR] = TD.PRIORITET,
	[HOUR] = TD.[HOUR],
	[DATE_1] = (CASE WHEN SD.DATE1 < @DateBegin THEN @DateBegin ELSE SD.DATE1 END),
	[DATE_2] = (CASE WHEN SD.DATE2 > @DateEnd  THEN @DateEnd ELSE SD.DATE2 END),
	[DOC]	= 1,
	[H] = 0,
	LINK = SD.LINK_UP 
FROM 
	dbo.SDOC_DIS SD
	INNER JOIN dbo.NETRUD N ON SD.[TYPE] = N.LINK
	INNER JOIN dbo.TYP_DAYS TD ON TD.LINK = N.TYPE_LINK
WHERE 
	SD.LINK_EMPL = @linkEmpl
	AND
	(SD.DATE1 BETWEEN @DateBegin AND @DateEnd OR SD.DATE2 BETWEEN @DateBegin AND @DateEnd OR
	  ((SD.DATE1 < @DateBegin) AND(SD.DATE2 > @DateEnd)))
  
UNION
--отпускные
SELECT 	
	[TYPE] = VV.TYPE_LINK,
	[PRIOR] = TD.PRIORITET,
	[HOUR] 	= TD.[HOUR],
	[DATE_1] = (CASE WHEN DATE_BEGIN < @DateBegin THEN @DateBegin ELSE IV.DATE_BEGIN END),
	[DATE_2] = (CASE WHEN ISNULL((

					SELECT top 1 (CASE WHEN IVB.DATE_BREAK - 1 > (ISNULL((

                    SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  
 					FROM dbo.ITEM_VACATION_DIS IVD
                    WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc),IV.DATE_END)) 
					
                    THEN (ISNULL((

					SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  
 					FROM dbo.ITEM_VACATION_DIS IVD
					WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc),IV.DATE_END)) 
					
					ELSE IVB.DATE_BREAK - 1 END) 

					FROM dbo.ITEM_VACATION_BREAK IVB
					WHERE IVB.VAC_LINK = IV.LINK AND IVB.ACTIVE = 1 order by IVB.DATE_BREAK desc), 
					
                    (ISNULL((

					SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  
 					FROM dbo.ITEM_VACATION_DIS IVD 
					WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc ),IV.DATE_END))) >@DateEnd 

					THEN @DateEnd  
                    ELSE ISNULL((

                    SELECT top 1 (CASE WHEN IVB.DATE_BREAK - 1 > (ISNULL((

					SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  
 					FROM ITEM_VACATION_DIS IVD
        				WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc ),IV.DATE_END)) 
					
                    THEN (ISNULL((

					SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  

 					FROM dbo.ITEM_VACATION_DIS IVD
					WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc),IV.DATE_END)) 

					ELSE IVB.DATE_BREAK - 1 END)  
					
					FROM dbo.ITEM_VACATION_BREAK IVB
					WHERE IVB.VAC_LINK = IV.LINK AND IVB.ACTIVE = 1 order by IVB.DATE_BREAK desc),
					
					ISNULL((
					
					SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  
 					FROM dbo.ITEM_VACATION_DIS IVD 
					WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc),IV.DATE_END)) END),
	[DOC] = (case when coalesce(TD.WORK_D,1) = 7 then 22 else 2 end),
	H = VV.HOLIDAY,
	LINK = IV.LINK
FROM 
	dbo.item_vacation iv
	INNER JOIN dbo.vacation_vid VV ON VV.LINK = iv.type_link
	INNER JOIN dbo.TYP_DAYS TD ON TD.LINK = VV.TYPE_LINK
WHERE 
	IV.EMPL_LINK = @linkEmpl 
	AND IV.ACTIVE = 1
	AND COALESCE(VV.TIME_ARCHE,0) = 0 
	AND (IV.DATE_BEGIN BETWEEN @DateBegin AND @DateEnd 
		OR IV.DATE_END BETWEEN @DateBegin AND @DateEnd 
		OR ((IV.DATE_BEGIN<@DateBegin) AND (IV.DATE_END>@DateEnd))
		OR IV.LINK IN (SELECT VAC_LINK FROM dbo.VACATION_DIS WHERE EMPL_LINK = @linkEmpl AND ACTIVE = 1 AND NEW_DATE_END > @DateBegin)
	    )
	AND IV.LINK NOT IN (SELECT VAC_LINK FROM dbo.item_vacation_break ivb WHERE EMPL_LINK = @linkEmpl AND ACTIVE = 1 AND ivb.DATE_BREAK < @DateBegin)
--командировочные
UNION
SELECT 
	[TYPE] 	= it.type_link, 
	[PRIOR] = TD.PRIORITET,
	[HOUR] = TD.[HOUR], 
	[DATE_1] = (CASE WHEN IT.[DATE_BEGIN]<@DateBegin THEN @DateBegin ELSE IT.[DATE_BEGIN] END),
	[DATE_2] = (CASE WHEN (ISNULL((SELECT (CASE WHEN ITL.NEW_DATE_END > IT.DATE_END THEN ITL.NEW_DATE_END ELSE IT.DATE_END END)
				 FROM dbo.ITEM_TRAVEL_LONG ITL WHERE ITL.TRAVEL_LINK = IT.LINK AND ITL.ACTIVE = 1),IT.DATE_END))> @DateEnd 
				 THEN @DateEnd ELSE 
				(ISNULL((SELECT (CASE WHEN ITL.NEW_DATE_END > IT.DATE_END THEN ITL.NEW_DATE_END ELSE IT.DATE_END END)
				 FROM dbo.ITEM_TRAVEL_LONG ITL WHERE ITL.TRAVEL_LINK = IT.LINK AND ITL.ACTIVE = 1),IT.DATE_END)) END),
	[DOC]= 3,
	[H] = 0,
	LINK = IT.LINK
FROM 
	dbo.item_travel IT
	INNER JOIN dbo.komand_vid KV ON KV.LINK = IT.type_link
	INNER JOIN dbo.TYP_DAYS TD ON TD.LINK = KV.TYPE_LINK
WHERE  
	IT.EMPL_LINK = @linkEmpl 
	AND IT.ACTIVE = 1 
	AND COALESCE(KV.TIME_ARCHE,0) = 0 
	AND (IT.DATE_BEGIN BETWEEN @DateBegin AND @DateEnd 
		OR IT.DATE_END BETWEEN @DateBegin AND @DateEnd 
		OR ((IT.DATE_BEGIN<@DateBegin) AND(IT.DATE_END>@DateEnd))
	 )
)  TAB

DELETE FROM @S
WHERE DATE_1 > DATE_2

INSERT INTO @INFO (ORD, NAME, DATE_BEG, DATE_END, COMMENT, LINK_OBJ, CODE_OBJ)
	SELECT 2, 'Больничный лист', DATE_1, DATE_2, 'Больничный лист', LINK_DOC, 'ORDER_DISABILITY_SHEET'
	FROM @S WHERE DOC = 1
UNION 
	SELECT 3, 'Отпуск, учитывающий праздники', DATE_1, DATE_2, 'Приказ на отпуск', LINK_DOC, 'VACATION'
	FROM @S WHERE DOC IN (2,22) AND coalesce(H,0) = 1
UNION 
	SELECT 4, 'Отпуск, не учитывающий праздники', DATE_1, DATE_2, 'Приказ на отпуск', LINK_DOC, 'VACATION'
	FROM @S WHERE DOC IN (2,22) AND coalesce(H,0) <> 1
UNION 
	SELECT 5, 'Командировка', DATE_1, DATE_2, 'Приказ на командировку', LINK_DOC, 'TRAVEL'
	FROM @S WHERE DOC = 3
UNION 
	SELECT 6, 'Заработок у другого работодателя', DATE_1, DATE_2, 'Заработок у другого работодателя', LINK_DOC, 'DOC_SAL_OTHER_DEP'
	FROM @S WHERE DOC = 4	

INSERT INTO @INFO (ORD, NAME, DATE_BEG, DATE_END, COMMENT, LINK_OBJ, CODE_OBJ)
	SELECT 7, 'Праздничные дни', t1.DATE, t1.DATE, TYPE_HOL_STR, LINK, 'KD_HOLIDAYS'
	FROM
		dbo.SD_DAY(@DateBegin,@DateEnd) T1 
		INNER JOIN KD_HOLIDAYS DH ON day(t1.DATE) = DH.DAY and month(t1.DATE) = DH.MONTH and YEAR(t1.DATE) = DH.YEAR
	WHERE 
		(DH.WORK_D = 14 or DH.WORK_D = 11) AND TYPE_HOL = 1
		AND
		EXISTS (SELECT * FROM @INFO I WHERE ORD = 3 AND T1.DATE BETWEEN DATE_BEG AND DATE_END)

SELECT ORD, [NAME] AS NAME_PER, DATE_BEG, DATE_END, 
	CNT_DAYS = CASE WHEN ORD BETWEEN 2 AND 6 THEN -1 ELSE 1 END * (datediff(day,DATE_BEG,DATE_END) + 1 ), 
	RealCount = @RealCount, COMMENT AS COM , LINK_OBJ, CODE_OBJ 
FROM @INFO ORDER BY ORD, DATE_BEG

RETURN 0






GO


GRANT EXECUTE ON dbo.[SA_CALENDAR_DAYS_INFO] TO PUBLIC

GO




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

GO

CREATE   PROCEDURE dbo.SA_IMPORT_PAY_ROLL_BANK_FORMATS 
	@BUFFER_ID VARCHAR(20)
AS

	DECLARE @SEPARETE TINYINT
	/*
	@SEPARETE 1 не разделять, 2 разделять по типу ведомости, 3 разделять по виду удержания, 4 разделять по типу ведомости и виду удержания
	*/
	SET @SEPARETE = dbo.SA_GET_OPTION_BY_CODE('VEDOM_OPTIONS_OPT14')
	--Вдруг не проинициализирована
	SET @SEPARETE = CASE WHEN @SEPARETE < 1 THEN 1 ELSE @SEPARETE END
	
	SELECT DISTINCT
		LINK_VEDOM = B.LINK, V.LINK_CARD, LINK = NC.FRMT_LINK, F.CODE, F.NAME, F.IsUserObject, F.UserFilename, 
		F.PRINT_OBJECT_METHOD, F.QUERY_ADD_MODULE, F.QUERY_REPMAKER, F.QUERY_REPORT, 
		F.QUERY_REPORT_PATH, F.LastFileNumber, F.IsDefaultFormat, F.SumType,
		C.BANK_LINK, 
		LINK_PAY = CASE WHEN @SEPARETE IN (3,4) THEN V.LINK_PAY ELSE -1 END, 
		TYP_PAYMENT = CASE WHEN @SEPARETE IN (2,4) THEN V.TYP_PAYMENT ELSE -1 END,
		COMMENT = LEFT('ФОРМАТ: ' + LTRIM(RTRIM(COALESCE(F.NAME,'НЕ ЗАДАН')))
				+ ', ТИП КАРТЫ: ' + LTRIM(RTRIM(COALESCE(NC.NAME,'НЕ ЗАДАН')))
				+ ', БАНК: ' + LTRIM(RTRIM(COALESCE(BK.NAME,'НЕ ЗАДАН')))
				+ CASE WHEN @SEPARETE IN (3,4) THEN ', ВИД УДЕРЖАНИЯ: ' + LTRIM(RTRIM(COALESCE(P.NAME,'НЕ ЗАДАН'))) ELSE '' END
				+ CASE WHEN @SEPARETE IN (2,4) THEN ', ВИД ВЫПЛАТЫ: ' + CASE V.TYP_PAYMENT WHEN 1 THEN 'ЗАРПЛАТА' WHEN 2 THEN 'АВАНС' ELSE 'МЕЖРАСЧЕТНАЯ ВЫПЛАТА' END ELSE '' END
				,254)
	FROM 
		dbo.BUFFER B
		INNER JOIN dbo.SDOC_VEDOM V ON V.LINK_UP = B.LINK
		INNER JOIN dbo.CARDS NC ON NC.LINK = V.LINK_CARD
		INNER JOIN DBO.S_BANK_FORMATS F ON F.LINK = NC.FRMT_LINK
		INNER JOIN dbo.SDOC_VEDOM_TABLE1 T ON T.LINK_UP = V.LINK_UP
		INNER JOIN DBO.EMPL E ON E.LINK = T.LINK_EMPL
		INNER JOIN dbo.SA_PERSON_ECARD_ACTUAL C ON C.PERS_LINK = E.PERS_LINK AND C.CARD_LINK = V.LINK_CARD
		INNER JOIN dbo.PAYS P ON P.LINK = V.LINK_PAY
		LEFT JOIN [dbo].[BANKS] BK ON BK.LINK = C.BANK_LINK

	WHERE
		B.ID = @BUFFER_ID
	UNION ALL
	SELECT DISTINCT
		LINK_VEDOM = B.LINK, V.LINK_CARD, LINK = NC.FRMT_LINK, F.CODE, F.NAME, F.IsUserObject, F.UserFilename, 
		F.PRINT_OBJECT_METHOD, F.QUERY_ADD_MODULE, F.QUERY_REPMAKER, F.QUERY_REPORT, 
		F.QUERY_REPORT_PATH, F.LastFileNumber, F.IsDefaultFormat, F.SumType,
		C.BANK_LINK, 
		LINK_PAY = CASE WHEN @SEPARETE IN (3,4) THEN V.LINK_PAY ELSE -1 END, 
		TYP_PAYMENT = CASE WHEN @SEPARETE IN (2,4) THEN V.TYP_PAYMENT ELSE -1 END,
		COMMENT = LEFT('ФОРМАТ: ' + LTRIM(RTRIM(COALESCE(F.NAME,'НЕ ЗАДАН')))
				+ ', ТИП КАРТЫ: ' + LTRIM(RTRIM(COALESCE(NC.NAME,'НЕ ЗАДАН')))
				+ ', БАНК: ' + LTRIM(RTRIM(COALESCE(BK.NAME,'НЕ ЗАДАН')))
				+ CASE WHEN @SEPARETE IN (3,4) THEN ', ВИД УДЕРЖАНИЯ: ' + LTRIM(RTRIM(COALESCE(P.NAME,'НЕ ЗАДАН'))) ELSE '' END
				+ CASE WHEN @SEPARETE IN (2,4) THEN ', ВИД ВЫПЛАТЫ: ' + CASE V.TYP_PAYMENT WHEN 1 THEN 'ЗАРПЛАТА' WHEN 2 THEN 'АВАНС' ELSE 'МЕЖРАСЧЕТНАЯ ВЫПЛАТА' END ELSE '' END
				,254)
	FROM 
		dbo.BUFFER B
		INNER JOIN dbo.SDOC_VEDOM_DGH V ON V.LINK_UP = B.LINK
		INNER JOIN dbo.CARDS NC ON NC.LINK = V.LINK_CARD
		INNER JOIN DBO.S_BANK_FORMATS F ON F.LINK = NC.FRMT_LINK
		INNER JOIN dbo.SDOC_VEDOM_DGH_TABLE1 T ON T.LINK_UP = V.LINK_UP
		INNER JOIN dbo.SA_PERSON_ECARD_ACTUAL C ON C.PERS_LINK = T.PERS_LINK AND C.CARD_LINK = V.LINK_CARD
		INNER JOIN dbo.PAYS P ON P.LINK = V.LINK_PAY
		LEFT JOIN [dbo].[BANKS] BK ON BK.LINK = C.BANK_LINK
	WHERE
		B.ID = @BUFFER_ID		


GO


GRANT EXECUTE ON dbo.[SA_IMPORT_PAY_ROLL_BANK_FORMATS] TO PUBLIC

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

GO

CREATE PROCEDURE dbo.SA_CALENDAR_DAYS3_ALLYEAR_INFO (@linkEmpl int, @Year int)
AS

DECLARE @INFO TABLE (
	ORD TINYINT, 
	SYMB varchar(4),
	NAME VARCHAR(254), 
	DATE_BEG DATETIME, 
	DATE_END DATETIME, 
	COMMENT VARCHAR(254), 
	LINK_OBJ INT, 
	CODE_OBJ VARCHAR(254)
)

/* Расшифровка рассчёта календарных дней */

declare @DateBegin datetime, @DateEnd datetime

--SET @DateBegin = dbo.ConvertDMY2Date(1,@Month,@Year) 
--SET @DateEnd 	= dbo.DateEndOfMonth(@DateBegin)

SET @DateBegin = dbo.ConvertDMY2Date(1,1,@Year) 
SET @DateEND = dbo.ConvertDMY2Date(1,12,@Year)
SET @DateEnd 	= dbo.DateEndOfMonth(@DateEND)

DECLARE @DateAccept datetime, @DateSack datetime
SET @DateAccept = ISNULL(dbo.kd_DateBeginWork(@linkEmpl,@DateEnd),'19000101')
SET @DateSack   = ISNULL(dbo.kd_DateEndWork(@linkEmpl,@DateEnd),'30000101')

SET @DateBegin = (case when @DateAccept < @DateBegin then @DateBegin else @DateAccept end)
SET @DateEnd = (case when @DateSack < @DateEnd then @DateSack else @DateEnd end)  

DECLARE @RealCount NUMERIC(18,2)
SET @RealCount = DBO.SA_CALENDAR_DAYS3_AllYear_FN(@linkEmpl,@Year)

INSERT INTO @INFO (ORD,SYMB, NAME, DATE_BEG, DATE_END, COMMENT, LINK_OBJ, CODE_OBJ)
SELECT 
	1,'', 'Период работы', @DateBegin, @DateEnd, 'Приказ о приёме/увольнениии',
	(SELECT ORDER_LINK FROM ITEM_MOVE WHERE NEW_FACE = 1 AND EMPL_LINK = @linkEmpl AND ACTIVE = 1),
	'ORDERS_REESTR'

UPDATE @INFO
SET LINK_OBJ = (SELECT TOP 1 ORDER_LINK FROM ITEM_DIS_FACE IM WHERE EMPL_LINK = @linkEmpl AND  ACTIVE = 1)
WHERE @DateSack = @DateEnd

DECLARE @S TABLE 
([TYPE] int,
 [SYMB] varchar(4),
 [PRIOR] int,
 [HOUR]  numeric(6,2),
 [DATE_1] datetime,
 [DATE_2] datetime,
 [DOC]	int,
 [H] int,
 LINK_DOC INT 	 	
)

INSERT INTO @S ([TYPE], [SYMB],[PRIOR],[HOUR],[DATE_1],[DATE_2],[DOC], [H], LINK_DOC)
---больничные
SELECT [TYPE], [SYMB],[PRIOR],[HOUR],[DATE_1],[DATE_2],[DOC], H, LINK FROM 
(SELECT 
	[TYPE] = SD.[TYPE],
	[SYMB] = TD.SYMB,
	[PRIOR] = TD.PRIORITET,
	[HOUR] = TD.[HOUR],
	[DATE_1] = (CASE WHEN SD.DATE1 < @DateBegin THEN @DateBegin ELSE SD.DATE1 END),
	[DATE_2] = (CASE WHEN SD.DATE2 > @DateEnd  THEN @DateEnd ELSE SD.DATE2 END),
	[DOC]	= 1,
	[H] = 0,
	LINK = SD.LINK_UP 
FROM 
	dbo.SDOC_DIS SD
	INNER JOIN dbo.NETRUD N ON SD.[TYPE] = N.LINK
	INNER JOIN dbo.TYP_DAYS TD ON TD.LINK = N.TYPE_LINK
WHERE 
	SD.LINK_EMPL = @linkEmpl
	AND
	(SD.DATE1 BETWEEN @DateBegin AND @DateEnd OR SD.DATE2 BETWEEN @DateBegin AND @DateEnd OR
	  ((SD.DATE1 < @DateBegin) AND(SD.DATE2 > @DateEnd)))
  
UNION
--отпускные
SELECT 	
	[TYPE] = VV.TYPE_LINK,
	[SYMB] = TD.SYMB,
	[PRIOR] = TD.PRIORITET,
	[HOUR] 	= TD.[HOUR],
	[DATE_1] = (CASE WHEN DATE_BEGIN < @DateBegin THEN @DateBegin ELSE IV.DATE_BEGIN END),
	[DATE_2] = (CASE WHEN ISNULL((

					SELECT top 1 (CASE WHEN IVB.DATE_BREAK - 1 > (ISNULL((

                    SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  
 					FROM dbo.ITEM_VACATION_DIS IVD
                    WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc),IV.DATE_END)) 
					
                    THEN (ISNULL((

					SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  
 					FROM dbo.ITEM_VACATION_DIS IVD
					WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc),IV.DATE_END)) 
					
					ELSE IVB.DATE_BREAK - 1 END) 

					FROM dbo.ITEM_VACATION_BREAK IVB
					WHERE IVB.VAC_LINK = IV.LINK AND IVB.ACTIVE = 1 order by IVB.DATE_BREAK desc), 
					
                    (ISNULL((

					SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  
 					FROM dbo.ITEM_VACATION_DIS IVD 
					WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc ),IV.DATE_END))) >@DateEnd 

					THEN @DateEnd  
                    ELSE ISNULL((

                    SELECT top 1 (CASE WHEN IVB.DATE_BREAK - 1 > (ISNULL((

					SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  
 					FROM ITEM_VACATION_DIS IVD
        				WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc ),IV.DATE_END)) 
					
                    THEN (ISNULL((

					SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  

 					FROM dbo.ITEM_VACATION_DIS IVD
					WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc),IV.DATE_END)) 

					ELSE IVB.DATE_BREAK - 1 END)  
					
					FROM dbo.ITEM_VACATION_BREAK IVB
					WHERE IVB.VAC_LINK = IV.LINK AND IVB.ACTIVE = 1 order by IVB.DATE_BREAK desc),
					
					ISNULL((
					
					SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  
 					FROM dbo.ITEM_VACATION_DIS IVD 
					WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc),IV.DATE_END)) END),
	[DOC] = (case when coalesce(TD.WORK_D,1) = 7 then 22 else 2 end),
	H = VV.HOLIDAY,
	LINK = IV.LINK
FROM 
	dbo.item_vacation iv
	INNER JOIN dbo.vacation_vid VV ON VV.LINK = iv.type_link
	INNER JOIN dbo.TYP_DAYS TD ON TD.LINK = VV.TYPE_LINK
WHERE 
	IV.EMPL_LINK = @linkEmpl 
	AND IV.ACTIVE = 1
	AND COALESCE(VV.TIME_ARCHE,0) = 0 
	AND (IV.DATE_BEGIN BETWEEN @DateBegin AND @DateEnd 
		OR IV.DATE_END BETWEEN @DateBegin AND @DateEnd 
		OR ((IV.DATE_BEGIN<@DateBegin) AND (IV.DATE_END>@DateEnd))
		OR IV.LINK IN (SELECT VAC_LINK FROM dbo.VACATION_DIS WHERE EMPL_LINK = @linkEmpl AND ACTIVE = 1 AND NEW_DATE_END > @DateBegin)
	    )
	AND IV.LINK NOT IN (SELECT VAC_LINK FROM dbo.item_vacation_break ivb WHERE EMPL_LINK = @linkEmpl AND ACTIVE = 1 AND ivb.DATE_BREAK < @DateBegin)
	AND
	(
		VV.NO_SAL = 1 --дни отпуска без сохранения заработной платы
	OR	
		TD.WORK_D = 7 -- Частично оплачиваемый отпуск женщинам, имеющим детей  в  возрасте до 1,5 лет
					-- Дополнительный отпуск без сохранения  заработной  платы  матерям, имеющим детей в возрасте до 3 лет
	OR
		TD.WORK_D = 5 -- Учебный отпуск
	OR
		VV.ADM = 1 -- Административный	
	)

--командировочные не учитываются
	
)  TAB

DELETE FROM @S
WHERE DATE_1 > DATE_2


INSERT INTO @INFO (ORD,SYMB, NAME, DATE_BEG, DATE_END, COMMENT, LINK_OBJ, CODE_OBJ)
	SELECT 2,SYMB, case when SYMB = 'Р' then 'Отпуск по беременности и родам' when SYMB = 'ОЧ' then 'Отпуск по уходу за ребенком' else 'Временная нетрудоспособность' end, DATE_1, DATE_2, case when SYMB = 'Р' then 'Отпуск по беременности и родам' when SYMB = 'ОЧ' then 'Отпуск по уходу за ребенком' else 'Временная нетрудоспособность' end, LINK_DOC, 'ORDER_DISABILITY_SHEET'
	FROM @S WHERE DOC = 1
UNION 
	SELECT 3,'', 'Отпуск, учитывающий праздники', DATE_1, DATE_2, 'Приказ на отпуск', LINK_DOC, 'VACATION'
	FROM @S WHERE DOC IN (2,22) AND coalesce(H,0) = 1
UNION 
	SELECT 4,'', 'Отпуск, не учитывающий праздники', DATE_1, DATE_2, 'Приказ на отпуск', LINK_DOC, 'VACATION'
	FROM @S WHERE DOC IN (2,22) AND coalesce(H,0) <> 1
UNION 
	SELECT 5,'', 'Командировка', DATE_1, DATE_2, 'Приказ на командировку', LINK_DOC, 'TRAVEL'
	FROM @S WHERE DOC = 3

INSERT INTO @INFO (ORD,SYMB, NAME, DATE_BEG, DATE_END, COMMENT, LINK_OBJ, CODE_OBJ)
	SELECT 6, '', 'Праздничные дни', t1.DATE, t1.DATE, TYPE_HOL_STR, LINK, 'KD_HOLIDAYS'
	FROM
		dbo.SD_DAY(@DateBegin,@DateEnd) T1 
		INNER JOIN KD_HOLIDAYS DH ON day(t1.DATE) = DH.DAY and month(t1.DATE) = DH.MONTH and YEAR(t1.DATE) = DH.YEAR
	WHERE 
		(DH.WORK_D = 14 or DH.WORK_D = 11) AND TYPE_HOL = 1
		AND
		EXISTS (SELECT * FROM @INFO I WHERE ORD = 3 AND T1.DATE BETWEEN DATE_BEG AND DATE_END)

SELECT ORD,SYMB, [NAME] AS NAME_PER, DATE_BEG, DATE_END, 
	CNT_DAYS = abs(CASE WHEN ORD BETWEEN 2 AND 5 THEN -1 ELSE 1 END * (datediff(day,DATE_BEG,DATE_END) + 1 )), 
	RealCount = @RealCount, COMMENT AS COM , LINK_OBJ, CODE_OBJ 
FROM @INFO ORDER BY ORD, DATE_BEG

RETURN 0








GO


GRANT EXECUTE ON dbo.[SA_CALENDAR_DAYS3_ALLYEAR_INFO] TO PUBLIC

GO


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

GO

CREATE PROCEDURE dbo.BK_REPORT_BOOK_MAIN 
		@DATE_START		DATETIME	/* -- НАЧАЛО ПЕРИОДА -- */,
		@DATE_STOP		DATETIME	/* -- КОНЕЦ ПЕРИОДА -- */,
--		@ACCOUNT_LONG		tinyint,
--		@cSOURCE		CHAR (1),
		@intSTR_JO		INT,		/* -- 0 - Разделять обороты по ЖО,
								1 - Выводить ЖО ондной строкой с одинаковой аналитикой -- */
--		@intSource0		INT,
		@intZabalansAcct	INT,
		@intACCT_GR		INT,
		@varKScVal1	char(1), @varKSnOtborLink1 int,	 -- Отбор субсчетов --
		@intPRN_KBK	int,				-- Код счета с КБК --
		@intPRN_KOSGU	int,				-- Код счета с КОСГУ --
		@intSVOD_ZB	int,				-- Сводный отчет (ЦБ) --
		@intGRP_SGU	int,				-- Вывести подитоги по субсчетам с по группе КОСГУ --
		@cVal_KBK char(1), @nOtborLinkKBK int,		-- Отбор КБК --
		@cVal_KOSGU char(1), @nOtborLinkKOSGU int,	-- Отбор КОСГУ --
		@cVal_SFIN char(1), @nOtborLinkSFIN int,	-- Отбор источников финансирования --
		@cVal_KAU char(1) = '', @nOtborKAU	int	= 0 -- Отбор источников финансирования --
AS
BEGIN
	DECLARE @DATE_BEG_YEAR DATETIME,  -- Дата начала года
		@MONTH_NAME VARCHAR(20),  -- Дата начала года
		@OUT_DATE_REST	DATETIME, -- Для расчета конечных остатков

		@intDEP_LINK	INT,
		@strORGNAME	VARCHAR (254),
		@strOKPO	VARCHAR (20),
		@strGLBUH	VARCHAR (100),
		@UCHR_NAME	VARCHAR (254),	-- Учредитель
		@BUDG_NAME	VARCHAR (254)	-- Наименование бюджета

	SET @DATE_BEG_YEAR = dbo.DateBeginOfYear (@DATE_START)
	SELECT @MONTH_NAME = dbo.DateMonthName(MONTH(@DATE_STOP))

	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)	/* -- Сводный отчет по ЦБ -- */
	SET @intDEP_LINK = ISNULL (dbo.BK_GetDepZB (), dbo.GetOwnDepLink ())
	
	IF @intSVOD_ZB = 1				/* -- Сводный отчет по ЦБ (собственные реквизиты организации) -- */
		SET @intDEP_LINK = dbo.GetOwnDepLink ()

	SELECT
		@strOKPO = D.[OKPO],
		@strORGNAME = dbo.BK_GET_PRINT_DEP_NAME (D.LINK),
		@UCHR_NAME = dbo.BK_GET_PRINT_DEP_NAME (D.UCHR_LINK),
		@BUDG_NAME = B.[NAME]
	FROM dbo.DEPARTMENTS D
	LEFT JOIN dbo.KL_ADMIN_BS V ON (V.LINK = D.VED_LINK)
	LEFT JOIN dbo.KL_BUDG_TYPE B ON (B.LINK = V.Link_Budg)
	WHERE D.LINK = @intDEP_LINK

	SELECT @UCHR_NAME = ISNULL (@UCHR_NAME, ''),
		@BUDG_NAME = ISNULL (@BUDG_NAME, '')

	IF @intSVOD_ZB = 1
		SET @strORGNAME = RTRIM (@strORGNAME) + ' (ЦБ)'

	SELECT @strGLBUH = SHORT_NAME
	FROM dbo.GetOtvFaceData (@intDEP_LINK, 'Главный бухгалтер')

	--- ОТБОР ПО СУБСЧЕТАМ --- 
	-- Отбор источников финансирования --
	DECLARE @TAB_SFIN TABLE (CODE CHAR (2))

	IF LEN (@cVal_SFIN) > 0 
		INSERT INTO @TAB_SFIN
		SELECT 
			D.CODE
		FROM dbo.OBJECT_VAR_FIN_SOURCE OVR
		INNER JOIN dbo.FIN_SOURCE D ON (D.LINK = OVR.RECORD)
		WHERE OVR.LINK_UP = @nOtborLinkSFIN
--			AND D.ISUSED = 1
	ELSE
	BEGIN
		INSERT INTO @TAB_SFIN
		SELECT 
			D.CODE
		FROM dbo.FIN_SOURCE D 
		WHERE D.ISUSED = 1

		INSERT INTO @TAB_SFIN (CODE) 
		SELECT ''
	END

	-- Отбор субсчетов --
	DECLARE @TAB_ACCT TABLE (ACCOUNT INT, ACCT_ROOT INT, JO INT)

	IF LEN (@varKScVal1) > 0
		INSERT INTO @TAB_ACCT
		SELECT
			OVR.RECORD,
			CASE 
				WHEN SA.cUSER <> '' THEN SA.LINK_SELF
				ELSE OVR.RECORD
			END,
			0	-- ЖО НЕ БЕРЕМ ИЗ ПС -- 
--			SA.JO
		FROM dbo.OBJECT_VAR_ACCT OVR
		INNER JOIN dbo.S_ACCOUNTS SA ON (OVR.RECORD = SA.LINK)
		WHERE OVR.LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO @TAB_ACCT
		SELECT
			SA.LINK,
			CASE 
				WHEN SA.cUSER <> '' THEN SA.LINK_SELF
				ELSE SA.LINK
			END,
			0	-- ЖО НЕ БЕРЕМ ИЗ ПС --
		FROM dbo.AccountsTableWithNoChild () T1
		INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = T1.LINK)
		INNER JOIN @TAB_SFIN T2 ON (T2.CODE = SA.cSOURCE)
		WHERE (@intZabalansAcct = 1
			OR (@intZabalansAcct = 2 AND ZABALANS = 0)
			OR (@intZabalansAcct = 3 AND ZABALANS = 1))

	--- ОТБОР ПО КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	--- ОТБОР ПО КОСГУ --- 
	DECLARE @TAB_KOSGU TABLE (LINK INT, CODE VARCHAR (20))
	IF LEN (@cVal_KOSGU) > 0
		INSERT INTO @TAB_KOSGU
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KOSGU AP 
		INNER JOIN dbo.OBJECT_VAR_KOSGU OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKOSGU
	ELSE
		INSERT INTO @TAB_KOSGU
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('SGU')

	--- ОТБОР ПО КАУ --- 
	DECLARE @T_KAU TABLE (LINK INT)
	IF LEN (@cVal_KAU) > 0
		INSERT INTO @T_KAU
		SELECT
			OVR.RECORD 
		FROM dbo.OBJECT_VAR_KAU OVR
		WHERE OVR.LINK_UP = @nOtborKAU
	ELSE
		SET @nOtborKAU = 0

	-- BEGIN YEAR --
	DECLARE @SALDO_BEGIN_YEAR TABLE
		(
		ACCOUNT [INT],
		SGU [INT],
		KBK [INT],
		KAU	INT,
		JO [INT],
		D_SUMMA [NUMERIC] (28,2),
		K_SUMMA [NUMERIC] (28,2)
		)

	INSERT INTO @SALDO_BEGIN_YEAR
	SELECT
		SA.ACCT_ROOT,
		CASE 
			WHEN @intPRN_KOSGU = 1 THEN ISNULL (SGU, 0)
			ELSE 0
		END, 
		CASE 
			WHEN @intPRN_KBK = 1 THEN ISNULL (KBK, 0)
			ELSE 0
		END,
		NULL,
		ISNULL (SA.JO, 0),
		SUM (D_SUMMA),
		SUM (K_SUMMA)
	FROM dbo.BB_RestSaldoForLedgerByDate1 (@DATE_BEG_YEAR, DEFAULT, 1) SBY
	INNER JOIN @TAB_ACCT SA ON (SBY.ACCOUNT = SA.ACCOUNT)
	INNER JOIN @TAB_KBK AP ON (AP.LINK_KBK = ISNULL (SBY.KBK, 0))
	INNER JOIN @TAB_KOSGU KOSGU ON (KOSGU.LINK = ISNULL (SBY.SGU, 0))
	WHERE (@intSVOD_ZB = 1
				AND SBY.DEP_LINK IN (SELECT LINK FROM dbo.DEPARTMENTS WHERE ZB = 1 OR [TYPE] = 4)
			OR @intSVOD_ZB = 0 AND SBY.DEP_LINK = @intDEP_LINK)
		AND (@nOtborKAU = 0
			OR @nOtborKAU > 0 AND EXISTS (SELECT * FROM @T_KAU TTT WHERE TTT.LINK = SBY.KAU)
			)	
	GROUP BY
		SA.ACCT_ROOT,
		CASE 
			WHEN @intPRN_KOSGU = 1 THEN ISNULL (SGU, 0)
			ELSE 0
		END, 
		CASE 
			WHEN @intPRN_KBK = 1 THEN ISNULL (KBK, 0)
			ELSE 0
		END,
		ISNULL (SA.JO, 0)

--select * from @SALDO_BEGIN_YEAR
--select * from @TAB_ACCT
	-- BEGIN PERIOD --
	DECLARE @SALDO_BEGIN_PERIOD TABLE
		(
		ACCOUNT [INT],
		SGU [INT],
		KBK [INT],
		KAU	INT,
		JO [INT],
		D_SUMMA [NUMERIC] (28,2),
		K_SUMMA [NUMERIC] (28,2)
		)

	INSERT INTO @SALDO_BEGIN_PERIOD
	SELECT
		SA.ACCT_ROOT,
		CASE 
			WHEN @intPRN_KOSGU = 1 THEN ISNULL (SGU, 0)
			ELSE 0
		END, 
		CASE 
			WHEN @intPRN_KBK = 1 THEN ISNULL (KBK, 0)
			ELSE 0
		END,
		NULL,
		ISNULL (SA.JO, 0),
		SUM (D_SUMMA),
		SUM (K_SUMMA)
	FROM dbo.BB_RestSaldoForLedgerByDate1(@DATE_START, DEFAULT, 1) SB
	INNER JOIN @TAB_ACCT SA ON (SB.ACCOUNT = SA.ACCOUNT)
	INNER JOIN @TAB_KBK AP ON (AP.LINK_KBK = ISNULL (SB.KBK, 0))
	INNER JOIN @TAB_KOSGU KOSGU ON (KOSGU.LINK = ISNULL (SB.SGU, 0))
	WHERE (@intSVOD_ZB = 1
				AND SB.DEP_LINK IN (SELECT LINK FROM dbo.DEPARTMENTS WHERE ZB = 1 OR [TYPE] = 4)
			OR @intSVOD_ZB = 0 AND SB.DEP_LINK = @intDEP_LINK)
		AND (@nOtborKAU = 0
			OR @nOtborKAU > 0 AND EXISTS (SELECT * FROM @T_KAU TTT WHERE TTT.LINK = SB.KAU)
			)	
	GROUP BY
		SA.ACCT_ROOT,
		CASE 
			WHEN @intPRN_KOSGU = 1 THEN ISNULL (SGU, 0)
			ELSE 0
		END, 
		CASE 
			WHEN @intPRN_KBK = 1 THEN ISNULL (KBK, 0)
			ELSE 0
		END,
		ISNULL (SA.JO, 0)
		
--SELECT * FROM @SALDO_BEGIN_PERIOD

	-- END PERIOD --
	SET @OUT_DATE_REST = DATEADD (DAY, 1, @DATE_STOP)

	DECLARE @SALDO_END_PERIOD TABLE
		(
		ACCOUNT [INT],
		SGU [INT],
		KBK [INT],
		KAU	INT,
		JO [INT],
		D_SUMMA [NUMERIC] (28,2),
		K_SUMMA [NUMERIC] (28,2)
		)

	INSERT INTO @SALDO_END_PERIOD
	SELECT
		SA.ACCT_ROOT,
		CASE 
			WHEN @intPRN_KOSGU = 1 THEN ISNULL (SGU, 0)
			ELSE 0
		END, 
		CASE 
			WHEN @intPRN_KBK = 1 THEN ISNULL (KBK, 0)
			ELSE 0
		END,
		NULL,
		ISNULL (SA.JO, 0),
		SUM (D_SUMMA),
		SUM (K_SUMMA)
	FROM dbo.BB_RestSaldoForLedgerByDate1(@OUT_DATE_REST, DEFAULT, 1) SE
	INNER JOIN @TAB_ACCT SA ON (SE.ACCOUNT = SA.ACCOUNT)
	INNER JOIN @TAB_KBK AP ON (AP.LINK_KBK = ISNULL (SE.KBK, 0))
	INNER JOIN @TAB_KOSGU KOSGU ON (KOSGU.LINK = ISNULL (SE.SGU, 0))
	WHERE (@intSVOD_ZB = 1
				AND SE.DEP_LINK IN (SELECT LINK FROM dbo.DEPARTMENTS WHERE ZB = 1 OR [TYPE] = 4)
			OR @intSVOD_ZB = 0 AND SE.DEP_LINK = @intDEP_LINK)
		AND (@nOtborKAU = 0
			OR @nOtborKAU > 0 AND EXISTS (SELECT * FROM @T_KAU TTT WHERE TTT.LINK = SE.KAU)
			)	
	GROUP BY
		SA.ACCT_ROOT,
		CASE 
			WHEN @intPRN_KOSGU = 1 THEN ISNULL (SGU, 0)
			ELSE 0
		END, 
		CASE 
			WHEN @intPRN_KBK = 1 THEN ISNULL (KBK, 0)
			ELSE 0
		END,
		ISNULL (SA.JO, 0)

--select * from @SALDO_END_PERIOD

	-- OBOROTS BY PERIOD --
	DECLARE @OBOROT_PERIOD TABLE
		(
 		ACCOUNT [INT],
		SGU [INT],
		KBK [INT],
		KAU	INT,
		LEDGER_JOURNAL [INT],
		D_SUMMA [NUMERIC] (28,2),
		K_SUMMA [NUMERIC] (28,2)
		)

	INSERT INTO @OBOROT_PERIOD
	SELECT
		SA.ACCT_ROOT,
		CASE 
			WHEN @intPRN_KOSGU = 1 THEN ISNULL (OB.SGU, 0)
			ELSE 0
		END, 
		CASE 
			WHEN @intPRN_KBK = 1 THEN ISNULL (OB.KBK, 0)
			ELSE 0
		END,
		NULL,
		ISNULL (LEDGER_JOURNAL, 0),
		SUM (D_SUMMA),
		SUM (K_SUMMA)
	FROM dbo.BB_RestOborotForLedgerByPeriod1(@DATE_START, @DATE_STOP, 1) OB
	INNER JOIN @TAB_ACCT SA ON (OB.ACCOUNT = SA.ACCOUNT)
	INNER JOIN @TAB_KBK AP ON (AP.LINK_KBK = ISNULL (OB.KBK, 0))
	INNER JOIN @TAB_KOSGU KOSGU ON (KOSGU.LINK = ISNULL (OB.SGU, 0))
	WHERE (@intSVOD_ZB = 1
				AND OB.DEP_LINK IN (SELECT LINK FROM dbo.DEPARTMENTS WHERE ZB = 1 OR [TYPE] = 4)
			OR @intSVOD_ZB = 0 AND OB.DEP_LINK = @intDEP_LINK)
		AND (@nOtborKAU = 0
			OR @nOtborKAU > 0 AND EXISTS (SELECT * FROM @T_KAU TTT WHERE TTT.LINK = OB.KAU)
			)	
	GROUP BY
		SA.ACCT_ROOT,
		CASE 
			WHEN @intPRN_KOSGU = 1 THEN ISNULL (SGU, 0)
			ELSE 0
		END, 
		CASE 
			WHEN @intPRN_KBK = 1 THEN ISNULL (KBK, 0)
			ELSE 0
		END,
		ISNULL (LEDGER_JOURNAL, 0)
--select * from @OBOROT_PERIOD

	-- ОБОРОТЫ С НАЧАЛА ГОДА -- 
	DECLARE @OBOROT_YEAR TABLE
		(
		ACCOUNT [INT],
		SGU [INT],
		KBK [INT],
		KAU	INT,
		LEDGER_JOURNAL [INT],
		D_SUMMA [NUMERIC] (28,2),
		K_SUMMA [NUMERIC] (28,2)
		)

	INSERT INTO @OBOROT_YEAR
	SELECT
		SA.ACCT_ROOT,
		CASE 
			WHEN @intPRN_KOSGU = 1 THEN ISNULL (OB.SGU, 0)
			ELSE 0
		END, 
		CASE 
			WHEN @intPRN_KBK = 1 THEN ISNULL (OB.KBK, 0)
			ELSE 0
		END, 
		NULL,
		ISNULL (LEDGER_JOURNAL, 0),
		SUM (D_SUMMA),
		SUM (K_SUMMA)
	FROM dbo.BB_RestOborotForLedgerByPeriod1(@DATE_BEG_YEAR, @DATE_STOP, 1) OB
	INNER JOIN @TAB_ACCT SA ON (OB.ACCOUNT = SA.ACCOUNT)
	INNER JOIN @TAB_KBK AP ON (AP.LINK_KBK = ISNULL (OB.KBK, 0))
	INNER JOIN @TAB_KOSGU KOSGU ON (KOSGU.LINK = ISNULL (OB.SGU, 0))
	WHERE (@intSVOD_ZB = 1
				AND OB.DEP_LINK IN (SELECT LINK FROM dbo.DEPARTMENTS WHERE ZB = 1 OR [TYPE] = 4)
			OR @intSVOD_ZB = 0 AND OB.DEP_LINK = @intDEP_LINK)
		AND (@nOtborKAU = 0
			OR @nOtborKAU > 0 AND EXISTS (SELECT * FROM @T_KAU TTT WHERE TTT.LINK = OB.KAU)
			)	
	GROUP BY
		SA.ACCT_ROOT,
		CASE 
			WHEN @intPRN_KOSGU = 1 THEN ISNULL (SGU, 0)
			ELSE 0
		END, 
		CASE 
			WHEN @intPRN_KBK = 1 THEN ISNULL (KBK, 0)
			ELSE 0
		END,
		ISNULL (LEDGER_JOURNAL, 0)

	--select * from @OBOROT_YEAR

	DECLARE @ACCOUNT_BOOK TABLE
		(
		ACCOUNT [INT],
		KBK [INT],
		SGU [INT],
		LEDGER_JO [INT])

	INSERT INTO @ACCOUNT_BOOK
	SELECT ACCOUNT, KBK, SGU, JO
	FROM @SALDO_BEGIN_YEAR
	WHERE D_SUMMA <> 0 OR K_SUMMA <> 0 
	UNION
	SELECT ACCOUNT, KBK, SGU, JO
	FROM @SALDO_BEGIN_PERIOD
	WHERE D_SUMMA <> 0 OR K_SUMMA <> 0 
	UNION
	SELECT ACCOUNT, KBK, SGU, LEDGER_JOURNAL
	FROM @OBOROT_PERIOD
	WHERE D_SUMMA <> 0 OR K_SUMMA <> 0 
	UNION
	SELECT ACCOUNT, KBK, SGU, JO
	FROM @SALDO_END_PERIOD
	WHERE D_SUMMA <> 0 OR K_SUMMA <> 0 
	UNION
	SELECT ACCOUNT, KBK, SGU, LEDGER_JOURNAL
	FROM @OBOROT_YEAR
	WHERE D_SUMMA <> 0 OR K_SUMMA <> 0 
--select * from @ACCOUNT_BOOK

	/* --- Итоговые остатки по группе --- */
	/* НАЧАЛО ГОДА */
	DECLARE @SALDO_BEGIN_YEAR_GR TABLE (ACCOUNT [INT],
				D_SUMMA [NUMERIC] (28,2),
				K_SUMMA [NUMERIC] (28,2))

	INSERT INTO @SALDO_BEGIN_YEAR_GR	
	SELECT ACCOUNT,
		SUM (D_SUMMA),
		SUM (K_SUMMA)
	FROM @SALDO_BEGIN_YEAR
	GROUP BY ACCOUNT

	/* НАЧАЛО ПЕРИОДА */
	DECLARE @SALDO_BEGIN_PERIOD_GR TABLE (ACCOUNT [INT],
				D_SUMMA [NUMERIC] (28,2),
				K_SUMMA [NUMERIC] (28,2))

	INSERT INTO @SALDO_BEGIN_PERIOD_GR	
	SELECT ACCOUNT,
		SUM (D_SUMMA),
		SUM (K_SUMMA)
	FROM @SALDO_BEGIN_PERIOD
	GROUP BY ACCOUNT

	/* КОНЕЦ ПЕРИОДА */
	DECLARE @SALDO_END_PERIOD_GR TABLE (ACCOUNT [INT],
				D_SUMMA [NUMERIC] (28,2),
				K_SUMMA [NUMERIC] (28,2))

	INSERT INTO @SALDO_END_PERIOD_GR	
	SELECT ACCOUNT,
		SUM (D_SUMMA),
		SUM (K_SUMMA)
	FROM @SALDO_END_PERIOD
	GROUP BY ACCOUNT
/*
SELECT * FROM @SALDO_BEGIN_YEAR_GR
SELECT * FROM @SALDO_BEGIN_PERIOD_GR
SELECT * FROM @SALDO_END_PERIOD_GR
*/

--SELECT * FROM @ACCOUNT_BOOK

	DECLARE @MAIN_BOOK TABLE (
		[MONTH]	VARCHAR(20),
		ORGNAME	VARCHAR(254),
		OKPO	VARCHAR (20),
		GLBUH	VARCHAR (50),
		UCHR_NAME VARCHAR (254),
		BUDG_NAME VARCHAR (254),
		ACCT_GR	VARCHAR (5),
		ZABALANS TINYINT,
		AC_CODE VARCHAR (20),
		CODE_LONG VARCHAR (60),
		KBK_CODE VARCHAR (30),
		SGU_CODE VARCHAR (3),
		JO_CODE VARCHAR (10),
		BEG_YEAR VARCHAR (10),
		SBYD_SUMMA NUMERIC (28,4),
		SBYK_SUMMA NUMERIC (28,4),
		SBD_SUMMA NUMERIC (28,4),
		SBK_SUMMA NUMERIC (28,4),
		OBD_SUMMA NUMERIC (28,4),
		OBK_SUMMA NUMERIC (28,4),

		YOD_SUM NUMERIC (28,4),
		YOK_SUM NUMERIC (28,4),

		SED_SUMMA NUMERIC (28,4),
		SEK_SUMMA NUMERIC (28,4),

		SBYD_SUM_G NUMERIC (28,4),
		SBYK_SUM_G NUMERIC (28,4),
		SBD_SUM_G NUMERIC (28,4),
		SBK_SUM_G NUMERIC (28,4),
		SED_SUM_G NUMERIC (28,4),
		SEK_SUM_G NUMERIC (28,4),

		[SBYD_SUM_T] NUMERIC (28,4),
		[SBYK_SUM_T] NUMERIC (28,4),
		[SBD_SUM_T] NUMERIC (28,4),
		[SBK_SUM_T] NUMERIC (28,4),
		[SED_SUM_T] NUMERIC (28,4),
		[SEK_SUM_T] NUMERIC (28,4),

		ACSGU_GR1	VARCHAR (30),
		ACSGU_GR2	VARCHAR (30)
		)

--	ORDER BY 1, 2, 3, 4, 5
-- 	MONTH, ORGNAME, ACCT_GR, AC_CODE,

		
	INSERT INTO @MAIN_BOOK
	SELECT @MONTH_NAME AS MONTH,
		@strORGNAME AS ORGNAME,
		@strOKPO AS OKPO,
		@strGLBUH AS GLBUH,
		@UCHR_NAME,
		@BUDG_NAME,
		SA.cSINTH AS ACCT_GR,
		SA.ZABALANS,
		SA.CODE AS AC_CODE,

		dbo.BK_GetAcctFullCode1 (AC.ACCOUNT, AC.KBK, AC.SGU, @intPRN_KBK, @intPRN_KOSGU) AS CODE_LONG,
		ISNULL (KL_KBK.CODE, ''),
		ISNULL (KOSGU.CODE, ''),
		ISNULL (CONVERT (VARCHAR (10), JO.CODE), '') AS JO_CODE,
		CONVERT (VARCHAR (10), @DATE_BEG_YEAR, 104) AS BEG_YEAR,
		ISNULL (REST_BY.D_SUMMA, 0) AS SBYD_SUMMA ,
		ISNULL (REST_BY.K_SUMMA, 0) AS SBYK_SUMMA,
		ISNULL (REST_BP.D_SUMMA, 0) AS SBD_SUMMA,
		ISNULL (REST_BP.K_SUMMA , 0) AS SBK_SUMMA,
		ISNULL (OB.D_SUMMA, 0) AS OBD_SUMMA,
		ISNULL (OB.K_SUMMA, 0) AS OBK_SUMMA,

		ISNULL (OBY.D_SUMMA, 0) AS YOD_SUM,
		ISNULL (OBY.K_SUMMA, 0) AS YOK_SUM,

		ISNULL (REST_EP.D_SUMMA, 0) AS SED_SUMMA ,
		ISNULL (REST_EP.K_SUMMA, 0) AS SEK_SUMMA,

		ISNULL (REST_BY_GR.D_SUMMA, 0) AS SBYD_SUM_G ,
		ISNULL (REST_BY_GR.K_SUMMA, 0) AS SBYK_SUM_G,
		ISNULL (REST_BP_GR.D_SUMMA, 0) AS SBD_SUM_G,
		ISNULL (REST_BP_GR.K_SUMMA , 0) AS SBK_SUM_G,
		ISNULL (REST_EP_GR.D_SUMMA, 0) AS SED_SUM_G,
		ISNULL (REST_EP_GR.K_SUMMA, 0) AS SEK_SUM_G,

		[SBYD_SUM_T] = ISNULL ((SELECT SUM (D_SUMMA) FROM @SALDO_BEGIN_YEAR_GR), 0),
		[SBYK_SUM_T] = ISNULL ((SELECT SUM (K_SUMMA) FROM @SALDO_BEGIN_YEAR_GR), 0),
		[SBD_SUM_T] = ISNULL ((SELECT SUM (D_SUMMA) FROM @SALDO_BEGIN_PERIOD_GR), 0),
		[SBK_SUM_T] = ISNULL ((SELECT SUM (K_SUMMA) FROM @SALDO_BEGIN_PERIOD_GR), 0),
		[SED_SUM_T] = ISNULL ((SELECT SUM (D_SUMMA) FROM @SALDO_END_PERIOD_GR), 0),
		[SEK_SUM_T] = ISNULL ((SELECT SUM (K_SUMMA) FROM @SALDO_END_PERIOD_GR), 0),

		CASE
--			WHEN @intGRP_SGU = 1 AND SA.P_KASSA = 1 AND KOSGU.IS_EKR = 1 THEN RTRIM (SA.CODE) + '.' + LEFT (KOSGU.CODE, 2) + '0'
--			WHEN @intGRP_SGU = 1 AND SA.P_KASSA = 1 THEN RTRIM (SA.CODE) + '.' + ISNULL (LEFT (KOSGU.CODE, 2) + '0', '000')
			WHEN @intGRP_SGU = 1 THEN RTRIM (SA.CODE) + '.' + ISNULL (LEFT (KOSGU.CODE, 2) + '0', '000')
			ELSE ''
		END, 
		CASE
--			WHEN @intGRP_SGU = 1 AND SA.P_KASSA = 1 AND KOSGU.IS_EKR = 1 THEN RTRIM (SA.CODE) + '.' + LEFT (KOSGU.CODE, 1) + '00'
--			WHEN @intGRP_SGU = 1 AND SA.P_KASSA = 1 THEN RTRIM (SA.CODE) + '.' + ISNULL (LEFT (KOSGU.CODE, 1) + '00', '000')
			WHEN @intGRP_SGU = 1 THEN RTRIM (SA.CODE) + '.' + ISNULL (LEFT (KOSGU.CODE, 1) + '00', '000')
			ELSE ''
		END
	FROM @ACCOUNT_BOOK AC
	LEFT OUTER JOIN @SALDO_BEGIN_YEAR REST_BY ON (REST_BY.ACCOUNT = AC.ACCOUNT
			AND REST_BY.KBK = AC.KBK
			AND REST_BY.SGU = AC.SGU
			AND REST_BY.JO = AC.LEDGER_JO)
	LEFT OUTER JOIN @SALDO_BEGIN_PERIOD REST_BP ON (REST_BP.ACCOUNT = AC.ACCOUNT
			AND REST_BP.KBK = AC.KBK
			AND REST_BP.SGU = AC.SGU
			AND REST_BP.JO = AC.LEDGER_JO)
	LEFT OUTER JOIN @OBOROT_PERIOD OB ON (OB.ACCOUNT = AC.ACCOUNT
			AND OB.KBK = AC.KBK
			AND OB.SGU = AC.SGU
			AND OB.LEDGER_JOURNAL = AC.LEDGER_JO)
	LEFT OUTER JOIN @SALDO_END_PERIOD REST_EP ON (REST_EP.ACCOUNT = AC.ACCOUNT
			AND REST_EP.KBK = AC.KBK
			AND REST_EP.SGU = AC.SGU
			AND REST_EP.JO = AC.LEDGER_JO)
	LEFT OUTER JOIN @OBOROT_YEAR OBY ON (OBY.ACCOUNT = AC.ACCOUNT
			AND OBY.KBK = AC.KBK
			AND OBY.SGU = AC.SGU
			AND OBY.LEDGER_JOURNAL = AC.LEDGER_JO)
	LEFT OUTER JOIN @SALDO_BEGIN_YEAR_GR REST_BY_GR ON (REST_BY_GR.ACCOUNT = AC.ACCOUNT)
	LEFT OUTER JOIN @SALDO_BEGIN_PERIOD_GR REST_BP_GR ON (REST_BP_GR.ACCOUNT = AC.ACCOUNT)
	LEFT OUTER JOIN @SALDO_END_PERIOD_GR REST_EP_GR ON (REST_EP_GR.ACCOUNT = AC.ACCOUNT)

	INNER JOIN dbo.S_ACCOUNTS SA ON SA.LINK = AC.ACCOUNT
	LEFT JOIN dbo.KL_KBK ON KL_KBK.LINK=AC.KBK

	LEFT JOIN dbo.KOSGU ON KOSGU.LINK=AC.SGU
	LEFT JOIN dbo.JOURNAL_OPERATION JO ON JO.LINK=AC.LEDGER_JO
--	ORDER BY 1, 2, 3, 4, 5


	IF @intACCT_GR = 1
		IF @intGRP_SGU = 1
			SELECT *
			FROM @MAIN_BOOK ORDER BY ORGNAME, [MONTH], ZABALANS, ACCT_GR, AC_CODE, SGU_CODE, KBK_CODE
		ELSE
			SELECT *
			FROM @MAIN_BOOK ORDER BY ORGNAME, [MONTH], ZABALANS, ACCT_GR, AC_CODE, KBK_CODE, SGU_CODE
	ELSE
		IF @intGRP_SGU = 1
			SELECT *
			FROM @MAIN_BOOK ORDER BY ORGNAME, [MONTH], ZABALANS, AC_CODE, SGU_CODE, KBK_CODE
		ELSE
			SELECT *
			FROM @MAIN_BOOK ORDER BY ORGNAME, [MONTH], ZABALANS, AC_CODE, KBK_CODE, SGU_CODE

-- EXECUTE KIR_EXEC_QUERY 40039,'''20060101'',''20081231'',0,1,0,0,1,1,0,0,1,40905'
/*
SELECT *,
	CONVERT (VARCHAR (26), REPLACE (CODE_LONG, '.', '')) AS SCHET,
	CONVERT (NUMERIC (15), SBYD_SUMMA * 100) AS OST_NG_D,
	CONVERT (NUMERIC (15), SBYK_SUMMA * 100) AS OST_NG_K,
	CONVERT (NUMERIC (15), SBD_SUMMA * 100) AS OST_NM_D,
	CONVERT (NUMERIC (15), SBK_SUMMA * 100) AS OST_NM_K
FROM @MAIN_BOOK ORDER BY ORGNAME, [MONTH], ZABALANS, AC_CODE, KBK_CODE, SGU_CODE
*/
END





GO


GRANT EXECUTE ON dbo.[BK_REPORT_BOOK_MAIN] TO PUBLIC

GO



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

GO

CREATE PROCEDURE DBO.SA_TABESL_EMPL_FILL_BUFFER (@BUFFERCODE VARCHAR(10), @LINK INT, @LINK_SOVM INT = -1, @OSN TINYINT = 0)
/*
СОХРАНЕНИЯ СПИСКА СОТРУДНИКОВ В ТАБЕЛЬ ИЗ БУФФЕРА
*/
AS
--@LINK_SOVM  = -1, ЕСЛИ ДОБАВЛЕНИЕ ВСЕГО ДЛЯ СОТРУДНИКА
-- >= 0, ЕЛСИ ЗАПОЛНИТЬ ЗАНОВО ДЛЯ СОТРУДНИКА
DECLARE @VARKSERROR	TINYINT,
			@VARKSSQLERROR	INT,
			@VARKSSTRVALUE	VARCHAR(7000),
			@VARKSTRANCOUNT	INT

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

SET @LINK_SOVM = COALESCE(@LINK_SOVM,-1)

DELETE FROM DBO.BUFFER
WHERE 
		@LINK_SOVM = -1
	AND
		RTRIM(LTRIM(ID)) = RTRIM(LTRIM(@BUFFERCODE))
	AND 
		EXISTS (SELECT * FROM DBO.TABELS S WHERE S.LINK_DOC = @LINK AND S.LINK_EMPL = DBO.BUFFER.LINK)
		
----------------		
CREATE TABLE #LOCAL_BUFFER(LINK INT)		
CREATE INDEX #LOCAL_BUFFER_LINK ON #LOCAL_BUFFER (LINK ASC)

INSERT INTO #LOCAL_BUFFER (LINK)
SELECT B.LINK FROM DBO.BUFFER B WHERE RTRIM(LTRIM(B.ID)) = RTRIM(LTRIM(@BUFFERCODE))

---------------
DECLARE @PERIOD DATETIME, @COMMENT VARCHAR(254), @DEP_LINK INT
SELECT TOP 1 @PERIOD = DATE_CALC, @COMMENT = COMMENTARY, @DEP_LINK = LINK_DEP FROM SDOC WHERE LINK = @LINK

INSERT INTO TABELS WITH (ROWLOCK) (LINK_EMPL, LINK_DOC, PERIOD)
SELECT LINK, @LINK, @PERIOD 
FROM #LOCAL_BUFFER B 
WHERE NOT EXISTS (SELECT * FROM DBO.TABELS T WHERE T.LINK_DOC = @LINK AND T.LINK_EMPL = B.LINK)

--СОЗДАТЬ АВТОКОММЕНТАРИЙ
IF LTRIM(RTRIM(COALESCE(@COMMENT,''))) = '' BEGIN
	DECLARE @CUR1 CURSOR, @FIO VARCHAR(100)
	SET @CUR1 = CURSOR FORWARD_ONLY

	FOR SELECT TOP 10 FIO
		FROM DBO.TABELS T INNER JOIN DBO.SD_EMPL E ON E.LINK = T.LINK_EMPL
		WHERE T.LINK_DOC = @LINK

	OPEN @CUR1
	FETCH NEXT FROM @CUR1 INTO @FIO
	WHILE (@@FETCH_STATUS <> -1)
	BEGIN
		IF (@@FETCH_STATUS <> -2)
		BEGIN
			SET @COMMENT = LTRIM(RTRIM(@COMMENT)) + 
						CASE WHEN LEN(LTRIM(RTRIM(@COMMENT)) + (CASE WHEN LTRIM(RTRIM(@COMMENT)) <> '' THEN ',' ELSE '' END) + LTRIM(RTRIM(@FIO))) < 70
							THEN (CASE WHEN LTRIM(RTRIM(@COMMENT)) <> '' THEN ',' ELSE '' END) + LTRIM(RTRIM(@FIO))
							ELSE CASE WHEN RIGHT(LTRIM(RTRIM(@COMMENT)),5) <> 'И ДР.'
								THEN 
								', И ДР.'
								ELSE ''
								END
						END
		END
		FETCH NEXT FROM @CUR1 INTO @FIO
	END

	CLOSE @CUR1
	DEALLOCATE @CUR1

	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

	UPDATE DBO.SDOC SET COMMENTARY = @UNAME + 'Табель:' + @COMMENT WHERE LINK = @LINK
END

--ФОРМИРОВАНИЕ ТАБЕЛЯ

DECLARE @M INT, @Y INT
SELECT @M = MONTH(@PERIOD), @Y = YEAR(@PERIOD)


CREATE TABLE #EMPL_DAYS (LINK_EMPL INT, LINK_WORK INT, LINK_WORK_TYPE INT, DATE1 DATETIME, [DAY] TINYINT, HOURS NUMERIC(5,2), DAY_TIP INT,
			 LINK_UP INT, SYMB VARCHAR(4), [NAME] VARCHAR(60), DOP_TAB TINYINT, DATEACCEPT DATETIME, DATESACK DATETIME, GRAPH_LINK INT, ETS_RAZR TINYINT)
INSERT INTO #EMPL_DAYS
EXEC DBO.SA_TABEL_FILL_EMPL @Y, @M, @LINK, @DEP_LINK, @BUFFERCODE

---СВЕДЕНИЯ О НЕЯВКАХ
CREATE TABLE #NEYAVKI (LINK_EMPL INT, [DAY] TINYINT, DAY_TIP INT, SYMB VARCHAR(4))
INSERT INTO #NEYAVKI (LINK_EMPL, [DAY], DAY_TIP, SYMB)
SELECT D.LINK_EMPL, D.[DAY], D.DAY_TIP, D.SYMB --MAX(D.DAY_TIP), MAX(D.SYMB)
FROM #EMPL_DAYS D INNER JOIN DBO.TYP_DAYS T ON T.WORK_D <> 1 AND T.LINK = D.DAY_TIP
WHERE D.DOP_TAB = 1 AND D.LINK_WORK_TYPE = (SELECT TOP 1 LINK FROM DBO.TABEL_NASTR2 WHERE CODE = 'ОСН')

---
CREATE INDEX #NEYAVKI_LINK_EMPL ON #NEYAVKI (LINK_EMPL ASC)

DELETE FROM DBO.TABELS_N
WHERE LINK_UP IN (SELECT DISTINCT T.LINK FROM DBO.TABELS T INNER JOIN #LOCAL_BUFFER B ON T.LINK_EMPL = B.LINK WHERE T.LINK_DOC = @LINK)

--ЗАПИСАТЬ ВСЕ НЕЯВКИ
INSERT INTO DBO.TABELS_N
(LINK_UP,D1,D2,D3,D4,D5,D6,D7,D8,D9,D10,D11,D12,D13,D14,D15,D16,D17,D18,D19,D20,D21,D22,D23,D24,D25,D26,D27,D28,D29,D30,D31)
SELECT DISTINCT LINK,
	D1 = D1.DAY_TIP,
	D2 = D2.DAY_TIP,
	D3 = D3.DAY_TIP,
	D4 = D4.DAY_TIP,
	D5 = D5.DAY_TIP,
	D6 = D6.DAY_TIP,
	D7 = D7.DAY_TIP,
	D8 = D8.DAY_TIP,
	D9 = D9.DAY_TIP,
	D10 = D10.DAY_TIP,
	D11 = D11.DAY_TIP,
	D12 = D12.DAY_TIP,
	D13 = D13.DAY_TIP,
	D14 = D14.DAY_TIP,
	D15 = D15.DAY_TIP,
	D16 = D16.DAY_TIP,
	D17 = D17.DAY_TIP,
	D18 = D18.DAY_TIP,
	D19 = D19.DAY_TIP,
	D20 = D20.DAY_TIP,
	D21 = D21.DAY_TIP,
	D22 = D22.DAY_TIP,
	D23 = D23.DAY_TIP,
	D24 = D24.DAY_TIP,
	D25 = D25.DAY_TIP,
	D26 = D26.DAY_TIP,
	D27 = D27.DAY_TIP,
	D28 = D28.DAY_TIP,
	D29 = D29.DAY_TIP,
	D30 = D30.DAY_TIP,
	D31 = D31.DAY_TIP
FROM DBO.TABELS E
	LEFT JOIN #NEYAVKI D1 ON D1.DAY = 1 AND E.LINK_EMPL = D1.LINK_EMPL
	LEFT JOIN #NEYAVKI D2 ON D2.DAY = 2 AND E.LINK_EMPL = D2.LINK_EMPL
	LEFT JOIN #NEYAVKI D3 ON D3.DAY = 3 AND E.LINK_EMPL = D3.LINK_EMPL
	LEFT JOIN #NEYAVKI D4 ON D4.DAY = 4 AND E.LINK_EMPL = D4.LINK_EMPL
	LEFT JOIN #NEYAVKI D5 ON D5.DAY = 5 AND E.LINK_EMPL = D5.LINK_EMPL
	LEFT JOIN #NEYAVKI D6 ON D6.DAY = 6 AND E.LINK_EMPL = D6.LINK_EMPL
	LEFT JOIN #NEYAVKI D7 ON D7.DAY = 7 AND E.LINK_EMPL = D7.LINK_EMPL
	LEFT JOIN #NEYAVKI D8 ON D8.DAY = 8 AND E.LINK_EMPL = D8.LINK_EMPL
	LEFT JOIN #NEYAVKI D9 ON D9.DAY = 9 AND E.LINK_EMPL = D9.LINK_EMPL
	LEFT JOIN #NEYAVKI D10 ON D10.DAY = 10 AND E.LINK_EMPL = D10.LINK_EMPL
	LEFT JOIN #NEYAVKI D11 ON D11.DAY = 11 AND E.LINK_EMPL = D11.LINK_EMPL
	LEFT JOIN #NEYAVKI D12 ON D12.DAY = 12 AND E.LINK_EMPL = D12.LINK_EMPL
	LEFT JOIN #NEYAVKI D13 ON D13.DAY = 13 AND E.LINK_EMPL = D13.LINK_EMPL
	LEFT JOIN #NEYAVKI D14 ON D14.DAY = 14 AND E.LINK_EMPL = D14.LINK_EMPL
	LEFT JOIN #NEYAVKI D15 ON D15.DAY = 15 AND E.LINK_EMPL = D15.LINK_EMPL
	LEFT JOIN #NEYAVKI D16 ON D16.DAY = 16 AND E.LINK_EMPL = D16.LINK_EMPL
	LEFT JOIN #NEYAVKI D17 ON D17.DAY = 17 AND E.LINK_EMPL = D17.LINK_EMPL
	LEFT JOIN #NEYAVKI D18 ON D18.DAY = 18 AND E.LINK_EMPL = D18.LINK_EMPL
	LEFT JOIN #NEYAVKI D19 ON D19.DAY = 19 AND E.LINK_EMPL = D19.LINK_EMPL
	LEFT JOIN #NEYAVKI D20 ON D20.DAY = 20 AND E.LINK_EMPL = D20.LINK_EMPL
	LEFT JOIN #NEYAVKI D21 ON D21.DAY = 21 AND E.LINK_EMPL = D21.LINK_EMPL
	LEFT JOIN #NEYAVKI D22 ON D22.DAY = 22 AND E.LINK_EMPL = D22.LINK_EMPL
	LEFT JOIN #NEYAVKI D23 ON D23.DAY = 23 AND E.LINK_EMPL = D23.LINK_EMPL
	LEFT JOIN #NEYAVKI D24 ON D24.DAY = 24 AND E.LINK_EMPL = D24.LINK_EMPL
	LEFT JOIN #NEYAVKI D25 ON D25.DAY = 25 AND E.LINK_EMPL = D25.LINK_EMPL
	LEFT JOIN #NEYAVKI D26 ON D26.DAY = 26 AND E.LINK_EMPL = D26.LINK_EMPL
	LEFT JOIN #NEYAVKI D27 ON D27.DAY = 27 AND E.LINK_EMPL = D27.LINK_EMPL
	LEFT JOIN #NEYAVKI D28 ON D28.DAY = 28 AND E.LINK_EMPL = D28.LINK_EMPL
	LEFT JOIN #NEYAVKI D29 ON D29.DAY = 29 AND E.LINK_EMPL = D29.LINK_EMPL
	LEFT JOIN #NEYAVKI D30 ON D30.DAY = 30 AND E.LINK_EMPL = D30.LINK_EMPL
	LEFT JOIN #NEYAVKI D31 ON D31.DAY = 31 AND E.LINK_EMPL = D31.LINK_EMPL
WHERE
	LINK_DOC = @LINK
	AND
	NOT EXISTS (SELECT * FROM DBO.TABELS_N N WHERE N.LINK_UP = E.LINK)

---
DROP TABLE #NEYAVKI

---СВЕДЕНИЯ ОБ ОТРАБОТАННОМ ВРЕМЕНИ
CREATE TABLE #WORK (LINK_EMPL INT, LINK_WORK INT, LINK_WORK_TYPE INT, [DAY] TINYINT, HOURS NUMERIC(5,2), DAY_TIP INT, DATEACCEPT DATETIME, DATESACK DATETIME, GRAPH_LINK INT, ETS_RAZR TINYINT)
INSERT INTO #WORK (LINK_EMPL, LINK_WORK, LINK_WORK_TYPE, [DAY], HOURS, DAY_TIP, DATEACCEPT, DATESACK, GRAPH_LINK, ETS_RAZR)
SELECT D.LINK_EMPL, LINK_WORK, LINK_WORK_TYPE, D.[DAY], D.HOURS, D.DAY_TIP, DATEACCEPT, DATESACK, GRAPH_LINK, ETS_RAZR
FROM #EMPL_DAYS D INNER JOIN DBO.TYP_DAYS T ON T.WORK_D = 1 AND T.LINK = D.DAY_TIP
---
CREATE INDEX #WORK_LINK_EMPL ON #WORK (LINK_EMPL ASC)

---ОБЕСПЕЧИМ НАЛИЧИЕ ВСЕХ ЧИСЕЛ МЕСЯЦА
DECLARE @I INT
SET @I = 1
WHILE @I <= 31 BEGIN
	INSERT INTO #WORK (LINK_EMPL, [DAY], HOURS, DAY_TIP)
	VALUES (0, @I, 0, 0)
	SET @I = @I + 1
END

--
DECLARE @VARKSTABLE VARCHAR(100)
EXEC X_GET_TABLE_NAME @VARKSTABLE OUTPUT

EXEC DBO.CROSSTAB @TABLE = #WORK, @TABLE2 = @VARKSTABLE, @ONROWS = 'LINK_EMPL,DAY_TIP,LINK_WORK,LINK_WORK_TYPE', @ONCOLS = DAY, @SUMCOL = HOURS

CREATE TABLE #WORK1 (LINK_EMPL INT, LINK_WORK INT, LINK_WORK_TYPE INT, DAY_TIP INT, C1 NUMERIC(5,2), C10 NUMERIC(5,2), C11 NUMERIC(5,2), C12 NUMERIC(5,2), C13 NUMERIC(5,2), C14 NUMERIC(5,2), C15 NUMERIC(5,2), C16 NUMERIC(5,2), C17 NUMERIC(5,2), C18 NUMERIC(5,2), C19 NUMERIC(5,2), C2 NUMERIC(5,2), C20 NUMERIC(5,2), C21 NUMERIC(5,2), C22 NUMERIC(5,2), C23 NUMERIC(5,2), C24 NUMERIC(5,2), C25 NUMERIC(5,2), C26 NUMERIC(5,2), C27 NUMERIC(5,2), C28 NUMERIC(5,2), C29 NUMERIC(5,2), C3 NUMERIC(5,2), C30 NUMERIC(5,2), C31 NUMERIC(5,2), C4 NUMERIC(5,2), C5 NUMERIC(5,2), C6 NUMERIC(5,2), C7 NUMERIC(5,2), C8 NUMERIC(5,2), C9  NUMERIC(5,2))

EXEC ( '
INSERT INTO #WORK1 (LINK_EMPL,LINK_WORK,LINK_WORK_TYPE,DAY_TIP,C1,C10,C11,C12,C13,C14,C15,C16,C17,C18,C19,C2,C20,C21,C22,C23,C24,C25,C26,C27,C28,C29,C3,C30,C31,C4,C5,C6,C7,C8,C9)
SELECT LINK_EMPL,LINK_WORK,LINK_WORK_TYPE,DAY_TIP,C1,C10,C11,C12,C13,C14,C15,C16,C17,C18,C19,C2,C20,C21,C22,C23,C24,C25,C26,C27,C28,C29,C3,C30,C31,C4,C5,C6,C7,C8,C9
FROM ' + @VARKSTABLE  + ' WHERE LINK_EMPL > 0')

EXEC ('DROP TABLE ' + @VARKSTABLE)

--
DELETE FROM DBO.TABELS_W 
WHERE LINK_UP IN (SELECT DISTINCT T.LINK FROM DBO.TABELS T INNER JOIN #LOCAL_BUFFER B ON T.LINK_EMPL = B.LINK WHERE T.LINK_DOC = @LINK)
	AND (@LINK_SOVM = COALESCE(LINK_SOVM,0) OR @LINK_SOVM = -2)
	AND (
			@OSN = 0 -- при массовом полном формировании
			OR 
			@OSN = 1 -- только при переформировании по одному сотруднику при утверждении приказа или больничного
			AND (
				--Виды дней из графика
				EXISTS (	-- Данный тип дня существует в графике
							SELECT *
							FROM 
								DBO.EMPL E
								INNER JOIN DBO.GRAPH G ON E.GRAPH_LINK = G.LINK
								INNER JOIN dbo.GRAPH_VID V ON V.LINK = G.VID_LINK
								INNER JOIN dbo.GRAPH_VID_TABLE T ON T.LINK_UP = V.LINK
								INNER JOIN #LOCAL_BUFFER B ON B.LINK = E.LINK
							WHERE
								T.TYPE_DAY = LINK_DAY	
						)
				OR --Исключение: Данный тип дня существует в справочнике празников как предпраздничный
					EXISTS ( SELECT * FROM dbo.HOLIDAYS H WHERE H.TYPE_HOL = 2 AND H.TD_LINK = LINK_DAY AND h.YEAR = year(@PERIOD) )				
				OR --Исключение: Данный тип дня командировка как вид явки. (заполняется из приказа)
					EXISTS ( SELECT * FROM dbo.KD_TYP_DAYS T WHERE T.WORK_D = 1 AND T.TYP_YAVKA = 7 AND T.LINK = LINK_DAY )					
				)

		)

--ЗАПИСАТЬ ВСЕ ЯВКИ
INSERT INTO DBO.TABELS_W (LINK_UP,LINK_SOVM,LINK_DAY,
	D1,D2,D3,D4,D5,D6,D7,D8,D9,D10,D11,D12,D13,D14,D15,D16,D17,D18,D19,D20,D21,D22,D23,D24,D25,D26,D27,D28,D29,D30,D31)
SELECT DISTINCT T.LINK, (CASE WHEN COALESCE(W1.LINK_WORK,0) = 0 THEN NULL ELSE W1.LINK_WORK END), W1.DAY_TIP,
	W1.C1, W1.C2, W1.C3, W1.C4, W1.C5, W1.C6, W1.C7, W1.C8, W1.C9, W1.C10,
	W1.C11, W1.C12, W1.C13, W1.C14, W1.C15, W1.C16, W1.C17, W1.C18, W1.C19, W1.C20,
	W1.C21, W1.C22, W1.C23, W1.C24, W1.C25, W1.C26, W1.C27, W1.C28, W1.C29, W1.C30, W1.C31
FROM 
	DBO.TABELS T LEFT JOIN #WORK1 W1 ON T.LINK_EMPL = W1.LINK_EMPL
WHERE
	T.LINK_DOC = @LINK
	AND
	W1.DAY_TIP IS NOT NULL
	AND
	(@LINK_SOVM <= -1 AND NOT EXISTS (SELECT DISTINCT LINK_UP FROM DBO.TABELS_W W2 WHERE W2.LINK_UP = T.LINK AND W2.LINK_DAY = W1.DAY_TIP) OR @LINK_SOVM >= 0 AND COALESCE(W1.LINK_WORK,0) = @LINK_SOVM )
	
--Запись события
DECLARE @ADD_TEXT VARCHAR(200), @LINK_EMPL INT

IF @LINK_SOVM <> -1
BEGIN

	SELECT TOP 1 @LINK_EMPL = B.LINK FROM #LOCAL_BUFFER B

	SELECT TOP 1 @ADD_TEXT = LEFT( 'автозаполнение по Т/Н ' + RTRIM(WE.TAB) + ' '
		+ RTRIM(WE.FIO) + ', ' + RTRIM(WE.code_type) + ', ' + RTRIM(WE.post_name), 200)
	FROM dbo.TABELS T 
		INNER JOIN [dbo].[SA_EMPLS_W_FN](@LINK_EMPL,@PERIOD,DEFAULT,@DEP_LINK) WE ON T.LINK_EMPL = WE.LINK_EMPL
	WHERE 
		T.LINK_DOC = @LINK AND WE.LINK = @LINK_SOVM
END		

EXEC dbo.SA_DO_EVENT @LINK, 'Автозаполненение', @ADD_TEXT	

WHILE @@TRANCOUNT > @VARKSTRANCOUNT
	COMMIT TRAN


	
RETURN 0




GO


GRANT EXECUTE ON dbo.[SA_TABESL_EMPL_FILL_BUFFER] TO PUBLIC

GO



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

GO


CREATE PROCEDURE dbo.RSA_RSV_1_15_PFR_PREPARE
	@Res float output, @varcStr varchar(250), @vardBegin datetime = '20150101', @vardEnd datetime = '20151231', @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,
	1,---инвалидов не выделяем 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 ,
	1,---инвалидов не выделяем dbo.is_invalid(GT.PERS_LINK,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,G.[MONTH],@nYEAR))),
	F.ENVD
	
FROM
	DOCUMENTS_DGH G INNER JOIN DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
	inner join PERSON P on GT.PERS_LINK = P.link
	inner join dbo.SAL_SFIN F on F.LINK = GT.LINK_VKR
WHERE
	FLAG_JC = 1
	AND GT.WAY_CALC  not in (5)
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3
	AND LINK_DEP = @DEP_LINK


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


CREATE TABLE #RES2(CODE_STR VARCHAR(10), C1 NUMERIC(18,2), C2 NUMERIC(18,2),  C3 NUMERIC(18,2), C4 NUMERIC(18,2), C5 NUMERIC(18,2), C6 NUMERIC(18,2), C7 NUMERIC(18,2), C8 NUMERIC(18,2))
/*
для заполнения показателя "количество застрахованных лиц", указывается количество застрахованных лиц,
за которых должны быть представлены сведения индивидуального (персонифицированного) учета за отчетный период.
*/

declare @EndYear datetime
Set @EndYear = dbo.DateEndOfYear(@START_DATE)

DECLARE @C1_PERIOD_BEG DATETIME, @C1_PERIOD_END DATETIME

SELECT @C1_PERIOD_BEG = @START_DATE,
	   @C1_PERIOD_END = @END_DATE
		
--------------
DECLARE @BDate datetime, @EndDate datetime, @EDate datetime, @NAvgCount int
SELECT @NAvgCount = COUNT(pers_link)
FROM
(
	SELECT DISTINCT E.pers_link
	FROM
		dbo.EMPL E inner join dbo.ITEM_MOVE P on E.link = P.empl_link and P.NEW_FACE = 1 AND P.ACTIVE=1
		left join dbo.ITEM_DIS_FACE U on E.link = U.empl_link AND U.ACTIVE=1
	WHERE
		P.DATE_BEGIN <= @C1_PERIOD_END
		and
		coalesce(U.DIS_DATE,'20990101') >= @C1_PERIOD_BEG
		And
		E.DEP_LINK = @DEP_LINK
	UNION
	Select DISTINCT
		DFG.link
	FROM PERSON DFG inner join SALARY_REESTR_DGH DGH on DFG.link = DGH.PERS_LINK
	WHERE
		DGH.DATE1 = (
			Select max(DATE1)  from SALARY_REESTR_DGH as DGH0
					where DGH.PERS_LINK = DGH0.PERS_LINK AND DGH0.DEP_LINK = DGH.DEP_LINK
						AND
						(
							ISNULL(DATE1, '19000101') between  @C1_PERIOD_BEG and @C1_PERIOD_END
							or ISNULL(DATE2, '20990101') between @C1_PERIOD_BEG and @C1_PERIOD_END
						)
					)
		And
		DGH.DEP_LINK = @DEP_LINK
) AS T		


--
INSERT INTO #RES2(CODE_STR, C1)
SELECT '1', ISNULL(@NAvgCount,0)



/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/
SELECT @BDate = @START_DATE, @EndDate = @END_DATE
SET @EDate = dateadd(year,1,convert(varchar, YEAR(@BDate))+'0101')

/* Среднесписочная численность мужчин и женщин */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 0, DEFAULT))
--
UPDATE #RES2 SET C2 = ISNULL(@NAvgCount,0) WHERE CODE_STR = '1'
--Раздел 2. Расчет страховых взносов по тарифу, установленному для плательщика страховых взносов
Declare @StBase2 table (link int)
Insert into @StBase2 (link)
select distinct link_pays from tax_ref where link_tax = (select top 1 link from pays where object = 3 and way_calc = 6)


--Фактическая база для договорников
SELECT
	GT.PERS_LINK, MONTH(G.[DATE]) AS MONTH_BASE, F.ENVD, SUMMA_BASE = sum(GT.SUMMA_BASE)
INTO #DGH_FAKT_BASE
FROM
	dbo.DOCUMENTS_DGH G INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
	INNER JOIN dbo.SAL_SFIN F on F.LINK = GT.LINK_VKR
WHERE
	FLAG_JC = 1
	AND GT.WAY_CALC  = 6
	AND YEAR(G.[DATE]) = @nYEAR
	AND MONTH(G.[DATE]) <= @nMONTH3
	AND LINK_DEP = @DEP_LINK
GROUP BY
	GT.PERS_LINK, MONTH(G.[DATE]), F.ENVD

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

DECLARE @LINK_EKR213 INT
SET @LINK_EKR213 = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '213')

DECLARE @ESN_213 INT --Начислять страховые взносы на доходы с 213 ЭКР
SET @ESN_213 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_5')

------
CREATE TABLE #CALCULATE_JURNAL (LINK_PAYS INT, PERIOD_BEGIN DATETIME, LINK_DOC INT, PERS_LINK INT, LINK_VKR INT, LINK_EKR INT, LINK_EMPL INT, SUMMA NUMERIC(18,2), WAY_CALC TINYINT , SPECO int)
INSERT INTO #CALCULATE_JURNAL (LINK_PAYS, PERIOD_BEGIN, LINK_DOC, PERS_LINK, LINK_VKR, LINK_EKR, LINK_EMPL, SUMMA,way_calc , SPECO)
SELECT CJ.LINK_PAYS, CJ.PERIOD_BEGIN, CJ.LINK_DOC, CJ.PERS_LINK, CJ.LINK_VKR, cj.LINK_EKR, CJ.LINK_EMPL, SUMMA = SUM(CJ.SUMMA), p.way_calc , SPECO
FROM dbo.CALCULATE_JURNAL CJ INNER JOIN dbo.PAYS P ON  CJ.LINK_PAYS = p.link
WHERE
	Year(period_begin) = @nYEAR
	and Month(period_begin) <= @nMONTH3
	and CJ.LINK_DEP = @DEP_LINK
GROUP BY
	cj.LINK_PAYS, cj.PERIOD_BEGIN, cj.LINK_DOC, cj.PERS_LINK, cj.LINK_VKR, cj.LINK_EKR, cj.LINK_EMPL, P.WAY_CALC,cj.SPECO


------	у кого была инвалидность в заданном периоде
CREATE TABLE #PERS_INV (PERS_LINK INT)
--SELECT DISTINCT PERS_LINK
--INTO #PERS_INV
--FROM dbo.PERS_INVALID I
--WHERE COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate

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


--Заготовка для #SALARY_SUM2
CREATE TABLE #SALARY_SUM_DATA (PERS_LINK INT, PERIOD_BEGIN DATETIME, SUMMA_ALL NUMERIC(18,2), SUMMA_NO NUMERIC(18,2), SUMMA_ALL_I NUMERIC(18,2), SUMMA_NO_I NUMERIC(18,2), SUMMA_ALL_E NUMERIC(18,2), SUMMA_NO_E NUMERIC(18,2), INV TINYINT
		/*,SUMMA_ALL_D1 NUMERIC(18,2)*/, SUMMA_NO_D1 NUMERIC(18,2)/*, SUMMA_ALL_D2 NUMERIC(18,2)*/, SUMMA_NO_D2 NUMERIC(18,2),
	SUM_NO_D1_O4 NUMERIC(18,2) ,SUM_NO_D1_B34 NUMERIC(18,2) ,SUM_NO_D1_B33 NUMERIC(18,2),SUM_NO_D1_B32 NUMERIC(18,2), SUM_NO_D1_B31 NUMERIC(18,2),
		SUM_NO_D2_O4 NUMERIC(18,2) ,SUM_NO_D2_B34 NUMERIC(18,2) ,SUM_NO_D2_B33 NUMERIC(18,2),SUM_NO_D2_B32 NUMERIC(18,2), SUM_NO_D2_B31 NUMERIC(18,2)
		)
--Сотрудники
INSERT INTO #SALARY_SUM_DATA (PERS_LINK, PERIOD_BEGIN, SUMMA_ALL, SUMMA_NO, SUMMA_ALL_I, SUMMA_NO_I, SUMMA_ALL_E, SUMMA_NO_E, INV
		/*,SUMMA_ALL_D1*/, SUMMA_NO_D1/*, SUMMA_ALL_D2*/, SUMMA_NO_D2,SUM_NO_D1_O4,SUM_NO_D1_B34,SUM_NO_D1_B33, SUM_NO_D1_B32, SUM_NO_D1_B31,
		SUM_NO_D2_O4,SUM_NO_D2_B34,SUM_NO_D2_B33, SUM_NO_D2_B32, SUM_NO_D2_B31
	)
select
	E.PERS_LINK,
	CJ.PERIOD_BEGIN,
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(CASE WHEN B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0 THEN SUMMA ELSE 0 END), --на которые не начисляются страховые взносы
	SUMMA_ALL_I = 0,
	SUMMA_NO_I = 0,
	SUMMA_ALL_E = SUM(CASE WHEN F.ENVD = 1 THEN SUMMA ELSE 0 END),
	SUMMA_NO_E = SUM(CASE WHEN F.ENVD = 1 AND (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) THEN SUMMA ELSE 0 END),
	INV = CASE WHEN I.PERS_LINK IS NULL THEN 0 ELSE 1 END,

	--SUMMA_ALL_D1 = SUM(CASE WHEN CJ.way_calc = 10 then  SUMMA ELSE 0 end ),
	SUMMA_NO_D1 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and ED.DOP = 1 AND isnull(SPO,'') ='' THEN SUMMA ELSE 0 END),

	----SUMMA_ALL_D2 = SUM(CASE WHEN CJ.way_calc = 11 then  SUMMA ELSE 0 end ),
	SUMMA_NO_D2 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and ED.DOP = 2 and  isnull(SPO,'') ='' THEN SUMMA ELSE 0 END),
	SUM_NO_D1_O4 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='О4'  THEN SUMMA ELSE 0 END),
	SUM_NO_D1_B34 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.4' THEN SUMMA ELSE 0 END),
	SUM_NO_D1_B33 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.3' THEN SUMMA ELSE 0 END),
	SUM_NO_D1_B32 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.2' THEN SUMMA ELSE 0 END),
	SUM_NO_D1_B31 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.1' THEN SUMMA ELSE 0 END),	
	SUM_NO_D2_O4 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='О4' THEN SUMMA ELSE 0 END),
	SUM_NO_D2_B34 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.4' THEN SUMMA ELSE 0 END),
	SUM_NO_D2_B33 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.3' THEN SUMMA ELSE 0 END),
	SUM_NO_D2_B32 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.2' THEN SUMMA ELSE 0 END),
	SUM_NO_D2_B31 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.1' THEN SUMMA ELSE 0 END)

from
	#CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
	INNER JOIN dbo.SAL_SFIN F on F.LINK = CJ.LINK_VKR
	INNER JOIN DBO.EMPL E ON E.LINK = CJ.LINK_EMPL
	LEFT JOIN @StBase2 B ON B.LINK = cj.LINK_PAYS
	LEFT JOIN #PERS_INV I ON I.PERS_LINK = E.PERS_LINK
	LEFT JOIN #EMPL_DT ED ON ED.link = CJ.LINK_EMPL
where 	
	P.[OBJECT] = 1
GROUP BY
	E.PERS_LINK, I.PERS_LINK, CJ.PERIOD_BEGIN


--Договрники
INSERT INTO #SALARY_SUM_DATA (PERS_LINK, PERIOD_BEGIN, SUMMA_ALL, SUMMA_NO, SUMMA_ALL_I, SUMMA_NO_I, SUMMA_ALL_E, SUMMA_NO_E, INV
		--,SUMMA_ALL_D1, SUMMA_NO_D1, SUMMA_ALL_D2, SUMMA_NO_D2
		)
select
	CJ.PERS_LINK,
	CJ.PERIOD_BEGIN,
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(SUMMA) - ISNULL((SELECT SUM(B1.SUMMA_BASE) FROM #DGH_FAKT_BASE1 B1 WHERE B1.PERS_LINK = CJ.PERS_LINK AND B1.MONTH_BASE = Month(CJ.PERIOD_BEGIN)),0), --на которые не начисляются страховые взносы
	SUMMA_ALL_I = 0,
	SUMMA_NO_I = 0,
	SUMMA_ALL_E = SUM(CASE WHEN F.ENVD = 1 THEN SUMMA ELSE 0 END),
	SUMMA_NO_E = SUM(CASE WHEN F.ENVD = 1 THEN SUMMA ELSE 0 END)  - ISNULL((SELECT SUM(B.SUMMA_BASE) FROM #DGH_FAKT_BASE B WHERE B.PERS_LINK = CJ.PERS_LINK AND B.MONTH_BASE = Month(CJ.PERIOD_BEGIN) AND B.ENVD = 1),0),
	INV = CASE WHEN I.PERS_LINK IS NULL THEN 0 ELSE 1 END

	--SUMMA_ALL_D1 = SUM(CASE WHEN CJ.way_calc = 10 then  SUMMA ELSE 0 end ),
	--SUMMA_NO_D1 = 0,

	--SUMMA_ALL_D2 = SUM(CASE WHEN CJ.way_calc = 11 then  SUMMA ELSE 0 end ),
	--SUMMA_NO_D2 = 0
		
from
	#CALCULATE_JURNAL CJ inner join dbo.pays p on p.link = cj.LINK_PAYS
	INNER JOIN dbo.SAL_SFIN F on F.LINK = CJ.LINK_VKR
	INNER JOIN DBO.PERSON P1 ON P1.LINK = CJ.PERS_LINK
	--База по договорникам в разрезе ЕНВД
--	LEFT JOIN #DGH_FAKT_BASE B ON B.PERS_LINK = CJ.PERS_LINK AND B.MONTH_BASE = Month(CJ.PERIOD_BEGIN) AND B.ENVD = 1
	--Общая база по договорникам
--	LEFT JOIN #DGH_FAKT_BASE1 B1 ON B1.PERS_LINK = CJ.PERS_LINK AND B1.MONTH_BASE = Month(CJ.PERIOD_BEGIN)
	LEFT JOIN #PERS_INV I ON I.PERS_LINK = CJ.PERS_LINK
where 	
	P.[OBJECT] = 1
GROUP BY
	CJ.PERS_LINK, I.PERS_LINK, CJ.PERIOD_BEGIN, P1.RESIDENT, p1.birthdate


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

--Данные о начисленной зарплате
SELECT MON = Month(PERIOD_BEGIN),
	SUMMA_ALL = SUM(SUMMA_ALL), SUMMA_NO = SUM(SUMMA_NO),
	SUMMA_ALL_I = SUM(SUMMA_ALL_I), SUMMA_NO_I = SUM(SUMMA_NO_I),
	SUMMA_ALL_E = SUM(SUMMA_ALL_E), SUMMA_NO_E = SUM(SUMMA_NO_E),
	SUMMA_NO_D1 = SUM(SUMMA_NO_D1), SUMMA_NO_D2 = SUM(SUMMA_NO_D2),
	SUM_NO_D1_O4  = SUM(SUM_NO_D1_O4), SUM_NO_D1_B34 = SUM(SUM_NO_D1_B34),
	SUM_NO_D1_B33 = SUM(SUM_NO_D1_B33), SUM_NO_D1_B32 = SUM(SUM_NO_D1_B32), SUM_NO_D1_B31 = SUM(SUM_NO_D1_B31),
	SUM_NO_D2_O4  = SUM(SUM_NO_D2_O4), SUM_NO_D2_B34 = SUM(SUM_NO_D2_B34),
	SUM_NO_D2_B33 = SUM(SUM_NO_D2_B33), SUM_NO_D2_B32 = SUM(SUM_NO_D2_B32), SUM_NO_D2_B31 = SUM(SUM_NO_D2_B31)

INTO #SALARY_SUM2
FROM #SALARY_SUM_DATA
GROUP BY
	Month(PERIOD_BEGIN)

--
DROP TABLE #SALARY_SUM_DATA	

--ОСТАТКИ ПО СЧЁТУ 303.09 (ВЗНОСЫ ПО ДОПТАРИФАМ) НА НАЧАЛО ГОДА
CREATE TABLE #REST_30309_KAU (LINK_KAU INT, REST NUMERIC(18,2))

DECLARE @Cur1 CURSOR, @LINK_ACC INT
SET @Cur1 = CURSOR FORWARD_ONLY

FOR SELECT LINK FROM dbo.S_ACCOUNTS WHERE CODE LIKE '303.09%'

OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @LINK_ACC
WHILE (@@fetch_status <> -1)
BEGIN

	IF (@@fetch_status <> -2)
	BEGIN

			INSERT INTO #REST_30309_KAU (LINK_KAU, REST)
			SELECT KAU, REST = coalesce(sum(K_SUMMA)-sum(D_SUMMA),0) FROM dbo.ARestGroupedTableByDate (@START_DATE, @LINK_ACC, DEFAULT) GROUP BY KAU

	END

	FETCH NEXT FROM @Cur1 INTO @LINK_ACC
END

CLOSE @Cur1
DEALLOCATE @Cur1

--ОСТАТКИ ПО СЧЁТУ 303.10 (ВЗНОСЫ ПО ДОПТАРИФАМ) НА НАЧАЛО ГОДА
CREATE TABLE #REST_30310(REST NUMERIC(18,2))

DECLARE @Cur2 CURSOR
SET @Cur2 = CURSOR FORWARD_ONLY

FOR SELECT LINK FROM dbo.S_ACCOUNTS WHERE CODE LIKE '303.10%'

OPEN @Cur2
FETCH NEXT FROM @Cur2 INTO @LINK_ACC
WHILE (@@fetch_status <> -1)
BEGIN

	IF (@@fetch_status <> -2)
	BEGIN

			INSERT INTO #REST_30310 (REST)
			SELECT REST = coalesce(sum(K_SUMMA)-sum(D_SUMMA),0) FROM dbo.ARestGroupedTableByDate (@START_DATE, @LINK_ACC, DEFAULT)

	END

	FETCH NEXT FROM @Cur2 INTO @LINK_ACC
END

CLOSE @Cur2
DEALLOCATE @Cur2

--ОСТАТКИ ПО СЧЁТУ 303.07 (ВЗНОСЫ ПО ДОПТАРИФАМ) НА НАЧАЛО ГОДА
CREATE TABLE #REST_30307(REST NUMERIC(18,2))

DECLARE @Cur3 CURSOR
SET @Cur3 = CURSOR FORWARD_ONLY

FOR SELECT LINK FROM dbo.S_ACCOUNTS WHERE CODE LIKE '303.07%'

OPEN @Cur3
FETCH NEXT FROM @Cur3 INTO @LINK_ACC
WHILE (@@fetch_status <> -1)
BEGIN

	IF (@@fetch_status <> -2)
	BEGIN

			INSERT INTO #REST_30307 (REST)
			SELECT REST = coalesce(sum(K_SUMMA)-sum(D_SUMMA),0) FROM dbo.ARestGroupedTableByDate (@START_DATE, @LINK_ACC, DEFAULT)

	END

	FETCH NEXT FROM @Cur3 INTO @LINK_ACC
END

CLOSE @Cur3
DEALLOCATE @Cur3

--ОСТАТОК НА НАЧАЛО ГОДА ПО КАУ ДЛЯ ВЗНОСОВ ПО ДОПТАРИФУ №1
DECLARE @KAU_S1 INT, @KAU_S2 INT

SET @KAU_S1 = (SELECT TOP 1 LINK_KAU FROM dbo.REPORT_OPTIONS WHERE Code = 'kau_RSV1_s1')
SET @KAU_S2 = (SELECT TOP 1 LINK_KAU FROM dbo.REPORT_OPTIONS WHERE Code = 'kau_RSV1_s2')

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6, C7, C8)
SELECT '100',
	C3 = ISNULL((SELECT SUM(REST) FROM #REST_30310),0),
	0,0,
	С6 = ISNULL((SELECT SUM(REST) FROM #REST_30309_KAU WHERE LINK_KAU = @KAU_S1),0),
	С7 = ISNULL((SELECT SUM(REST) FROM #REST_30309_KAU WHERE LINK_KAU = @KAU_S2),0),
	C8 = ISNULL((SELECT SUM(REST) FROM #REST_30307),0)

/*Страховая часть*/
CREATE TABLE #PLAT (VID TINYINT, Y INT, MON TINYINT, SUMMA NUMERIC(18,2), Y_p INT, MON_p TINYINT)

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

	INSERT INTO BUFFER (link, id)
	select link, 'DT' from s_accounts where cSinth = '303' and cAnalit = '10' --С 290экр НЕ ДОЛЖЕН БРАТЬСЯ

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

	INSERT INTO BUFFER (link, id)
	select link, 'KT' from s_accounts where cSinth = '201' and (cAnalit = '11' or cAnalit = '21' or cAnalit = '27')

	INSERT INTO #PLAT (VID, Y, MON, SUMMA,Y_P,MON_P)
	SELECT 1,
		Y = CONVERT(INT,YEAR(p.DATE_PROV)),
		MON = CONVERT(INT,MONTH(p.DATE_PROV)),
		P.SUMMA,
		Y_P = CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')),
		MON_P = CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.'))
	from
		dbo.AProvByBufferConditionsShortDate(@BYearDate, @end_date, 'DT', 'KT') P	
		left join dbo.DOCUMENTS_PAY_ADD PA on P.link = PA.link
		left join dbo.g_prov G on G.link = P.link
		LEFT JOIN dbo.KOSGU DG ON DG.LINK = P.DT_EKR
	WHERE
		P.DEP_LINK = @DEP_LINK
		AND
		G.DEP = @DEP_LINK
		--AND
		--CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.')) <= @M
		--AND
		--CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')) = @Y
		AND
		DG.CODE <> '290'

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



/* DECLARE @Res float
SET @Res = 0
exec [dbo].RSA_RSV_1_14_PFR_PREPARE @Res output, '', '20140101', '20140331', 3, 0, 2494
select @Res 	
*/


INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6, C7, C8)
SELECT '140',
	С3 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE Y >= @nYEAR and (Y_p >= @nYEAR OR Y_p = 0 )),0),
	С4 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE Y = @nYEAR AND Y <> 0 and Y_p < @nYEAR AND Y_p <> 0),0),
	 0, 0,0, 0

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6, C7, C8)
SELECT '141',
	С3 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE Y >= @nYEAR  and MON = @nMONTH1  and (Y_p >= @nYEAR OR Y_p = 0 )),0),
	С4 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE Y = @nYEAR AND Y <> 0 AND MON = @nMONTH1 and Y_p < @nYEAR AND Y_p <> 0),0),
	 0, 0,0,0
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6, C7, C8)
SELECT '142',
	С3 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE Y >= @nYEAR and MON = @nMONTH2 and (Y_p >= @nYEAR OR Y_p = 0 )),0),
	С4 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE Y = @nYEAR AND Y <> 0 AND MON = @nMONTH2 and Y_p < @nYEAR AND Y_p <> 0),0),
	 0, 0,0,0	
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6, C7, C8)
SELECT '143',
	С3 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE Y >= @nYEAR and MON = @nMONTH3 and (Y_p >= @nYEAR OR Y_p = 0 )),0),
	С4 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT WHERE Y = @nYEAR AND Y <> 0 AND MON = @nMONTH3 and Y_p < @nYEAR AND Y_p <> 0),0),
	 0, 0,0,0
	
/*Накопительная часть (для годов ниже 2014)*/
CREATE TABLE #PLAT_NAK (VID TINYINT, Y INT, MON TINYINT, SUMMA NUMERIC(18,2), Y_P INT, MON_P TINYINT)

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

	INSERT INTO BUFFER (link, id)
	select link, 'DT' from s_accounts where cSinth = '303' and cAnalit = '11'
	
	INSERT INTO BUFFER (link, id)
	select link, 'KT' from s_accounts where cSinth = '304' and cAnalit = '05'

	INSERT INTO BUFFER (link, id)
	select link, 'KT' from s_accounts where cSinth = '201' and (cAnalit = '11' or cAnalit = '21' or cAnalit = '27')

	INSERT INTO #PLAT_NAK (VID, Y, MON, SUMMA, Y_P, MON_P)
	SELECT 1,
		Y = CONVERT(INT,YEAR(p.DATE_PROV)),
		MON = CONVERT(INT,MONTH(p.DATE_PROV)),
		P.SUMMA,
		Y_P = CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')),
		MON_P = CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.'))
	from
		dbo.AProvByBufferConditionsShortDate(@START_DATE, @end_date, 'DT', 'KT') P	
		left join dbo.DOCUMENTS_PAY_ADD PA on P.link = PA.link
		left join dbo.g_prov G on G.link = P.link
		LEFT JOIN dbo.KOSGU DG ON DG.LINK = P.DT_EKR
	WHERE
		P.DEP_LINK = @DEP_LINK
		AND
		G.DEP = @DEP_LINK
		--AND
		--CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.')) <= @M
		--AND
		--CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')) = @Y
		AND
		DG.CODE >= '211'
		AND DG.CODE <'290'

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


UPDATE #RES2
SET C5 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT_NAK WHERE Y = @nYEAR AND Y <> 0 and Y_p < @nYEAR AND Y_p <> 0),0)
FROM #RES2
WHERE code_str = '140'

UPDATE #RES2
SET C5 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT_NAK WHERE Y = @nYEAR AND Y <> 0 AND MON = @nMONTH1 and Y_p < @nYEAR AND Y_p <> 0),0)
FROM #RES2
WHERE code_str = '141'
UPDATE #RES2
SET C5 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT_NAK WHERE Y = @nYEAR AND Y <> 0 AND MON = @nMONTH2 and Y_p < @nYEAR AND Y_p <> 0),0)
FROM #RES2
WHERE code_str = '142'
UPDATE #RES2
SET C5 = ISNULL((SELECT SUM(SUMMA) FROM #PLAT_NAK WHERE Y = @nYEAR AND Y <> 0 AND MON = @nMONTH3 and Y_p < @nYEAR AND Y_p <> 0),0)
FROM #RES2
WHERE code_str = '143'

DROP TABLE #PLAT
DROP TABLE #PLAT_NAK
--Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соот-ветствии со ст. 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
-- с 2012 года расчет ведется по физ лицам , инвалидам и ЕНВД вместе
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '200',
			
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))			
				WHEN 6 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 9 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
				WHEN 12 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MON = 1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 4 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 5 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 6 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 7 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 8 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 9 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))				
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 10 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 11 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
					 + Convert(numeric(18,2),SUM(CASE WHEN MON = 12 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))	 					 	 					 			 					
			END,			
			
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH1 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH2 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END)),
			 Convert(numeric(18,2),SUM(CASE WHEN MON = @nMONTH3 THEN SUMMA_ALL - SUMMA_ALL_I - SUMMA_ALL_E ELSE 0 END))
FROM #SALARY_SUM2		


--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '201',
	
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1) ,0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0))
		WHEN 6 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 6),0))			
		WHEN 9 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 9),0))			
		WHEN 12 THEN
			CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0))		
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 4) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 4),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 5) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 5),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 6) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 6),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 7) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 7),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 8) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 8),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 9) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 9),0))					
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 10) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 10),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 11) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 11),0))
			+ CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = 12) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 12),0))			
	END,	
	
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH1) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = @nMONTH1),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH2) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = @nMONTH2),0)),
	CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 1 AND MONTH_BASE = @nMONTH3) ,0) + ISNULL( (SELECT SUM(SUMMA_NO - SUMMA_NO_I - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = @nMONTH3),0))





----- Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
----- (отражаются суммы фактически произведенных и документально подтвержденных расходов, связанных с извлечением доходов,
-----  полученных по договору авторского заказа, договору об отчуждении исключительного права на произведения науки, литературы,
-----  искусства, издательскому лицензионному договору, лицензионному договору о предоставлении права использования произведения науки,
-----  литературы, искусства или суммы расходов, которые не могут быть подтверждены документально и принимаемые к вычету)
-----  Сейчас заполняем нулями
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '202',
	
	CASE @nMONTH3
		WHEN 3 THEN
			CONVERT(numeric(18,2),0)
		WHEN 6 THEN
			CONVERT(numeric(18,2),0)
		WHEN 9 THEN
			CONVERT(numeric(18,2),0)
		WHEN 12 THEN
			CONVERT(numeric(18,2),0)
	END,	
	
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0),
	CONVERT(numeric(18,2),0)

-----

--Суммы, превышающие предельную величину базы для начисления страховых взносов
DECLARE @LIMIT NUMERIC(18,2)

SELECT
	@LIMIT  = MIN(S.PREDEL)
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
	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
	 ORDER BY [DATE] DESC)
	AND
	S.PERCENT1 > 0
	
SET @LIMIT = ISNULL(@LIMIT,0)



--Суммы, превышающие предельную величину базы для начисления медицинского страхования
DECLARE @LIMIT_OMS NUMERIC(18,2)

SELECT @LIMIT_OMS = 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_OMS = ISNULL(@LIMIT_OMS,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_OMS
	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_OMS
	 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_OMS
	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_OMS
	 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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 '214',
	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))	


-- Количество чел , кому начислялись страховые взносы на обязательное медицинское страхование
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '215',
	CASE WHEN @nMONTH3 > 3 THEN
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 and WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 AND I = 1 and MONTH_BASE = @nMONTH1
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 and WAY_CALC = 3 AND I = 1 and MONTH_BASE = @nMONTH2
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 and WAY_CALC = 3 AND I = 1 and MONTH_BASE = @nMONTH3) T
			),0)
	END,	
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 and WAY_CALC = 3 AND I = 1 and MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 and WAY_CALC = 3 AND I = 1 and MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 and 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 = '214')
			) / (@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 = '214')
			) / (@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 = '214')
			) / (@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 = '214')
			) / (@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 = '214'
		
	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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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_OMS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OMS 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 '2140',
	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))	

-- Количество чел , кому начислялись страховые взносы на обязательное медицинское страхование
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2150',
	CASE WHEN @nMONTH3 > 3 THEN
		ISNULL(
			(SELECT MAX(CNT)
			FROM
				(SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 and WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 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 WAY_CALC = 3 AND I = 2 and MONTH_BASE = @nMONTH1
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 and WAY_CALC = 3 AND I = 2 and MONTH_BASE = @nMONTH2
				UNION SELECT CNT = count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 and WAY_CALC = 3 AND I = 2 and MONTH_BASE = @nMONTH3) T
			),0)
	END,	
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 and WAY_CALC = 3 AND I = 2 and MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 and WAY_CALC = 3 AND I = 2 and MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where summa <> 0 and 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'
			
	END	
	
END	
	


IF ISNULL(@IPERCENT_OMS,0) > 0
BEGIN
	--Вычисление погрешности для ОМС	
	SELECT
		@C3N = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2140 =
					(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 = '2140')
			) / (@IPERCENT_OMS/100)
		),

		@C3NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2140  =
					(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( --Стр 2140 =
					(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 = '2140')
			) / (@IPERCENT_OMS/100)
		),
		@C4NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2140 =
					(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( --Стр 2140 =
					(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 = '2140')
			) / (@IPERCENT_OMS/100)
		),

		@C5NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2140 =
					(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( --Стр 2140 =
					(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 = '2140')
			) / (@IPERCENT_OMS/100)
		),
		@C6NS = CONVERT(NUMERIC(18,2),
			(
				SUM( --Стр 2140 =
					(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 = '2140'
		
	END

	--Корректируем необлагаемые суммы на копейки округления
	IF @SALARY_OPTIONS_OPT6_1 = 3
	BEGIN
		UPDATE #RES2
		SET
			C3 = C3 + ISNULL(@C3N,0),
			C4 = C4 + ISNULL(@C4N,0),
			C5 = C5 + ISNULL(@C5N,0),
			C6 = C6 + ISNULL(@C6N,0)			
		WHERE
			CODE_STR = '2110'
	END	

END		

---------------
/********Расчет допольнительного тарифа страховых взносов  указаных в части 1 статьи 58.3 Федерального закона от 24 июля 2009 г. № 212-ФЗ**********/
/*******Раздел 2.2*********/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '220',
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON <= 3 ),0) )
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)  + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			
			
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
			
FROM #SPR_ESN
WHERE WAY_CALC = 10	 and SP = ''	

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '221',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN
WHERE WAY_CALC = 10	 and SP = ''	


------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '282', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT
	'224',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN
WHERE WAY_CALC = 10 and SP = ''	

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '225',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 and SP = ''	 and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 and SP = ''	 and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10  and SP = ''	and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10  and SP = ''	and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10  and SP = ''	and  MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10  and SP = ''	and  MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10  and SP = ''	and  MONTH_BASE = @nMONTH3) ,0)


/********Расчет допольнительного тарифа страховых взносов  указаных в части 2 статьи 58.3 Федерального закона от 24 июля 2009 г. № 212-ФЗ**********/
/*******Раздел 2.3*********/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '230',
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			
			
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
			
FROM #SPR_ESN
WHERE WAY_CALC = 11	 and SP = ''		

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '231',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN
WHERE WAY_CALC = 11	 and SP = ''	

------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '292', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT
	'234',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN
WHERE WAY_CALC = 11 and SP = ''	

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '235',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 and SP = ''	 and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 and SP = ''	and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 and SP = ''	and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 and SP = ''	and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 and SP = ''	and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 and SP = ''	and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 and SP = ''	and  MONTH_BASE = @nMONTH3) ,0)



/********2.4. Расчет страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов по доп тарифу 1***********/
/*******Раздел 2.4*** Класс условий труда - опасный, подкласс условий труда - 4  ******/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '240',
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON <= 6),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			
			
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH3),0))
			
FROM #SPR_ESN
WHERE WAY_CALC = 10	AND SP = 'О4'	


--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '241',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN
WHERE WAY_CALC = 10	AND SP = 'О4'



------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '243', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT
	'244',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP = 'О4'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '245',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'О4' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'О4' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'О4' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'О4' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'О4' and  MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'О4' and  MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'О4' and  MONTH_BASE = @nMONTH3) ,0)


/********Расчет допольнительного тарифа страховых взносов  по доп тарифу 1**********/
/*******Раздел 2.4**** Класс условий труда - вредный, подкласс условий труда - 3.4  *****/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '246',
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			
			
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
			
FROM #SPR_ESN
WHERE WAY_CALC = 10	 AND SP = 'В3.4'	

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '247',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN
WHERE WAY_CALC = 10	 AND SP = 'В3.4'	

------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '249', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT
	'250',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN
WHERE WAY_CALC = 10	 AND SP = 'В3.4'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '251',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.4' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.4' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.4' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.4' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.4' and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.4' and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.4' and  MONTH_BASE = @nMONTH3) ,0)


/*******Раздел 2.4*** Класс условий труда - вредный, подкласс условий труда - 3.3  ******/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '252',
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			
			
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
			
FROM #SPR_ESN
WHERE WAY_CALC = 10	AND SP = 'В3.3'	

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '253',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN
WHERE WAY_CALC = 10	AND SP = 'В3.3'


------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '255', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT
	'256',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP = 'В3.3'



--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '257',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'В3.3' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'В3.3' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'В3.3' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'В3.3' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'В3.3' and  MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'В3.3' and  MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10 AND SP = 'В3.3' and  MONTH_BASE = @nMONTH3) ,0)


/********Расчет допольнительного тарифа страховых взносов  по доп тарифу 1**********/
/*******Раздел 2.4**** Класс условий труда - вредный, подкласс условий труда - 3.2 *****/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '258',
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			
			
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
			
FROM #SPR_ESN
WHERE WAY_CALC = 10	 AND SP = 'В3.2'	

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '259',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN
WHERE WAY_CALC = 10	 AND SP = 'В3.2'	

------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '261', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT
	'262',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN
WHERE WAY_CALC = 10	 AND SP = 'В3.2'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '263',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.2' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.2' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.2' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.2' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.2' and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.2' and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.2' and  MONTH_BASE = @nMONTH3) ,0)

/*******Раздел 2.4**** Класс условий труда - вредный, подкласс условий труда - 3.1 *****/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '264',
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			
			
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
			
FROM #SPR_ESN
WHERE WAY_CALC = 10	 AND SP = 'В3.1'	

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '265',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN
WHERE WAY_CALC = 10	 AND SP = 'В3.1'	

------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '267', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT
	'268',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN
WHERE WAY_CALC = 10	 AND SP = 'В3.1'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '269',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.1' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.1' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.1' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.1' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.1' and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.1' and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 10	 AND SP = 'В3.1' and  MONTH_BASE = @nMONTH3) ,0)


/********2.4. Расчет страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов по доп тарифу 2***********/
/*******Раздел 2.4*** Класс условий труда - опасный, подкласс условий труда - 4  ******/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2400',
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			
			
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
			
FROM #SPR_ESN
WHERE WAY_CALC = 11	AND SP = 'О4'	



--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2410',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN
WHERE WAY_CALC = 11	AND SP = 'О4'


------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '2430', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT
	'2440',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP = 'О4'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2450',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'О4' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'О4' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'О4' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'О4' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'О4' and  MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'О4' and  MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'О4' and  MONTH_BASE = @nMONTH3) ,0)


/********Расчет допольнительного тарифа страховых взносов  по доп тарифу 2**********/
/*******Раздел 2.4**** Класс условий труда - вредный, подкласс условий труда - 3.4  *****/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2460',
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			
			
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
			
FROM #SPR_ESN
WHERE WAY_CALC = 11	 AND SP = 'В3.4'	

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2470',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN
WHERE WAY_CALC = 11	 AND SP = 'В3.4'	

------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '249', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT
	'2500',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN
WHERE WAY_CALC = 11	 AND SP = 'В3.4'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2510',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.4' and  MONTH_BASE = @nMONTH3) ,0)


/*******Раздел 2.4*** Класс условий труда - вредный, подкласс условий труда - 3.3  ******/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2520',
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			
			
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
			
FROM #SPR_ESN
WHERE WAY_CALC = 11	AND SP = 'В3.3'	

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2530',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN
WHERE WAY_CALC = 10	AND SP = 'В3.3'


------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '2550', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT
	'2560',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP = 'В3.3'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2570',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE = @nMONTH1) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE = @nMONTH2) ,0) ,
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.3' and  MONTH_BASE = @nMONTH3) ,0)


/********Расчет допольнительного тарифа страховых взносов  по доп тарифу 2**********/
/*******Раздел 2.4**** Класс условий труда - вредный, подкласс условий труда - 3.2 *****/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2580',
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			
			
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))
			
FROM #SPR_ESN
WHERE WAY_CALC = 11	 AND SP = 'В3.2'	

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2590',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN
WHERE WAY_CALC = 11	 AND SP = 'В3.2'	

------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '2610', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT
	'2620',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN
WHERE WAY_CALC = 11	 AND SP = 'В3.2'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2630',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.2' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.2' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.2' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.2' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.2' and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.2' and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11 AND SP = 'В3.2' and  MONTH_BASE = @nMONTH3) ,0)

/*******Раздел 2.4**** Класс условий труда - вредный, подкласс условий труда - 3.1 *****/
--- Сумма выплат и иных вознаграждений, начисленных в пользу физических лиц, в соответствии со статьей 7 Федерального закона от 24 июля 2009 г. № 212-ФЗ
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2640',
			CASE @nMONTH3
				WHEN 3 THEN
					 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
				WHEN 6 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
				WHEN 9 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
				WHEN 12 THEN
					Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
			END,			
			
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
			 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA_BASE ELSE 0 END)+ ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH3),0))
			
FROM #SPR_ESN
WHERE WAY_CALC = 11	 AND SP = 'В3.1'	

--Суммы, не под-лежащие обло-жению страхо-выми взносами:
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2650',
	
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 3 ),0))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 6 ),0))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 9 ),0))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON <= 12 ),0))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH1 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH2 ),0)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN DED_M + INV_M ELSE 0 END) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = @nMONTH3 ),0))

FROM #SPR_ESN
WHERE WAY_CALC = 11	 AND SP = 'В3.1'	



------ Сумма расходов, принимаемых к вычету, в соответствии с частью 7 статьи 8 Федерального закона от 24 июля 2009 № 212-ФЗ
--INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
--SELECT '2670', 0, 0, 0, 0


---***Начислено страховых взносов по дополнительному тарифу для отдельных категорий плательщиков страховых взносов
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT
	'2680',
	CASE @nMONTH3
		WHEN 3 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 3 THEN SUMMA ELSE 0 END))
		WHEN 6 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 6 THEN SUMMA ELSE 0 END))
		WHEN 9 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 9 THEN SUMMA ELSE 0 END))
		WHEN 12 THEN
			Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE <= 12 THEN SUMMA ELSE 0 END))
	END,	
	
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH1 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH2 THEN SUMMA ELSE 0 END)),
	 Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = @nMONTH3 THEN SUMMA ELSE 0 END))

FROM #SPR_ESN
WHERE WAY_CALC = 11	 AND SP = 'В3.1'

--- ***Количество физических лиц, с выплат которым начислены страховые взносы по дополнительному тарифу страховых взносов (чел.)
INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '2690',

	CASE @nMONTH3
		WHEN 3 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE <= 3 ) ,0)
		WHEN 6 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE <= 6 ) ,0)		
		WHEN 9 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE <= 9 ) ,0)		
		WHEN 12 THEN
			ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE <= 12 ) ,0)		
	END,

	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE = @nMONTH1) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE = @nMONTH2) ,0),
	ISNULL((SELECT count(DISTINCT ref_phys_pers) FROM #SPR_ESN where WAY_CALC = 11	 AND SP = 'В3.1' and  MONTH_BASE = @nMONTH3) ,0)

--select * from #RES2
---------------
/********СРЕДНЕСПИСОЧНАЯ ЧИСЛЕННОСТЬ**********/

DECLARE @Date1M datetime, @Date2M datetime, @Date3M datetime

SELECT @BDate = @START_DATE, @EndDate = @END_DATE
SET @EDate = dateadd(year,1,convert(varchar, YEAR(@BDate))+'0101')

if @nMONTH3 =3
begin
	SET @Date1M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0101')
	SET @Date2M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0201')
	SET @Date3M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0301')
end
if @nMONTH3 =6
begin
	SET @Date1M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0401')
	SET @Date2M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0501')
	SET @Date3M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0601')
end
if @nMONTH3 =9
begin
	SET @Date1M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0701')
	SET @Date2M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0801')
	SET @Date3M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'0901')
end
if @nMONTH3 =12
begin
	SET @Date1M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'1001')
	SET @Date2M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'1101')
	SET @Date3M = dateadd(year,0,convert(varchar, YEAR(@BDate))+'1201')
end

/* Считаем что все наши организации не состоят из уставных вкладов инвалидов , поэтому таблицу 3.1 -3.2 не заполняем */
/* Среднесписочная численность всего */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 0, DEFAULT))

/*INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '331',@NAvgCount,
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date1M, @Date2M, @DEP_LINK, 0, 1, 0, DEFAULT)),
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date2M, @Date3M, @DEP_LINK, 0, 1, 0, DEFAULT)),
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date3M, @END_DATE, @DEP_LINK, 0, 1, 0, DEFAULT))	

/* Среднесписочная численность работников инвалидов */
Set @NAvgCount = convert(numeric(18,0), dbo.sa_ssch_empls(@START_DATE, @END_DATE, @DEP_LINK, 0, 1, 1, DEFAULT))

INSERT INTO #RES2(CODE_STR, C3, C4, C5, C6)
SELECT '332',@NAvgCount,
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date1M, @Date2M, @DEP_LINK, 0, 1, 1, DEFAULT)),
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date2M, @Date3M, @DEP_LINK, 0, 1, 1, DEFAULT)),
			convert(numeric(18,0), dbo.sa_ssch_empls(@Date3M, @END_DATE, @DEP_LINK, 0, 1, 1, DEFAULT))	

*/

/* Завершаем - списываем значения во временную таблицу */
DECLARE @Table_Razd1 VARCHAR(100)
EXEC dbo.X_GET_TABLE_NAME @Table_Razd1 OUTPUT
EXEC ('select * INTO ' + @Table_Razd1 + ' from #RES2 order by code_str')
EXEC dbo.BufferClear
EXEC dbo.BufferPush -116, @Table_Razd1

DROP TABLE #RES2
















GO


GRANT EXECUTE ON dbo.[RSA_RSV_1_15_PFR_PREPARE] TO PUBLIC

GO



GO

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

GO

CREATE   PROCEDURE [dbo].SA_SZV4_PACHKA_CALC_Buffer (@BufferCode varchar(10), @link int, @Year int, @Month tinyint) 
AS

IF @Year < 2010
	EXEC dbo.SA_SZV4_PACHKA_CALC_Buffer1 @BufferCode, @link, @Year, @Month

IF @Year >= 2010 AND @Year <= 2012	
	EXEC dbo.SA_SZV4_PACHKA_CALC_Buffer2 @BufferCode, @link, @Year, @Month	

IF @Year >= 2013 AND @Year <= 2014	
	EXEC dbo.SA_SZV4_PACHKA_CALC_Buffer3 @BufferCode, @link, @Year, @Month	

IF @Year >= 2015 AND @Month <=3
	EXEC dbo.SA_SZV4_PACHKA_CALC_Buffer4 @BufferCode, @link, @Year, @Month		

IF @Year >= 2015 AND @Month >=6
	EXEC dbo.SA_SZV4_PACHKA_CALC_Buffer_2015_6 @BufferCode, @link, @Year, @Month		

GO


GRANT EXECUTE ON dbo.[SA_SZV4_PACHKA_CALC_Buffer] TO PUBLIC

GO

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

GO

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

CREATE PROCEDURE dbo.BK_REPORT_SVOD_PROV
	@varKSdDate1	DATETIME,
	@varKSdDate2	DATETIME,
	@varKSnPRN_KBK	INT,
	@varKSnPRN_SGU	INT,
	@intSVOD_PROV	INT,
	@varKScVal1 char(1), @varKSnOtborLink1 int /* -- Отбор субсчетов -- */,
	@cVal_KBK char(1), @nOtborLinkKBK int	/* Отбор КБК */,
	@intSVOD_ZB INT
AS
BEGIN
	DECLARE	@varKSLINK_DEP	INT,
		@varKSDEP_CODE	VARCHAR (20),
		@varKSDEP_NAME	VARCHAR (254),
		@varKSDEP_OKPO	VARCHAR (20)

	--- ОТБОР СУБСЧЕТОВ --- 
	DECLARE @ACCT  TABLE (LINK_ACCT [INT])	
	IF LEN (@varKScVal1) > 0
		INSERT INTO @ACCT
		SELECT RECORD
		FROM dbo.OBJECT_VAR_ACCT
		WHERE LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO @ACCT
		SELECT LINK
		FROM dbo.AccountsTableWithNoChild()

	--- ОТБОР КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	-- Параметры организации -- 
	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)
	SET @varKSLINK_DEP = dbo.BK_GetDepZB ()

	IF @intSVOD_ZB = 1 OR @varKSLINK_DEP IS NULL
		SET @varKSLINK_DEP = dbo.GetOwnDepLink()

	SELECT @varKSLINK_DEP = LINK,
		@varKSDEP_CODE = CODE,
		@varKSDEP_NAME = dbo.BK_GET_PRINT_DEP_NAME (LINK),
		@varKSDEP_OKPO = OKPO
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @varKSLINK_DEP

	IF @intSVOD_ZB = 1
	BEGIN
		SET @varKSDEP_NAME = RTRIM (@varKSDEP_NAME) + ' (ЦБ)'
		SET @varKSLINK_DEP = NULL
	END

	--- Список  операций ---
	DECLARE @TABLE_OPER TABLE (LINK_DOC INT,
				LINK_G2 INT,
				XOZ_OPER INT
				)
	
	INSERT INTO @TABLE_OPER
	SELECT
		LINK_DOC,
		LINK_G2,
		XOZ_OPER
	FROM dbo.BK_GetTableOborotByDate1
		(@varKSdDate1, @varKSdDate2,
		DEFAULT, DEFAULT,
		@varKSLINK_DEP)
	GROUP BY
		LINK_DOC,
		LINK_G2,
		XOZ_OPER

-- select * from @TABLE_OPER

	--- Проводки ---
	DECLARE @TABLE_PROV TABLE ([DOC_NUM] VARCHAR (60),
				[dDOC_DATE] DATETIME,
				[DOC_DATE] VARCHAR (10),
				[DOC_NAME] VARCHAR (254),
				[JO_CODE] VARCHAR (254),
				[DT_ACCT] VARCHAR (60),
				[KT_ACCT] VARCHAR (60),
				[SUMMA] NUMERIC (28,4))

	INSERT INTO @TABLE_PROV
	SELECT
		G.NUMBER,
		G.[DATE], 
		CONVERT (VARCHAR (10), G.[DATE], 104),
		dbo.JurnalProvGetDocKind (G.LINK, G.[OBJECT]),
		dbo.BX_XOZ_OPER_EnumJurnals (T_OP.XOZ_OPER),
		[DT_ACCT] = dbo.BK_GetAcctFullCode1 (GAP_D.ACCOUNT, GAP_D.KBK, GAP_D.SGU, @varKSnPRN_KBK, @varKSnPRN_SGU),
		[KT_ACCT] = dbo.BK_GetAcctFullCode1 (GAP_K.ACCOUNT, GAP_K.KBK, GAP_K.SGU, @varKSnPRN_KBK, @varKSnPRN_SGU),
		G2.SUMMA
	FROM @TABLE_OPER T_OP
	INNER JOIN dbo.G_PROV G ON (G.LINK = T_OP.LINK_DOC)
	INNER JOIN dbo.G_PROV2 G2 ON (G2.LINK = T_OP.LINK_G2)
	LEFT JOIN dbo.G_PROV_AP GAP_D ON (GAP_D.LINK_UP = T_OP.LINK_G2
		AND GAP_D.DB_KR = 0)
	LEFT JOIN dbo.G_PROV_AP GAP_K ON (GAP_K.LINK_UP = T_OP.LINK_G2
		AND GAP_K.DB_KR = 1)
	LEFT JOIN @ACCT AC_D ON (AC_D.LINK_ACCT = GAP_D.ACCOUNT)
	LEFT JOIN @ACCT AC_K ON (AC_K.LINK_ACCT = GAP_K.ACCOUNT)

	LEFT JOIN @TAB_KBK KBK_D ON (KBK_D.LINK_KBK = ISNULL (GAP_D.KBK, 0))
	LEFT JOIN @TAB_KBK KBK_K ON (KBK_K.LINK_KBK = ISNULL (GAP_K.KBK, 0))

	WHERE (AC_D.LINK_ACCT = GAP_D.ACCOUNT
		OR AC_K.LINK_ACCT = GAP_K.ACCOUNT)
		AND (KBK_D.LINK_KBK IS NOT NULL
			OR KBK_K.LINK_KBK IS NOT NULL)

	IF @intSVOD_PROV = 1
		SELECT @varKSDEP_NAME AS ORGNAME, DT_ACCT, KT_ACCT, JO_CODE, SUM (SUMMA) AS SUMMA
		FROM @TABLE_PROV 
		GROUP BY DT_ACCT, KT_ACCT, JO_CODE
	ELSE
		SELECT @varKSDEP_NAME AS ORGNAME, * FROM @TABLE_PROV ORDER BY dDOC_DATE, DOC_NAME, DOC_NUM
END


GO


GRANT EXECUTE ON dbo.[BK_REPORT_SVOD_PROV] TO PUBLIC

GO



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

GO
CREATE PROCEDURE [dbo].[SA_VEDOM_ACCOUNTS_TAB] (@LINK_VEDOM INT)
AS

BEGIN

	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
	
	if @CODE_OBJECT = 'DOCUMENTS_DED_PAYROLL' 
		SELECT @LINK_EKR_DEFAULT = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '211' 
	else 																			
		SELECT @LINK_EKR_DEFAULT = (case when (select count(a.link_ekr) from (SELECT p.link_ekr 
										  FROM salary_REESTR_DGH sd 
										  INNER JOIN DOCUMENTS_DED_PR_TABLE_DGH dt1 ON sd.pers_link = dt1.pers_link  
										  INNER JOIN DOCUMENTS_DED_PR_DGH dt ON dt.link = dt1.link
										  inner join pays p ON p.link = sd.LINK_PAYS
										  WHERE dt1.LINK = @LINK_VEDOM AND (dt.YEAR_BASE BETWEEN year(sd.DATE1) AND YEAR(sd.date2) AND dt.YEAR_BASE <=YEAR(sd.date2) AND dt.MONTH_BASE <= MONTH(sd.DATE2)) group by p.link_ekr) a) = 1 
										  then (SELECT p.link_ekr 
												  FROM salary_REESTR_DGH sd 
												  INNER JOIN DOCUMENTS_DED_PR_TABLE_DGH dt1 ON sd.pers_link = dt1.pers_link  
												  INNER JOIN DOCUMENTS_DED_PR_DGH dt ON dt.link = dt1.link
												  inner join pays p ON p.link = sd.LINK_PAYS
												  WHERE dt1.LINK = @LINK_VEDOM AND (dt.YEAR_BASE BETWEEN year(sd.DATE1) AND YEAR(sd.date2) AND dt.YEAR_BASE <=YEAR(sd.date2) AND dt.MONTH_BASE <= MONTH(sd.DATE2)) group by p.link_ekr) 
										  else  ' '
										  end )
																													

	---- данные из ведомости
	CREATE TABLE #ved_data (LINK_SFIN INT ,LINK_EKR INT ,Fin_Source tinyint,USER_ACC VARCHAR(4),KD_CODE_ACC VARCHAR(6),CODE_EKR CHAR(3),CODE_KBK VARCHAR(30))
	INSERT INTO #ved_data
	SELECT
		LINK_SFIN = V.LINK_VKR,
		LINK_EKR = V.LINK_EKR,
		Fin_Source = COALESCE(CAST (F.SOURCE as CHAR(1)),''),
		USER_ACC = F.USER_ACC,
		KD_CODE_ACC = P.CODE_ACC,
		CODE_EKR = EKR.CODE,
		CODE_KBK = REPLACE(KBK.CODE,'.','')
	FROM 	
		(
			SELECT LINK_PAY, LINK_VKR = LINK_sfin, vt1.LINK_EKR FROM dbo.SDOC_VEDOM V1 
				INNER JOIN SDOC_VEDOM_TABLE1 vt1 ON  vt1.link_up =V1.link_up
				WHERE V1.LINK_up =       @LINK_VEDOM
			GROUP BY LINK_PAY, LINK_sfin, vt1.LINK_EKR
			UNION ALL
			SELECT LINK_PAY, LINK_VKR, vt2.LINK_EKR FROM dbo.SDOC_VEDOM_DGH V2 
				INNER JOIN  SDOC_VEDOM_DGH_TABLE1 vt2 ON  vt2.link_up =V2.link_up
				WHERE V2.LINK_up =       @LINK_VEDOM
			GROUP BY LINK_PAY, LINK_VKR, vt2.LINK_EKR
			
		) V
		INNER JOIN dbo.SAL_SFIN F ON V.LINK_VKR = F.LINK
		INNER JOIN dbo.PAYS P ON V.LINK_PAY = P.LINK
		INNER JOIN dbo.KOSGU EKR ON EKR.LINK = V.LINK_EKR
		INNER JOIN dbo.KL_KBK KBK ON KBK.LINK = F.KBK
		
	---
	Declare @ACC_302 VARCHAR(10)
	SELECT TOP 1 @ACC_302 = LTRIM(RTRIM(VALUE)) FROM dbo.S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SALARY_OPTIONS_OPT1'))) AND SID IS NULL

	-- таблица ДТ - КТ 
	SELECT distinct dt = a1.CODE,  
		  kt = a2.CODE,
		  link_sfin = CASE WHEN ISNULL(a1.link_sfin,'')<>'' then a1.link_sfin else a2.link_sfin END,
		  EKR_KODE = CASE WHEN ISNULL(a1.CODE_EKR,'')<>'' then a1.code_ekr else a2.CODE_EKR end ,
		  KBK_CODE = CASE WHEN ISNULL(a1.CODE_KBK,'')<>'' then a1.code_kbk else a2.CODE_KBK end 
	FROM
	(SELECT sa1.CODE, CODE_EKR, link_sfin, CODE_KBK  FROM  dbo.S_ACCOUNTS sa1
		INNER  JOIN #ved_data vd ON   sa1.cSource = vd.Fin_Source AND  sa1.ANALIT_EKR = vd.LINK_EKR
	 WHERE sa1.cSinth = RTRIM(LTRIM(@ACC_302)) 
		   AND (isnull(VD.USER_ACC,'') = '' 
						or isnull(sa1.cUser,'') = RTRIM(LTRIM(isnull(VD.USER_ACC,''))))
	) a1 , 
	(SELECT sa1.CODE, CODE_EKR, link_sfin , CODE_KBK
	FROM dbo.S_ACCOUNTS sa1
		INNER  JOIN #ved_data vd ON   sa1.cSource = vd.Fin_Source  AND (sa1.cSinth + '.' + sa1.cAnalit = vd.KD_CODE_ACC)

	WHERE  	 isnull(cUser,'') = RTRIM(LTRIM(COALESCE(vd.USER_ACC,''))) 
	) a2 
		
	DROP TABLE #ved_data		
	
	RETURN

END		







GO


GRANT EXECUTE ON dbo.[SA_VEDOM_ACCOUNTS_TAB] TO PUBLIC

GO



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

GO

CREATE PROCEDURE [dbo].SD_EMPL_DED_SAVE
    @LINK			INT	OUTPUT,
	@EMPL_LINK		INT = null,
	@DED_LINK		INT = null,
	@Date1			DATETIME,
	@Date2			DATETIME,
	@LINK_DGH	int = null
AS

DECLARE @varKSSQLError	int, 
		@varKSEventText	varchar(7000),
		@varKStrancount	int,  
		@varKSObjLink int, 
		@varKSRowCount INT

if @EMPL_LINK = 0 
	set @EMPL_LINK = null
if @LINK_DGH = 0 
	set @LINK_DGH = null	

	
IF (@EMPL_LINK IS NULL OR @EMPL_LINK = 0) AND (@LINK_DGH IS NULL OR @LINK_DGH = 0)  
BEGIN
	RETURN 5
END
	IF @DED_LINK IS NULL OR @DED_LINK = 0
BEGIN
	RETURN 5
END

----
DECLARE 
	@LINK_PERSON INT,
	@DEP_LINK INT,
	@ROW_COUNT INT
	
	
--- проверка на пересечение периодов вычетов для реестров гпх
IF @LINK_DGH IS NOT NULL 
BEGIN 

	SET @LINK_PERSON = (SELECT TOP 1 PERS_LINK FROM dbo.REESTR_DGH WHERE LINK = @LINK_DGH)
	SET @DEP_LINK = (SELECT TOP 1 DEP_LINK FROM dbo.REESTR_DGH WHERE LINK = @LINK_DGH)

	DELETE FROM dbo.SAL_WORNINGS WHERE SID = SUSER_SID()
	
	SET @ROW_COUNT = 0

	INSERT INTO dbo.SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	SELECT 
		'Не сохранён вычет с кодом "' + COALESCE((LTRIM(RTRIM(TD.CODE))),'') + '". ' + dbo.ku_GetPersFIO(@LINK_PERSON) + ' имеет вычет с периодом, который пересекается с периодом такого же вычета в других договорах:',
		'Дог.№' + LTRIM(RTRIM(R.NUMBER)) + ' от ' + CONVERT(VARCHAR(10),R.[DATE],104) + ' Код вычета: ' + LTRIM(RTRIM(CODE)) + ' период с ' + CONVERT(VARCHAR(10),D.DATE1,104) + ' по ' + CONVERT(VARCHAR(10),ISNULL(D.DATE2,'20991231'),104),   
		'Измените период действия вычета в данном договоре.',
		'SALARY'
	FROM 
		dbo.REESTR_DGH R
		INNER JOIN dbo.EMPL_DED D ON R.LINK = D.LINK_DGH	
		INNER JOIN [dbo].[DICTIONARY_TYP_DEDUCTION]	TD ON TD.[LINK] = D.[DED_LINK]
	WHERE
		R.DEP_LINK = @DEP_LINK
		AND
		R.PERS_LINK = @LINK_PERSON
		AND 
		R.LINK <> @LINK_DGH
		AND
		D.DED_LINK = @DED_LINK
		AND
		D.DATE1 <= ISNULL(@Date2,'20990101')
		AND  
		ISNULL(D.DATE2,'20990101') >= @Date1

	SET @ROW_COUNT = @@ROWCOUNT	

	IF @ROW_COUNT > 0
		RETURN 8
		
END
ELSE BEGIN
	-- проверка на пересечение периодов вычетов для личных карточек сотрудников
	SET @LINK_PERSON = (SELECT TOP 1 PERS_LINK FROM dbo.SD_EMPL WHERE LINK = @EMPL_LINK)
	SET @DEP_LINK = (SELECT TOP 1 DEP_LINK FROM dbo.SD_EMPL WHERE LINK = @EMPL_LINK)

	DELETE FROM dbo.SAL_WORNINGS WHERE SID = SUSER_SID()
	
	SET @ROW_COUNT = 0

	INSERT INTO dbo.SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	SELECT 
		'Не сохранён вычет с кодом "' + COALESCE((LTRIM(RTRIM(TD.CODE))),'') + '". ' + dbo.ku_GetPersFIO(@LINK_PERSON) + ' имеет вычет с периодом, который пересекается с периодом такого же вычета в других личных карточках:',
		'Таб.№' + LTRIM(RTRIM(E.TAB)) + ' Код вычета: ' + LTRIM(RTRIM(CODE)) + ' период с ' 
		+ CONVERT(VARCHAR(10),D.DATE1,104) + ' по ' 
		+ CONVERT(VARCHAR(10),
					(CASE WHEN dbo.DateEndOfMonth(ISNULL(e.DATE_END,'20490101')) <  dbo.DateEndOfMonth(ISNULL(D.DATE2,'20490101'))
						THEN dbo.DateEndOfMonth(ISNULL(e.DATE_END,'20490101'))
						ELSE dbo.DateEndOfMonth(ISNULL(D.DATE2,'20490101'))
					END)
				,104),   
		'Измените период действия вычета в личной карточке.',
		'SALARY'
	FROM 
		dbo.sd_empl e
		INNER JOIN dbo.EMPL_DED D ON e.LINK = D.EMPL_LINK
		INNER JOIN [dbo].[DICTIONARY_TYP_DEDUCTION]	TD ON TD.[LINK] = D.[DED_LINK]
	WHERE
		e.DEP_LINK = @DEP_LINK
		AND
		e.PERS_LINK = @LINK_PERSON
		AND 
		e.LINK <> @EMPL_LINK
		AND
		D.DED_LINK = @DED_LINK
		AND
		D.DATE1 <= ISNULL(@Date2,'20990101')
		AND  
		--(Case when e.DATE_END is null then dbo.DateEndOfMonth(ISNULL(D.DATE2,'20990101')) else  dbo.DateEndOfMonth(ISNULL(E.DATE_END,'20990101')) end ) >= @Date1
		(CASE WHEN dbo.DateEndOfMonth(ISNULL(e.DATE_END,'20490101')) <  dbo.DateEndOfMonth(ISNULL(D.DATE2,'20490101'))
			THEN dbo.DateEndOfMonth(ISNULL(e.DATE_END,'20490101'))
			ELSE dbo.DateEndOfMonth(ISNULL(D.DATE2,'20490101'))
		END) >= @Date1
	
	SET @ROW_COUNT = @@ROWCOUNT	

	IF @ROW_COUNT > 0
		RETURN 8

END

--
SELECT @varKSObjLink = LINK FROM S_OBJECTS WHERE CODE = 'SD_EMPL_DED'

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

IF @LINK is null OR @LINK = 0
BEGIN
	INSERT INTO dbo.EMPL_DED WITH (ROWLOCK) (EMPL_LINK,DED_LINK,DATE1,DATE2,LINK_DGH) 
	VALUES (@EMPL_LINK,@DED_LINK,@Date1,@Date2,@LINK_DGH)
	SELECT @varKSSQLError = @@ERROR, @LINK = @@IDENTITY
	IF @varKSSQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
END
ELSE
BEGIN
	IF  not exists (select link from dbo.EMPL_DED where link = @LINK)
	BEGIN	
		INSERT INTO dbo.EMPL_DED WITH (ROWLOCK) (EMPL_LINK,DED_LINK,DATE1,DATE2,LINK_DGH) 
		VALUES (@EMPL_LINK,@DED_LINK,@Date1,@Date2,@LINK_DGH)
		SELECT @varKSSQLError = @@ERROR, @LINK = @@IDENTITY
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	ELSE 
	BEGIN
		UPDATE dbo.EMPL_DED WITH (ROWLOCK) 
		SET EMPL_LINK = @EMPL_LINK, DED_LINK = @DED_LINK,DATE1 = @Date1,DATE2 = @Date2, LINK_DGH=@LINK_DGH
		WHERE LINK =@LINK
		SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END
END	


SET @varKSEventText = 'Заявленные вычеты сотрудника' 
EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @varKSEventText, @varKSObjLink, 'EMPL_DED',@LINK

WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0




GO


GRANT EXECUTE ON dbo.[SD_EMPL_DED_SAVE] TO PUBLIC

GO


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


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

GO
CREATE PROC [dbo].[SA_PERS_CARD_ESN_15] (@LINK_EMPL INT = NULL, @YEAR INT, @LINK_PERSON INT = NULL)
AS
BEGIN

DECLARE @DEP_LINK INT
SET @DEP_LINK = (SELECT TOP 1 DEP_LINK FROM USER_DEP)

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

IF @LINK_EMPL IS NOT NULL
	SET @LINK_PERSON = ISNULL((SELECT TOP 1 PERS_LINK FROM dbo.EMPL WHERE LINK = @LINK_EMPL),0)

DECLARE @PERSON_CZ INT, @PERSON_RESIDENT int
SELECT  @PERSON_RESIDENT = resident , @PERSON_CZ =  CASE WHEN ltrim(rtrim(c.name)) LIKE ('%иностран%') THEN  1 WHEN ltrim(rtrim(c.name)) LIKE ('%без гражданства%') THEN  2 ELSE 0 end
	FROM person p
	INNER JOIN  citizenship  c ON c.link = p.CITIZ_LINK 
	WHERE p.link = @LINK_PERSON

DECLARE @BYearDate DATETIME, @EndYear DATETIME
SELECT @BYearDate = dbo.ConvertDMY2Date(1,1,@YEAR), @EndYear = dbo.ConvertDMY2Date(31,12,@YEAR)

-- суммы по сотрудникам
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 YEAR(birthdate)<= 1966 THEN 1 ELSE 2 END ) AS FACE_GROUP, 
	dbo.is_invalid(REF_PHYS_PERS,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MONTH_BASE,@YEAR))),
	F.ENVD	,
	SP = isnull(s4.code,'') 
from 
	dbo.SA_ESN_VIEW(@YEAR, 12, @DEP_LINK, @LINK_PERSON) 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 YEAR(birthdate)<= 1966 THEN 1 ELSE 2 END ) AS FACE_GROUP , dbo.is_invalid(GT.PERS_LINK,dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,G.[MONTH],@YEAR))),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]) = @YEAR
	AND LINK_DEP = @DEP_LINK
	AND (P.link = @LINK_PERSON OR @LINK_PERSON = 0)

--Раздел 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]) = @YEAR
	AND LINK_DEP = @DEP_LINK
	AND (GT.PERS_LINK = @LINK_PERSON OR @LINK_PERSON = 0) 
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 #DGH_CJ (PERS_LINK INT, PERIOD_BEGIN DATETIME, LINK_VKR INT, FACE_GROUP TINYINT, SUMMA NUMERIC(18,2))
INSERT INTO #DGH_CJ (PERS_LINK, PERIOD_BEGIN, LINK_VKR, FACE_GROUP, SUMMA)
SELECT PERS_LINK, PERIOD_BEGIN, LINK_VKR, 
	FACE_GROUP = ( CASE WHEN YEAR(p1.birthdate)<= 1966 THEN 1 ELSE 2 END ),
	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) = @YEAR
	AND CJ.LINK_DEP = @DEP_LINK
	AND P.[OBJECT] = 1
	AND (P1.link = @LINK_PERSON OR @LINK_PERSON = 0)	
GROUP BY
	PERS_LINK, PERIOD_BEGIN, LINK_VKR, ( CASE WHEN YEAR(p1.birthdate)<= 1966 THEN 1 ELSE 2 END )	



------	у кого есть расчеты по доп тарифам со спец оценками в заданном периоде
SELECT DISTINCT sd.LINK, DOP = (CASE when S.COD_POS_SPISOK is NOT NULL then 1 else 2 end) , SPO = isnull(s4.code,''), mn.m
INTO #EMPL_DT
FROM DBO.KU_EMPL_PLACING SD
	left JOIN (select * from STAFF WHERE dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,1,@YEAR)) BETWEEN DATE_BEGIN AND DATE_END  or dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,12,@YEAR)) BETWEEN DATE_BEGIN AND DATE_END  ) S ON S.LINK_up = SD.STAFF_HEAD  AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,12,@YEAR )) 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'
	inner join  dbo.months_ex(@BYearDate, @EndYear) mn ON dbo.ConvertDMY2Date(1,mn.m,mn.y)  between s.DATE_BEGIN  AND s.DATE_END
	WHERE
		(S.COD_POS_SPISOK is NOT NULL OR S.COD_POS_SPISOK2 is NOT NULL)
		AND sd.pers_link = @LINK_PERSON
--

-----
SELECT MON, FACE_GROUP, 
	SUMMA_ALL = SUM(SUMMA_ALL), SUMMA_NO = SUM(SUMMA_NO), 
	--SUMMA_ALL_I = SUM(SUMMA_ALL_I), SUMMA_NO_I = SUM(SUMMA_NO_I),
	SUMMA_ALL_E = SUM(SUMMA_ALL_E), SUMMA_NO_E = SUM(SUMMA_NO_E),
	SUMMA_ALL_D1 = SUM(SUMMA_ALL_D1), SUMMA_NO_D1 = SUM(SUMMA_NO_D1), SUMMA_ALL_D2 = SUM(SUMMA_ALL_D2), 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 
(
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), --на которые не начисляются страховые взносы
	( CASE WHEN YEAR(birthdate)<= 1966 THEN 1 ELSE 2 END ) AS FACE_GROUP,
	--SUMMA_ALL_I = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA ELSE 0 END),
	--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),
	SUMMA_ALL_E = SUM(CASE WHEN F.ENVD = 1 /*AND I.LINK IS NULL*/ THEN SUMMA ELSE 0 END),
	SUMMA_NO_E = SUM(CASE WHEN F.ENVD = 1 /*AND I.LINK IS NULL*/ AND (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) THEN SUMMA ELSE 0 END),
	
	---ПО ДОП.ТАРИФАМ С ОСОБЫМИ УСЛОВИЯМИ 
	SUMMA_ALL_D1 = SUM(CASE WHEN p.way_calc = 10 then  SUMMA ELSE 0 end ),
	SUMMA_NO_D1 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and ED.DOP = 1 AND isnull(SPO,'') ='' THEN SUMMA ELSE 0 END),

	SUMMA_ALL_D2 = SUM(CASE WHEN p.way_calc = 11 then  SUMMA ELSE 0 end ),
	SUMMA_NO_D2 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and ED.DOP = 2 and  isnull(SPO,'') ='' THEN SUMMA ELSE 0 END),
	SUM_NO_D1_O4 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='О4'  THEN SUMMA ELSE 0 END),
	SUM_NO_D1_B34 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.4' THEN SUMMA ELSE 0 END),
	SUM_NO_D1_B33 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.3' THEN SUMMA ELSE 0 END),
	SUM_NO_D1_B32 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.2' THEN SUMMA ELSE 0 END),
	SUM_NO_D1_B31 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.1' THEN SUMMA ELSE 0 END),	
	SUM_NO_D2_O4 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='О4' THEN SUMMA ELSE 0 END),
	SUM_NO_D2_B34 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.4' THEN SUMMA ELSE 0 END),
	SUM_NO_D2_B33 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.3' THEN SUMMA ELSE 0 END),
	SUM_NO_D2_B32 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.2' THEN SUMMA ELSE 0 END),
	SUM_NO_D2_B31 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.1' THEN SUMMA ELSE 0 END)
from 
	dbo.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
	INNER JOIN DBO.PERSON P1 ON P1.LINK = E.PERS_LINK
	LEFT JOIN @StBase2 B ON B.LINK = cj.LINK_PAYS
	LEFT JOIN DBO.KU_PERS_INVALID I ON I.PERS_LINK = E.PERS_LINK AND COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate
	LEFT JOIN #EMPL_DT ED ON ED.link = CJ.LINK_EMPL AND ed.m = Month(CJ.PERIOD_BEGIN)
where 	
	Year(period_begin) = @YEAR
	and CJ.LINK_DEP = @DEP_LINK
	and P.[OBJECT] = 1
	AND (P1.link = @LINK_PERSON OR @LINK_PERSON = 0)
GROUP BY
	Month(CJ.PERIOD_BEGIN), ( CASE WHEN YEAR(birthdate)<= 1966 THEN 1 ELSE 2 END )
UNION ALL	
select 
	MON = Month(CJ.PERIOD_BEGIN),
	SUMMA_ALL = SUM(SUMMA),
	SUMMA_NO = SUM(SUMMA - ISNULL(B1.SUMMA_BASE,0)), --на которые не начисляются страховые взносы
	FACE_GROUP,
	--SUMMA_ALL_I = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(CJ.PERIOD_BEGIN) BETWEEN COALESCE(I.DATE_BEGIN,CJ.PERIOD_BEGIN) AND  COALESCE(I.DATE_END,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) THEN SUMMA ELSE 0 END),
	--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(B1.SUMMA_BASE,0) ELSE 0 END),
	SUMMA_ALL_E = SUM(CASE WHEN F.ENVD = 1 /*AND I.LINK IS NULL*/ THEN SUMMA ELSE 0 END),
	SUMMA_NO_E = SUM(CASE WHEN F.ENVD = 1 /*AND I.LINK IS NULL*/ THEN SUMMA - ISNULL(B.SUMMA_BASE,0) ELSE 0 END),
	SUMMA_ALL_D1 =	0,
	SUMMA_NO_D1 = 0,
	SUMMA_ALL_D2 = 0,
	SUMMA_NO_D2 = 0,
	SUM_NO_D1_O4 = 0,
	SUM_NO_D1_B34 = 0,
	SUM_NO_D1_B33 = 0,
	SUM_NO_D1_B32 = 0,
	SUM_NO_D1_B31 = 0,
	SUM_NO_D2_O4 = 0,
	SUM_NO_D2_B34 = 0,
	SUM_NO_D1_B33 = 0,
	SUM_NO_D2_B32 = 0,
	SUM_NO_D2_B31 = 0
from 
	#DGH_CJ CJ
	INNER JOIN dbo.SAL_SFIN F on F.LINK = CJ.LINK_VKR
	--База по договорникам в разрезе ЕНВД
	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 DBO.KU_PERS_INVALID I ON I.PERS_LINK = CJ.PERS_LINK AND COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate
GROUP BY
	Month(CJ.PERIOD_BEGIN), FACE_GROUP
) AS T
GROUP BY 
	MON, FACE_GROUP


--========================================================================================================	
----Облагаемая и необлагаемая суммы в ФСС для договорников 

SELECT 
	MON = MONTH(G.DATE_CALC), 
	SUMMA_NO = SUM(T1.SUMMA),
	--SUMMA_NO_I = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(G.DATE_CALC) BETWEEN COALESCE(I.DATE_BEGIN,G.DATE_CALC) AND COALESCE(I.DATE_END,dbo.DateEndOfMonth(G.DATE_CALC)) THEN T1.SUMMA ELSE 0 END),
	SUMMA_NO_E = SUM(CASE WHEN F.ENVD = 1 /*AND I.LINK IS NULL*/ THEN SUMMA ELSE 0 END)
INTO #DGH_FSS	
FROM 
	dbo.SDOC G
	INNER JOIN dbo.SDOC_DGH_TABLE T1 ON G.LINK = T1.LINK_UP
	INNER JOIN dbo.SAL_SFIN F on F.LINK = T1.LINK_VKR
	LEFT JOIN DBO.KU_PERS_INVALID I ON I.PERS_LINK = T1.PERS_LINK AND COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate	
WHERE
	G.[OBJECT] =(select TOP 1 LINK from s_objects where code = 'DOCUMENTS_DGH')
	and T1.[OBJECT] = 1
	AND G.FLAG_JC = 1
	AND YEAR(G.[DATE]) = @YEAR
	AND LINK_DEP = @DEP_LINK 
	AND (T1.PERS_LINK = @LINK_PERSON OR @LINK_PERSON = 0)
	AND NOT EXISTS ( SELECT T3.* FROM dbo.SDOC_DGH_TABLE T3 INNER JOIN dbo.PAYS P on T3.LINK_PAY = P.LINK
						WHERE T3.[OBJECT] = 3
							AND T3.LINK_UP = T1.LINK_UP AND P.WAY_CALC  = 2 AND T1.LINK_VKR = T3.LINK_VKR)	
GROUP BY 
	MONTH(G.DATE_CALC)
--========================================================================================================

---Начислено пособий за счет средств ФСС
SELECT 
	MON = MONTH(period_begin),
	SUMMA = SUM(SUMMA),
	--SUMMA_I = SUM(CASE WHEN I.LINK IS NOT NULL AND dbo.DateEndOfMonth(period_begin) BETWEEN COALESCE(I.DATE_BEGIN,period_begin) AND COALESCE(I.DATE_END,dbo.DateEndOfMonth(period_begin)) THEN SUMMA ELSE 0 END),
	SUMMA_E = SUM(CASE WHEN F.ENVD = 1 /*AND I.LINK IS NULL*/ THEN SUMMA ELSE 0 END)	
INTO #SUM_FSS
FROM 
	dbo.PAYS P
	INNER JOIN dbo.CALCULATE_JURNAL J ON P.LINK = J.LINK_PAYS
	INNER JOIN dbo.SAL_SFIN F on F.LINK = J.LINK_VKR
	INNER JOIN dbo.EMPL E ON J.LINK_EMPL = E.LINK
	LEFT JOIN DBO.KU_PERS_INVALID I ON I.PERS_LINK = E.PERS_LINK AND COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate		
WHERE
	Year(period_begin) = @YEAR
	and J.LINK_DEP = @DEP_LINK
	and P.[OBJECT] = 1	
	AND J.LINK_EKR = (SELECT TOP 1 LINK FROM KOSGU WHERE CODE = '213')	
	AND E.PERS_LINK = @LINK_PERSON	
GROUP BY 	
	MONTH(period_begin)
--========================================================================================================

CREATE TABLE #RES(CODE_STR VARCHAR(3), SUM01 NUMERIC(18,2), SUM02 NUMERIC(18,2), SUM03 NUMERIC(18,2), SUM04 NUMERIC(18,2), SUM05 NUMERIC(18,2), SUM06 NUMERIC(18,2), SUM07 NUMERIC(18,2), SUM08 NUMERIC(18,2), SUM09 NUMERIC(18,2), SUM10 NUMERIC(18,2), SUM11 NUMERIC(18,2), SUM12 NUMERIC(18,2))

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '100',
	CASE WHEN @PERSON_CZ IN (1,2) THEN ( case when @PERSON_RESIDENT = 3 THEN 1 WHEN @PERSON_RESIDENT = 1 THEN 2 ELSE 0 END ) ELSE 0 END  ,
	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,	0	
---<<<<<< По общему тарифу >>>>>>>>>
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '101',
	ISNULL((SELECT SUM(SUMMA_ALL /*- SUMMA_ALL_I*/ - SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 1), 0),
	ISNULL((SELECT SUM(SUMMA_ALL /*- SUMMA_ALL_I*/ - SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 2), 0),
	ISNULL((SELECT SUM(SUMMA_ALL /*- SUMMA_ALL_I*/ - SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 3), 0),
	ISNULL((SELECT SUM(SUMMA_ALL /*- SUMMA_ALL_I*/ - SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 4), 0),
	ISNULL((SELECT SUM(SUMMA_ALL /*- SUMMA_ALL_I*/ - SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 5), 0),
	ISNULL((SELECT SUM(SUMMA_ALL /*- SUMMA_ALL_I*/ - SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 6), 0),
	ISNULL((SELECT SUM(SUMMA_ALL /*- SUMMA_ALL_I*/ - SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 7), 0),
	ISNULL((SELECT SUM(SUMMA_ALL /*- SUMMA_ALL_I*/ - SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 8), 0),
	ISNULL((SELECT SUM(SUMMA_ALL /*- SUMMA_ALL_I*/ - SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 9), 0),
	ISNULL((SELECT SUM(SUMMA_ALL /*- SUMMA_ALL_I*/ - SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 10), 0),
	ISNULL((SELECT SUM(SUMMA_ALL /*- SUMMA_ALL_I*/ - SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 11), 0),
	ISNULL((SELECT SUM(SUMMA_ALL /*- SUMMA_ALL_I*/ - SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 12), 0)	



INSERT INTO #RES VALUES ('103', 0,0,0,0,0,0,0,0,0,0,0,0)	

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '105',
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 1), 0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 2), 0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 3), 0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 4),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 4), 0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 5),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 5), 0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 6),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 6), 0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 7),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 7), 0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 8),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 8), 0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 9),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 9), 0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 10),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 10), 0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 11),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 11), 0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 12),0)+ ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 12), 0)

INSERT INTO #RES VALUES ('107', 0,0,0,0,0,0,0,0,0,0,0,0)

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '109',
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 1),0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 2),0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 3),0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 4),0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 5),0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 6),0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 7),0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 8),0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 9),0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 10),0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 11),0),
	ISNULL( (SELECT SUM(SUMMA_NO /*- SUMMA_NO_I*/ - SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 12),0)


--Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную ст. 8 Федерального закона
-- ОПС 
DECLARE @LIMIT_OPS NUMERIC(18,2)

SELECT @LIMIT_OPS = MAX(S.PREDEL)
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 AND S.TARIF = 1
WHERE 
	[DATE] = (SELECT TOP 1 [DATE] 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 AND S.TARIF = 1 AND [DATE] < @EndYear ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
	AND s.PREDEL <> 999999999.00 

	
SET @LIMIT_OPS = ISNULL(@LIMIT_OPS,0)



SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OPS ELSE 0 END INTO #SPR_ESN1 FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP 
INSERT INTO #SPR_ESN1 SELECT MON = 2, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 2 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 3, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 3 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 4, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 4 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 5, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 5 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 6, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 6 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 7, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 7 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 8, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 8 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 9, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 9 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 10, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 10 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 11, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 11 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1 SELECT MON = 12, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 12 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP



SELECT DISTINCT T.REF_PHYS_PERS, M.M, T.FACE_GROUP, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2
FROM 
	#SPR_ESN1 T INNER JOIN dbo.months_ex(@BYearDate, @EndYear) 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

-- ФСС
DECLARE @LIMIT_FSS NUMERIC(18,2)

SELECT @LIMIT_FSS = 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 AND S.TARIF = 1
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 S.TARIF = 1 AND [DATE] < @EndYear ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
	AND s.PREDEL <> 999999999.00 
	
SET @LIMIT_FSS = ISNULL(@LIMIT_FSS,0)



SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSS THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_FSS ELSE 0 END INTO #SPR_ESN1_F FROM #SPR_ESN WHERE WAY_CALC = 2 AND MONTH_BASE <= 1 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP 
INSERT INTO #SPR_ESN1_F SELECT MON = 2, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 2 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_F SELECT MON = 3, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 3 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_F SELECT MON = 4, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 4 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_F SELECT MON = 5, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 5 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_F SELECT MON = 6, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 6 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_F SELECT MON = 7, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 7 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_F SELECT MON = 8, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 8 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_F SELECT MON = 9, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 9 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_F SELECT MON = 10, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 10 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_F SELECT MON = 11, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 11 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP
INSERT INTO #SPR_ESN1_F SELECT MON = 12, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSS THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSS ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 12 /*AND I = 1*/ AND E = 0 GROUP BY REF_PHYS_PERS, FACE_GROUP



SELECT DISTINCT T.REF_PHYS_PERS, M.M, T.FACE_GROUP, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
INTO #SPR_ESN2_F
FROM 
	#SPR_ESN1_F T INNER JOIN dbo.months_ex(@BYearDate, @EndYear) M ON 1=1
	LEFT JOIN #SPR_ESN1_F T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
	LEFT JOIN #SPR_ESN1_F 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 #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '111',
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2 WHERE  M = 1) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2 WHERE  M = 2) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2 WHERE  M = 3) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2 WHERE  M = 4) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2 WHERE  M = 5) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2 WHERE  M = 6) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2 WHERE  M = 7) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2 WHERE  M = 8) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2 WHERE  M = 9) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2 WHERE  M = 10) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2 WHERE  M = 11) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2 WHERE  M = 12) ,0)

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '113',
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_F WHERE  M = 1) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_F WHERE  M = 2) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_F WHERE  M = 3) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_F WHERE  M = 4) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_F WHERE  M = 5) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_F WHERE  M = 6) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_F WHERE  M = 7) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_F WHERE  M = 8) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_F WHERE  M = 9) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_F WHERE  M = 10) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_F WHERE  M = 11) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_F WHERE  M = 12) ,0)

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '115',
	ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
	ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
	ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
	ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
	ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
	ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
	ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
	ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
	ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
	ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
	ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
	ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '101'
WHERE R2.CODE_STR IN ('103', '105', '107' )

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '117', SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12 FROM #RES WHERE CODE_STR = '115'

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '119',
	ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
	ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
	ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
	ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
	ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
	ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
	ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
	ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
	ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
	ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
	ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
	ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '101'
WHERE R2.CODE_STR IN ('103', '105', '107', '109')

--exec [SA_PERS_CARD_ESN_15] 324 ,2015, NULL


INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '121',
	ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 1) /*- (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 2)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 2) /*- (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 2)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 3) /*- (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 3)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 4) /*- (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 4) */ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 5) /*- (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 5)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 6) /*- (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 6)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 7) /*- (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 7)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 8)/* - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 8) */,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 9) /*- (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 9)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 10) /* - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 10)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 11)/* - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 11)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 12) /* - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 12)*/ ,0)

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '123',
	ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 1) /*- (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 2)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 2) /*- (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 2)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 3) /*- (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 3)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 4) /*- (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 4) */ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 5) /*- (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 5)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 6) /*- (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 6)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 7) /*- (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 7)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 8)/* - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 8) */,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 9) /*- (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 9)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 10) /* - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 10)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 11)/* - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 11)*/ ,0),
	ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1 s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 /*AND s.I = 1*/ AND s.E = 0 AND s.MONTH_BASE = 12) /* - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 12)*/ ,0)


/*
	ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 1) ,0),
	ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 2) ,0),
	ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 3) ,0),
	ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 4) ,0),
	ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 5) ,0),
	ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 6) ,0),
	ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 7) ,0),
	ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 8) ,0),
	ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 9) ,0),
	ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 10) ,0),
	ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 11) ,0),
	ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2 WHERE  M = 12) ,0)	
*/
--Перечисленно по доп тарифам на ОПС
/*INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '123',
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in(10,11) AND I = 1 AND E = 0 AND MONTH_BASE = 1) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in(10,11) AND I = 1 AND E = 0 AND MONTH_BASE = 2) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in(10,11) AND I = 1 AND E = 0 AND MONTH_BASE = 3) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in(10,11) AND I = 1 AND E = 0 AND MONTH_BASE = 4) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in(10,11) AND I = 1 AND E = 0 AND MONTH_BASE = 5) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in(10,11) AND I = 1 AND E = 0 AND MONTH_BASE = 6) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in(10,11) AND I = 1 AND E = 0 AND MONTH_BASE = 7) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in(10,11) AND I = 1 AND E = 0 AND MONTH_BASE = 8) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in(10,11) AND I = 1 AND E = 0 AND MONTH_BASE = 9) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in(10,11) AND I = 1 AND E = 0 AND MONTH_BASE = 10) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in(10,11) AND I = 1 AND E = 0 AND MONTH_BASE = 11) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in(10,11) AND I = 1 AND E = 0 AND MONTH_BASE = 12) ,0)	
*/
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '125',
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 1) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 2) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 3) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 4) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 5) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 6) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 7) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 8) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 9) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 10) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 11) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 12) ,0)
	
/*INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '127',
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = 1) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = 2) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = 3) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = 4) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = 5) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = 6) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = 7) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = 8) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = 9) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = 10) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = 11) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND I = 1 AND E = 0 AND MONTH_BASE = 12) ,0)
*/
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '127',
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 1) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 2) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 3) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 4) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 5) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 6) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 7) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 8) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 9) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 10) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 11) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 /*AND I = 1*/ AND E = 0 AND MONTH_BASE = 12) ,0)

--INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
--SELECT '128',0,0,0,0, 0,0,0,0,0,0,0,0

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '129',0,0,0,0, 0,0,0,0,0,0,0,0

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '131',0,0,0,0, 0,0,0,0,0,0,0,0

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '133',0,0,0,0, 0,0,0,0,0,0,0,0

/*INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '131',
	ISNULL( (SELECT SUM(SUMMA - SUMMA_I - SUMMA_E) FROM  #SUM_FSS WHERE MON = 1) ,0),
	ISNULL( (SELECT SUM(SUMMA - SUMMA_I - SUMMA_E) FROM  #SUM_FSS WHERE MON = 2) ,0),
	ISNULL( (SELECT SUM(SUMMA - SUMMA_I - SUMMA_E) FROM  #SUM_FSS WHERE MON = 3) ,0),
	ISNULL( (SELECT SUM(SUMMA - SUMMA_I - SUMMA_E) FROM  #SUM_FSS WHERE MON = 4) ,0),
	ISNULL( (SELECT SUM(SUMMA - SUMMA_I - SUMMA_E) FROM  #SUM_FSS WHERE MON = 5) ,0),
	ISNULL( (SELECT SUM(SUMMA - SUMMA_I - SUMMA_E) FROM  #SUM_FSS WHERE MON = 6) ,0),
	ISNULL( (SELECT SUM(SUMMA - SUMMA_I - SUMMA_E) FROM  #SUM_FSS WHERE MON = 7) ,0),
	ISNULL( (SELECT SUM(SUMMA - SUMMA_I - SUMMA_E) FROM  #SUM_FSS WHERE MON = 8) ,0),
	ISNULL( (SELECT SUM(SUMMA - SUMMA_I - SUMMA_E) FROM  #SUM_FSS WHERE MON = 9) ,0),
	ISNULL( (SELECT SUM(SUMMA - SUMMA_I - SUMMA_E) FROM  #SUM_FSS WHERE MON = 10) ,0),
	ISNULL( (SELECT SUM(SUMMA - SUMMA_I - SUMMA_E) FROM  #SUM_FSS WHERE MON = 11) ,0),
	ISNULL( (SELECT SUM(SUMMA - SUMMA_I - SUMMA_E) FROM  #SUM_FSS WHERE MON = 12) ,0)	
*/
/* ---Расходы на цели обязательного социального страхования всего4: сейчас не выводим 
--АДТКТ("_.303.02","_.302.13","ДЛЯ ДАТА>='01.01' И ДАТА<КВАРТАЛ")
CREATE TABLE #RASH_OPS (VID TINYINT, Y INT, MON TINYINT, SUMMA NUMERIC(18,2), Y_P INT, MON_P TINYINT)

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

	INSERT INTO BUFFER (link, id)
	select link, 'DT' from s_accounts where cSinth = '303' and cAnalit = '02'
	
	INSERT INTO BUFFER (link, id)
	select link, 'KT' from s_accounts where cSinth = '302' and cAnalit = '13'

	INSERT INTO #RASH_OPS (VID, Y, MON, SUMMA, Y_P, MON_P)
	SELECT 1,
		Y = CONVERT(INT,YEAR(p.DATE_PROV)),
		MON = CONVERT(INT,MONTH(p.DATE_PROV)),
		P.SUMMA,
		Y_P = CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')),
		MON_P = CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.'))
	from
		dbo.AProvByBufferConditionsShortDate(@BYearDate, @endYear, 'DT', 'KT') P	
		left join dbo.DOCUMENTS_PAY_ADD PA on P.link = PA.link
		left join dbo.g_prov G on G.link = P.link
		LEFT JOIN dbo.KOSGU DG ON DG.LINK = P.DT_EKR
	WHERE
		P.DEP_LINK = @DEP_LINK
		AND
		G.DEP = @DEP_LINK
		--AND
		--CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,2,'.')) <= @M
		--AND
		--CONVERT(INT,DBO.SA_GET_WORD_NUM(PERIOD,3,'.')) = @Y
		AND
		DG.CODE <>'290'

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


INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '129',
	ISNULL( (SELECT SUM(SUMMA) FROM  #RASH_OPS WHERE MON = 1) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #RASH_OPS WHERE MON = 2) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #RASH_OPS WHERE MON = 3) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #RASH_OPS WHERE MON = 4) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #RASH_OPS WHERE MON = 5) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #RASH_OPS WHERE MON = 6) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #RASH_OPS WHERE MON = 7) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #RASH_OPS WHERE MON = 8) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #RASH_OPS WHERE MON = 9) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #RASH_OPS WHERE MON = 10) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #RASH_OPS WHERE MON = 11) ,0),
	ISNULL( (SELECT SUM(SUMMA) FROM  #RASH_OPS WHERE MON = 12) ,0)	
*/
---<<<<<< Конец По общему тарифу >>>>>>>>>


---<<<<<< По тарифу инвалидов >>>>>>>>> ТАРИФ ООИ отменен - расчет по нему закомментируем 

--IF EXISTS(SELECT * FROM #SALARY_SUM2 WHERE SUMMA_ALL_I <> 0)
--	OR EXISTS (SELECT * FROM #SPR_ESN WHERE I = 2 AND (DED_M <> 0 OR INV_M <> 0 OR SUMMA <> 0) )
--BEGIN	

/*INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '300',
	CASE WHEN @PERSON_CZ IN (1,2) THEN ( case when @PERSON_RESIDENT = 3 THEN 1 WHEN @PERSON_RESIDENT =1 THEN 2 ELSE 0 END ) ELSE 0 END  ,
	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,	0	

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '301',
		ISNULL((SELECT SUM(SUMMA_ALL_I) FROM #SALARY_SUM2 WHERE MON = 1), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_I) FROM #SALARY_SUM2 WHERE MON = 2), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_I) FROM #SALARY_SUM2 WHERE MON = 3), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_I) FROM #SALARY_SUM2 WHERE MON = 4), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_I) FROM #SALARY_SUM2 WHERE MON = 5), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_I) FROM #SALARY_SUM2 WHERE MON = 6), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_I) FROM #SALARY_SUM2 WHERE MON = 7), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_I) FROM #SALARY_SUM2 WHERE MON = 8), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_I) FROM #SALARY_SUM2 WHERE MON = 9), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_I) FROM #SALARY_SUM2 WHERE MON = 10), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_I) FROM #SALARY_SUM2 WHERE MON = 11), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_I) FROM #SALARY_SUM2 WHERE MON = 12), 0)	

	INSERT INTO #RES VALUES ('303', 0,0,0,0,0,0,0,0,0,0,0,0)		

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '305',
		ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #SALARY_SUM2 WHERE MON = 1),0) + 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 = 2),0) + 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 = 3),0) + 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 = 4),0) + 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 = 5),0) + 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 = 6),0) + 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 = 7),0) + 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 = 8),0) + 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 = 9),0) + 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 = 10),0) + 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 = 11),0) + 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 = 12),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 12), 0)

	INSERT INTO #RES VALUES ('307', 0,0,0,0,0,0,0,0,0,0,0,0)

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '309',
		ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #DGH_FSS WHERE MON = 1),0),
		ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #DGH_FSS WHERE MON = 2),0),
		ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #DGH_FSS WHERE MON = 3),0),
		ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #DGH_FSS WHERE MON = 4),0),
		ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #DGH_FSS WHERE MON = 5),0),
		ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #DGH_FSS WHERE MON = 6),0),
		ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #DGH_FSS WHERE MON = 7),0),
		ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #DGH_FSS WHERE MON = 8),0),
		ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #DGH_FSS WHERE MON = 9),0),
		ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #DGH_FSS WHERE MON = 10),0),
		ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #DGH_FSS WHERE MON = 11),0),
		ISNULL( (SELECT SUM(SUMMA_NO_I) FROM #DGH_FSS WHERE MON = 12),0)

----Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную ст. 8 Федерального закона
-- ОПС 
	DECLARE @LIMIT_OPSI NUMERIC(18,2)

	SELECT @LIMIT_OPSI = MAX(S.PREDEL)
	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 AND S.TARIF = 3
	WHERE 
		[DATE] = (SELECT TOP 1 [DATE] 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 AND S.TARIF = 3 AND [DATE] < @EndYear ORDER BY [DATE] DESC) 
		AND
		S.PERCENT1 > 0
		AND s.PREDEL <> 999999999.00 

		
	SET @LIMIT_OPSI = ISNULL(@LIMIT_OPSI,0)

	SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSI THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OPSI ELSE 0 END INTO #SPR_ESN1I FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP 
	INSERT INTO #SPR_ESN1I SELECT MON = 2, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 2 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1I SELECT MON = 3, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 3 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1I SELECT MON = 4, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 4 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1I SELECT MON = 5, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 5 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1I SELECT MON = 6, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 6 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1I SELECT MON = 7, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 7 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1I SELECT MON = 8, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 8 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1I SELECT MON = 9, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 9 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1I SELECT MON = 10, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 10 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1I SELECT MON = 11, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 11 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1I SELECT MON = 12, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 12 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP

	SELECT DISTINCT T.REF_PHYS_PERS, M.M, T.FACE_GROUP, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
	INTO #SPR_ESN2I
	FROM 
		#SPR_ESN1I T INNER JOIN dbo.months_ex(@BYearDate, @EndYear) 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



-- ФСС
DECLARE @LIMIT_FSSI NUMERIC(18,2)

SELECT @LIMIT_FSSI = 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 AND S.TARIF = 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 = 2 AND S.TARIF = 1 AND [DATE] < @EndYear ORDER BY [DATE] DESC) 
	AND
	S.PERCENT1 > 0
	AND s.PREDEL <> 999999999.00 


SET @LIMIT_FSSI = ISNULL(@LIMIT_FSSI,0)


	SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSI THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_FSSI ELSE 0 END INTO #SPR_ESN1FI FROM #SPR_ESN WHERE WAY_CALC = 2 AND MONTH_BASE <= 1 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP 
	INSERT INTO #SPR_ESN1FI SELECT MON = 2, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 2 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1FI SELECT MON = 3, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 3 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1FI SELECT MON = 4, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 4 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1FI SELECT MON = 5, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 5 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1FI SELECT MON = 6, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 6 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1FI SELECT MON = 7, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 7 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1FI SELECT MON = 8, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 8 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1FI SELECT MON = 9, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 9 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1FI SELECT MON = 10, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 10 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1FI SELECT MON = 11, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 11 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1FI SELECT MON = 12, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSI THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSI ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 12 AND I = 2 GROUP BY REF_PHYS_PERS, FACE_GROUP

	SELECT DISTINCT T.REF_PHYS_PERS, M.M, T.FACE_GROUP, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
	INTO #SPR_ESN2FI
	FROM 
		#SPR_ESN1FI T INNER JOIN dbo.months_ex(@BYearDate, @EndYear) M ON 1=1
		LEFT JOIN #SPR_ESN1FI T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
		LEFT JOIN #SPR_ESN1FI 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 #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '311',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2I WHERE  M = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2I WHERE  M = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2I WHERE  M = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2I WHERE  M = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2I WHERE  M = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2I WHERE  M = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2I WHERE  M = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2I WHERE  M = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2I WHERE  M = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2I WHERE  M = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2I WHERE  M = 12) ,0)

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '313',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2FI WHERE  M = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2FI WHERE  M = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2FI WHERE  M = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2FI WHERE  M = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2FI WHERE  M = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2FI WHERE  M = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2FI WHERE  M = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2FI WHERE  M = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2FI WHERE  M = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2FI WHERE  M = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2FI WHERE  M = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2FI WHERE  M = 12) ,0)		

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '315',
		ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
		ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
		ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
		ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
		ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
		ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
		ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
		ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
		ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
		ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
		ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
		ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '301'
	WHERE R2.CODE_STR IN ('303', '305', '307')

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '317', SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12 FROM #RES WHERE CODE_STR = '315'

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '319',
		ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
		ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
		ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
		ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
		ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
		ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
		ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
		ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
		ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
		ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
		ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
		ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '301'
	WHERE R2.CODE_STR IN ('303', '305', '307', '309')


	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '321',
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 1),0),
		--ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 1) - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 2),0),
		--ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 2) - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 3),0),
		--ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 3) - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 4),0),
		--ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 4) - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 5),0),
		--ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 5) - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 6),0),
		--ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 6) - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 7),0),
		--ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 7) - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 8),0),
		--ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 8) - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 9),0),
		--ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 9) - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 10),0),
		--ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 10) - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 11),0),
		--ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 11) - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 12),0)
		--ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 6 AND I = 2 AND MONTH_BASE = 12) - (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1),0)

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '323',
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 1),0),
		--ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 2),0),
		--ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 3),0),
		--ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 4),0),
		--ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 5),0),
		--ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 6),0),
		--ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 7),0),
		--ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 8),0),
		--ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 9),0),
		--ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 10),0),
		--ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 11),0),
		--ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1I s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6 AND s.I = 2 AND s.E = 0 AND s.MONTH_BASE = 12),0)
		--ISNULL( (SELECT SUM(ISNULL(SUMMA,0)) FROM  #SPR_ESN2I WHERE  M = 1) ,0)	

/*	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '323',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND I = 2 AND MONTH_BASE = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND I = 2 AND MONTH_BASE = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND I = 2 AND MONTH_BASE = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND I = 2 AND MONTH_BASE = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND I = 2 AND MONTH_BASE = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND I = 2 AND MONTH_BASE = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND I = 2 AND MONTH_BASE = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND I = 2 AND MONTH_BASE = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND I = 2 AND MONTH_BASE = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND I = 2 AND MONTH_BASE = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND I = 2 AND MONTH_BASE = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND I = 2 AND MONTH_BASE = 12) ,0)	
*/

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '325',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND I = 2 AND MONTH_BASE = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND I = 2 AND MONTH_BASE = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND I = 2 AND MONTH_BASE = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND I = 2 AND MONTH_BASE = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND I = 2 AND MONTH_BASE = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND I = 2 AND MONTH_BASE = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND I = 2 AND MONTH_BASE = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND I = 2 AND MONTH_BASE = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND I = 2 AND MONTH_BASE = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND I = 2 AND MONTH_BASE = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND I = 2 AND MONTH_BASE = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND I = 2 AND MONTH_BASE = 12) ,0)
	
	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '327',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 12) ,0)

/*	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '329',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND I = 2 AND MONTH_BASE = 12) ,0)

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '331',
		ISNULL( (SELECT SUM(SUMMA_I) FROM  #SUM_FSS WHERE MON = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA_I) FROM  #SUM_FSS WHERE MON = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA_I) FROM  #SUM_FSS WHERE MON = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA_I) FROM  #SUM_FSS WHERE MON = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA_I) FROM  #SUM_FSS WHERE MON = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA_I) FROM  #SUM_FSS WHERE MON = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA_I) FROM  #SUM_FSS WHERE MON = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA_I) FROM  #SUM_FSS WHERE MON = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA_I) FROM  #SUM_FSS WHERE MON = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA_I) FROM  #SUM_FSS WHERE MON = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA_I) FROM  #SUM_FSS WHERE MON = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA_I) FROM  #SUM_FSS WHERE MON = 12) ,0)	
*/
--END		
*/
---<<<<<< Конец По тарифу инвалидов >>>>>>>>>


---<<<<<< По тарифу ЕНВД>>>>>>>>>
--IF EXISTS(SELECT * FROM #SALARY_SUM2 WHERE SUMMA_ALL_E <> 0)
--	OR EXISTS (SELECT * FROM #SPR_ESN WHERE E = 1 AND (DED_M <> 0 OR INV_M <> 0 OR SUMMA <> 0) )
--BEGIN
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '500',
	CASE WHEN @PERSON_CZ IN (1,2) THEN ( case when @PERSON_RESIDENT = 3 THEN 1 WHEN @PERSON_RESIDENT =1 THEN 2 ELSE 0 END ) ELSE 0 END  ,
	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,	0

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '501',
		ISNULL((SELECT SUM(SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 1), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 2), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 3), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 4), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 5), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 6), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 7), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 8), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 9), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 10), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 11), 0),
		ISNULL((SELECT SUM(SUMMA_ALL_E) FROM #SALARY_SUM2 WHERE MON = 12), 0)	
		
	INSERT INTO #RES VALUES ('503', 0,0,0,0,0,0,0,0,0,0,0,0)	

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '505',
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 1),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 1), 0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 2),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 2), 0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 3),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 3), 0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 4),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 4), 0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 5),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 5), 0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 6),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 6), 0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 7),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 7), 0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 8),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 8), 0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 9),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 9), 0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 10),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 10), 0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 11),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 11), 0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #SALARY_SUM2 WHERE MON = 12),0) + ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN WHERE WAY_CALC = 6 AND E = 1 AND MONTH_BASE = 12), 0)

	INSERT INTO #RES VALUES ('507', 0,0,0,0,0,0,0,0,0,0,0,0)

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '509',
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 1),0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 2),0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 3),0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 4),0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 5),0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 6),0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 7),0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 8),0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 9),0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 10),0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 11),0),
		ISNULL( (SELECT SUM(SUMMA_NO_E) FROM #DGH_FSS WHERE MON = 12),0)

	--Суммы, превышающие предельную величину базы для начисления страховых взносов, установленную ст. 8 Федерального закона
	-- ОПС 
	DECLARE @LIMIT_OPSE NUMERIC(18,2)

	SELECT @LIMIT_OPSE = MAX(S.PREDEL)
	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 AND S.TARIF = 2
	WHERE 
		[DATE] = (SELECT TOP 1 [DATE] 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 AND S.TARIF = 2 AND [DATE] < @EndYear ORDER BY [DATE] DESC) 
		AND
		S.PERCENT1 > 0
		AND s.PREDEL <> 999999999.00 

		
	SET @LIMIT_OPSE = ISNULL(@LIMIT_OPSE,0)

	SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSE THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_OPSE ELSE 0 END INTO #SPR_ESN1E FROM #SPR_ESN WHERE WAY_CALC = 6 AND MONTH_BASE <= 1 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP 
	INSERT INTO #SPR_ESN1E SELECT MON = 2, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 2 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1E SELECT MON = 3, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 3 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1E SELECT MON = 4, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 4 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1E SELECT MON = 5, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 5 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1E SELECT MON = 6, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 6 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1E SELECT MON = 7, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 7 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1E SELECT MON = 8, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 8 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1E SELECT MON = 9, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 9 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1E SELECT MON = 10, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 10 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1E SELECT MON = 11, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 11 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1E SELECT MON = 12, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_OPSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_OPSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 6 AND  MONTH_BASE <= 12 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP

	SELECT DISTINCT T.REF_PHYS_PERS, M.M, T.FACE_GROUP, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
	INTO #SPR_ESN2E
	FROM 
		#SPR_ESN1E T INNER JOIN dbo.months_ex(@BYearDate, @EndYear) M ON 1=1
		LEFT JOIN #SPR_ESN1E T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
		LEFT JOIN #SPR_ESN1E 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

	-- FSS
	DECLARE @LIMIT_FSSE NUMERIC(18,2)

	SELECT @LIMIT_FSSE = MAX(S.PREDEL)
	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 AND S.TARIF = 2
	WHERE 
		[DATE] = (SELECT TOP 1 [DATE] 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 AND S.TARIF = 2 AND [DATE] < @EndYear ORDER BY [DATE] DESC) 
		AND
		S.PERCENT1 > 0
		AND s.PREDEL <> 999999999.00 

		
	SET @LIMIT_FSSE = ISNULL(@LIMIT_FSSE,0)

	SELECT MON = 1, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSE THEN (SUM(SUMMA_BASE) - SUM(DED_M) - SUM(INV_M)) - @LIMIT_FSSE ELSE 0 END INTO #SPR_ESN1_FE FROM #SPR_ESN WHERE WAY_CALC = 2 AND MONTH_BASE <= 1 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP 
	INSERT INTO #SPR_ESN1_FE SELECT MON = 2, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 2 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1_FE SELECT MON = 3, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 3 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1_FE SELECT MON = 4, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 4 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1_FE SELECT MON = 5, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 5 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1_FE SELECT MON = 6, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 6 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1_FE SELECT MON = 7, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 7 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1_FE SELECT MON = 8, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 8 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1_FE SELECT MON = 9, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 9 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1_FE SELECT MON = 10, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 10 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1_FE SELECT MON = 11, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 11 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP
	INSERT INTO #SPR_ESN1_FE SELECT MON = 12, REF_PHYS_PERS, FACE_GROUP, SUMMA = CASE WHEN (SUM(SUMMA_BASE) - SUM(DED_M)) > @LIMIT_FSSE THEN (SUM(SUMMA_BASE) - SUM(DED_M)) - @LIMIT_FSSE ELSE 0 END FROM #SPR_ESN WHERE WAY_CALC = 2 AND  MONTH_BASE <= 12 AND E = 1 GROUP BY REF_PHYS_PERS, FACE_GROUP

	SELECT DISTINCT T.REF_PHYS_PERS, M.M, T.FACE_GROUP, SUMMA = ISNULL(T1.SUMMA,0) - ISNULL(T2.SUMMA,0)
	INTO #SPR_ESN2_FE
	FROM 
		#SPR_ESN1_FE T INNER JOIN dbo.months_ex(@BYearDate, @EndYear) M ON 1=1
		LEFT JOIN #SPR_ESN1_FE T1 ON T1.REF_PHYS_PERS = T.REF_PHYS_PERS AND T1.MON = M.M
		LEFT JOIN #SPR_ESN1_FE 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 #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '511',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2E WHERE  M = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2E WHERE  M = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2E WHERE  M = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2E WHERE  M = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2E WHERE  M = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2E WHERE  M = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2E WHERE  M = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2E WHERE  M = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2E WHERE  M = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2E WHERE  M = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2E WHERE  M = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2E WHERE  M = 12) ,0)

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '513',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_FE WHERE  M = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_FE WHERE  M = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_FE WHERE  M = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_FE WHERE  M = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_FE WHERE  M = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_FE WHERE  M = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_FE WHERE  M = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_FE WHERE  M = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_FE WHERE  M = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_FE WHERE  M = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_FE WHERE  M = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN2_FE WHERE  M = 12) ,0)		

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '515',
		ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
		ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
		ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
		ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
		ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
		ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
		ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
		ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
		ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
		ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
		ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
		ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '501'
	WHERE R2.CODE_STR IN ('503', '505', '507')

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '517', SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12 FROM #RES WHERE CODE_STR = '515'

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '519',
		ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
		ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
		ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
		ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
		ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
		ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
		ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
		ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
		ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
		ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
		ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
		ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '501'
	WHERE R2.CODE_STR IN ('503', '505', '507', '509')

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '521',
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 1),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 2),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 3),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 4),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 5),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 6),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 7),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 8),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 9),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 10),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 11),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) = 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 12),0)


	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '523',
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 1),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 2),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 3),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 4),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 5),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 6),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 7),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 8),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 9),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 10),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 11),0),
		ISNULL( (SELECT (case when sum(S1.SUMMA) <> 0 then SUM(s.SUMMA) else 0 end) FROM  #SPR_ESN s inner join #SPR_ESN1E s1 on s1.mon =s.MONTH_BASE and s1.face_group= s.face_group  WHERE s.WAY_CALC = 6  AND s.E = 1 AND s.MONTH_BASE = 12),0)
	/*INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '521',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND E = 1 AND MONTH_BASE = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND E = 1 AND MONTH_BASE = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND E = 1 AND MONTH_BASE = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND E = 1 AND MONTH_BASE = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND E = 1 AND MONTH_BASE = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND E = 1 AND MONTH_BASE = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND E = 1 AND MONTH_BASE = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND E = 1 AND MONTH_BASE = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND E = 1 AND MONTH_BASE = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND E = 1 AND MONTH_BASE = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND E = 1 AND MONTH_BASE = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 7 AND E = 1 AND MONTH_BASE = 12) ,0)	

	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '523',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND E = 1 AND MONTH_BASE = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND E = 1 AND MONTH_BASE = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND E = 1 AND MONTH_BASE = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND E = 1 AND MONTH_BASE = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND E = 1 AND MONTH_BASE = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND E = 1 AND MONTH_BASE = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND E = 1 AND MONTH_BASE = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND E = 1 AND MONTH_BASE = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND E = 1 AND MONTH_BASE = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND E = 1 AND MONTH_BASE = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND E = 1 AND MONTH_BASE = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC in (10,11) AND E = 1 AND MONTH_BASE = 12) ,0)	
*/
	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '525',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND E = 1 AND MONTH_BASE = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND E = 1 AND MONTH_BASE = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND E = 1 AND MONTH_BASE = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND E = 1 AND MONTH_BASE = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND E = 1 AND MONTH_BASE = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND E = 1 AND MONTH_BASE = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND E = 1 AND MONTH_BASE = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND E = 1 AND MONTH_BASE = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND E = 1 AND MONTH_BASE = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND E = 1 AND MONTH_BASE = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND E = 1 AND MONTH_BASE = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC IN(3,4) AND E = 1 AND MONTH_BASE = 12) ,0)
		
/*	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '527',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND E = 1 AND MONTH_BASE = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND E = 1 AND MONTH_BASE = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND E = 1 AND MONTH_BASE = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND E = 1 AND MONTH_BASE = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND E = 1 AND MONTH_BASE = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND E = 1 AND MONTH_BASE = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND E = 1 AND MONTH_BASE = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND E = 1 AND MONTH_BASE = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND E = 1 AND MONTH_BASE = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND E = 1 AND MONTH_BASE = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND E = 1 AND MONTH_BASE = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 4 AND E = 1 AND MONTH_BASE = 12) ,0)
*/
	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '527',
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND E = 1 AND MONTH_BASE = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND E = 1 AND MONTH_BASE = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND E = 1 AND MONTH_BASE = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND E = 1 AND MONTH_BASE = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND E = 1 AND MONTH_BASE = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND E = 1 AND MONTH_BASE = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND E = 1 AND MONTH_BASE = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND E = 1 AND MONTH_BASE = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND E = 1 AND MONTH_BASE = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND E = 1 AND MONTH_BASE = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND E = 1 AND MONTH_BASE = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA) FROM  #SPR_ESN WHERE WAY_CALC = 2 AND E = 1 AND MONTH_BASE = 12) ,0)
/*
	INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '531',
		ISNULL( (SELECT SUM(SUMMA_E) FROM  #SUM_FSS WHERE MON = 1) ,0),
		ISNULL( (SELECT SUM(SUMMA_E) FROM  #SUM_FSS WHERE MON = 2) ,0),
		ISNULL( (SELECT SUM(SUMMA_E) FROM  #SUM_FSS WHERE MON = 3) ,0),
		ISNULL( (SELECT SUM(SUMMA_E) FROM  #SUM_FSS WHERE MON = 4) ,0),
		ISNULL( (SELECT SUM(SUMMA_E) FROM  #SUM_FSS WHERE MON = 5) ,0),
		ISNULL( (SELECT SUM(SUMMA_E) FROM  #SUM_FSS WHERE MON = 6) ,0),
		ISNULL( (SELECT SUM(SUMMA_E) FROM  #SUM_FSS WHERE MON = 7) ,0),
		ISNULL( (SELECT SUM(SUMMA_E) FROM  #SUM_FSS WHERE MON = 8) ,0),
		ISNULL( (SELECT SUM(SUMMA_E) FROM  #SUM_FSS WHERE MON = 9) ,0),
		ISNULL( (SELECT SUM(SUMMA_E) FROM  #SUM_FSS WHERE MON = 10) ,0),
		ISNULL( (SELECT SUM(SUMMA_E) FROM  #SUM_FSS WHERE MON = 11) ,0),
		ISNULL( (SELECT SUM(SUMMA_E) FROM  #SUM_FSS WHERE MON = 12) ,0)	
*/--END		
---<<<<<< Конец По общему тарифу >>>>>>>>>

----------------------------------------------
-------<<<<< Суммы по ДОП тарифам по категориям вредности >>>>>> 

/********суммы выплат и иных вознаграждений в пользу застрахованного лица, занятого на соответствующих видах работ, указанных***********/
/*******в подпунктах 1—18 пункта 1 статьи 27 Федерального закона от 17 декабря 2001 года № 173-ФЗ «О трудовых пенсиях в Российской Федерации» ******/
----Выплаты по всем видам работ
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '600',
	CASE WHEN @PERSON_CZ IN (1,2) THEN ( case when @PERSON_RESIDENT = 3 THEN 1 WHEN @PERSON_RESIDENT = 1 THEN 2 ELSE 0 END ) ELSE 0 END  ,
	0,	0,	0,	0,	0,	0,	0,	0,	0,	0,	0
--- Выплаты в соответствии с ч. 1-2 ст. 7 212-ФЗ
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '601',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUMMA_NO_D2) +  SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 1),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUMMA_NO_D2) +  SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 2),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUMMA_NO_D2) +  SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 3),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUMMA_NO_D2) +  SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 4),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUMMA_NO_D2) +  SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 5),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUMMA_NO_D2) +  SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 6),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUMMA_NO_D2) +  SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 7),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUMMA_NO_D2) +  SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 8),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUMMA_NO_D2) +  SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 9),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUMMA_NO_D2) +  SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUMMA_NO_D2) +  SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUMMA_NO_D2) +  SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 12),0))
FROM #SPR_ESN
WHERE WAY_CALC IN (10,11)


-- Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 8
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '603', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

--Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 9
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '605',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 2 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
	    Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 7 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 8 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 9 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) + SUM(SUM_NO_D1_O4) + SUM(SUM_NO_D1_B34) + SUM(SUM_NO_D1_B33)+ SUM(SUM_NO_D1_B32)+ SUM(SUM_NO_D1_B31) + SUM(SUM_NO_D2_O4) + SUM(SUM_NO_D2_B34) + SUM(SUM_NO_D2_B33)+ SUM(SUM_NO_D2_B32)+ SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 12 ),0))
FROM #SPR_ESN
WHERE WAY_CALC IN (10,11)

----База для начисления взносов на доплату к пенсии
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '607',
		ISNULL( (R1.SUM01) - (R2.SUM01)- (R3.SUM01) ,0),
		ISNULL( (R1.SUM02) - (R2.SUM02)- (R3.SUM02) ,0),
		ISNULL( (R1.SUM03) - (R2.SUM03)- (R3.SUM03) ,0),
		ISNULL( (R1.SUM04) - (R2.SUM04)- (R3.SUM04) ,0),
		ISNULL( (R1.SUM05) - (R2.SUM05)- (R3.SUM05) ,0),
		ISNULL( (R1.SUM06) - (R2.SUM06)- (R3.SUM06) ,0),
		ISNULL( (R1.SUM07) - (R2.SUM07)- (R3.SUM07) ,0),
		ISNULL( (R1.SUM08) - (R2.SUM08)- (R3.SUM08) ,0),
		ISNULL( (R1.SUM09) - (R2.SUM09)- (R3.SUM09) ,0),
		ISNULL( (R1.SUM10) - (R2.SUM10)- (R3.SUM10) ,0),
		ISNULL( (R1.SUM11) - (R2.SUM11)- (R3.SUM11) ,0),
		ISNULL( (R1.SUM12) - (R2.SUM12)- (R3.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '601'
	INNER JOIN #RES R3 ON R2.CODE_STR = '603'
	WHERE R3.CODE_STR IN ('605')

INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '609', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '611', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

---------------------
------ДОП 1
-----Выплаты по видам работ, указанным в подпункте 1 пункта 1 статьи 27 Федерального закона от 17.12.2001 г. № 173-ФЗ, по непрошедшим специальной оценки условий труда рабочим местам
--- Выплаты в соответствии с ч. 1-2 ст. 7 212-ФЗ
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '613',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 1),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA_BASE ELSE 0 END),0)+ ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 2),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 3),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 4),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 5),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 6),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 7),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 8),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 9),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA_BASE ELSE 0 END),0)+ ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 12),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP = ''

-- Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 8
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '615', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

--Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 9
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '617',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 1),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 2),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 3),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 4),0)),
	    Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 5),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 6),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 7),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 8),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 9),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN DED_M + INV_M ELSE 0 END),0)+ ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D1) FROM #SALARY_SUM2 WHERE MON = 12),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP = ''

--База для начисления страховых взносов																														
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '619',
		ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
		ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
		ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
		ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
		ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
		ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
		ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
		ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
		ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
		ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
		ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
		ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '613'
	WHERE R2.CODE_STR IN ('617')

---***Начислено страховых взносов
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT
	'621',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA ELSE 0 END),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP = ''

------------------------------------------------------------
-----Выплаты по видам работ по рабочим местам с классом условий труда О4 (опасные)
--- Выплаты в соответствии с ч. 1-2 ст. 7 212-ФЗ
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '623',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 2),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 7),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 8),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 9),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 12),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP = 'О4'

-- Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 8
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '625', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

--Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 9
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '627',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 2 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
	    Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 7 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 8 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 9 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_O4) FROM #SALARY_SUM2 WHERE MON = 12 ),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP = 'О4'

--База для начисления страховых взносов																														
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '629',
		ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
		ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
		ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
		ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
		ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
		ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
		ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
		ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
		ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
		ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
		ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
		ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '623'
	WHERE R2.CODE_STR IN ('627')

---***Начислено страховых взносов
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT
	'631',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA ELSE 0 END),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP = 'О4'
---------------------------------------------------------------------------------
/********Выплаты по видам работ, указанным в подпункте 1 пункта 1 статьи 27 Федерального закона от 17.12.2001 г. № 173-ФЗ, по рабочим местам с классом условий труда В3.4 (вредные 3.4)**********/
--- Выплаты в соответствии с ч. 1-2 ст. 7 212-ФЗ
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '633',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 2),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 7),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 8),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA_BASE ELSE 0 END) ,0)+ ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 9),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA_BASE ELSE 0 END) ,0)+ ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 12),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP = 'В3.4'

-- Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 8
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '635', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

--Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 9
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '637',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 2 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
	    Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 7 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 8 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 9 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B34) FROM #SALARY_SUM2 WHERE MON = 12 ),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP ='В3.4'

--База для начисления страховых взносов																														
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '639',
		ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
		ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
		ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
		ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
		ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
		ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
		ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
		ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
		ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
		ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
		ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
		ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '633'
	WHERE R2.CODE_STR IN ('637')

---***Начислено страховых взносов
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT
	'641',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA ELSE 0 END),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP = 'В3.4'

/*******Выплаты по видам работ, указанным в подпункте 1 пункта 1 статьи 27 Федерального закона от 17.12.2001 г. № 173-ФЗ, по рабочим местам с классом условий труда В3.3 (вредные 3.3)  ******/
--- Выплаты в соответствии с ч. 1-2 ст. 7 212-ФЗ
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '643',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 2),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 7),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 8),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 9),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 12),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP = 'В3.3'	

-- Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 8
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '645', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

--Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 9
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '647',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 2 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
	    Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 7 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 8 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 9 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B33) FROM #SALARY_SUM2 WHERE MON = 12 ),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP ='В3.3'	

--База для начисления страховых взносов																														
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '649',
		ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
		ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
		ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
		ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
		ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
		ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
		ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
		ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
		ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
		ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
		ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
		ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '643'
	WHERE R2.CODE_STR IN ('647')

---***Начислено страховых взносов
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT
	'651',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA ELSE 0 END),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP = 'В3.3'	

/********Выплаты по видам работ, указанным в подпункте 1 пункта 1 статьи 27 Федерального закона от 17.12.2001 г. № 173-ФЗ, по рабочим местам с классом условий труда В3.2 (вредные 3.2)**********/
--- Выплаты в соответствии с ч. 1-2 ст. 7 212-ФЗ
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '653',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 2),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 7),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 8),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 9),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 12),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP = 'В3.2'	

-- Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 8
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '655', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

--Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 9
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '657',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN DED_M + INV_M ELSE 0 END) ,0)+ ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 2 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
	    Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 7 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 8 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 9 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B32) FROM #SALARY_SUM2 WHERE MON = 12 ),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP ='В3.2'	

--База для начисления страховых взносов																														
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '659',
		ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
		ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
		ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
		ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
		ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
		ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
		ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
		ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
		ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
		ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
		ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
		ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '653'
	WHERE R2.CODE_STR IN ('657')

---***Начислено страховых взносов
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT
	'661',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA ELSE 0 END),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP = 'В3.2'	

/*******Выплаты по видам работ, указанным в подпункте 1 пункта 1 статьи 27 Федерального закона от 17.12.2001 г. № 173-ФЗ, по рабочим местам с классом условий труда В3.1 (вредные 3.1) *****/
--- Выплаты в соответствии с ч. 1-2 ст. 7 212-ФЗ
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '663',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 2),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 7),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 8),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 9),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 12),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP = 'В3.1'	

-- Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 8
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '665', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

--Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 9
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '667',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 2 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
	    Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 7 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 8 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 9 ),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D1_B31) FROM #SALARY_SUM2 WHERE MON = 12 ),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP ='В3.1'	

--База для начисления страховых взносов																														
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '669',
		ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
		ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
		ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
		ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
		ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
		ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
		ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
		ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
		ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
		ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
		ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
		ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '663'
	WHERE R2.CODE_STR IN ('667')

---***Начислено страховых взносов
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT
	'671',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA ELSE 0 END),0))
FROM #SPR_ESN
WHERE WAY_CALC = 10 AND SP = 'В3.1'	

----------------------------------------
------------Доп 2
-----Выплаты по видам работ, указанным в подпунктах 2—18 пункта 1 статьи 27 Федерального закона от 17.12.2001 г. № 173-ФЗ, по непрошедшим специальной оценки условий труда рабочим местам
--- Выплаты в соответствии с ч. 1-2 ст. 7 212-ФЗ

INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '701',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 1),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 2),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 3),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 4),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 5),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 6),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 7),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 8),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 9),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA_BASE ELSE 0 END),0)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA_BASE ELSE 0 END),0)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA_BASE ELSE 0 END),0)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 12),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP = ''

-- Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 8
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '703', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

--Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 9
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '705',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 1),0) ),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 1),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 1),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 1),0)),
	    Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 1),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 1),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 1),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 1),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 1),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN DED_M + INV_M ELSE 0 END),0)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 1),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN DED_M + INV_M ELSE 0 END),0)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 1),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN DED_M + INV_M ELSE 0 END),0)+ ISNULL( (SELECT SUM(SUMMA_NO_D2) FROM #SALARY_SUM2 WHERE MON = 1),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP = ''

--База для начисления страховых взносов																														
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '707',
		ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
		ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
		ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
		ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
		ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
		ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
		ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
		ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
		ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
		ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
		ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
		ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '701'
	WHERE R2.CODE_STR IN ('705')

---***Начислено страховых взносов
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT
	'709',
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL( SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA ELSE 0 END),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP = ''

------------------------------------------------------------
-----Выплаты по видам работ по рабочим местам с классом условий труда О4 (опасные)
--- Выплаты в соответствии с ч. 1-2 ст. 7 212-ФЗ
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '711',
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 2),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 7),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 8),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 9),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 12),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP = 'О4'

-- Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 8
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '713', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

--Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 9
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '715',
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 1 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 2 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 2 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 3 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 4 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
	    Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 5 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 6 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 7 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 7 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 8 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 8 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 9 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 9 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 10 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 11 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 12 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_O4) FROM #SALARY_SUM2 WHERE MON = 12 ),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP = 'О4'

--База для начисления страховых взносов																														
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '717',
		ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
		ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
		ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
		ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
		ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
		ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
		ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
		ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
		ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
		ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
		ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
		ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '711'
	WHERE R2.CODE_STR IN ('715')

---***Начислено страховых взносов
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT
	'719',
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA ELSE 0 END),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP = 'О4'
---------------------------------------------------------------------------------
/********Выплаты по видам работ, указанным в подпункте 2—18 пункта 1 статьи 27 Федерального закона от 17.12.2001 г. № 173-ФЗ, по рабочим местам с классом условий труда В3.4 (вредные 3.4)**********/
--- Выплаты в соответствии с ч. 1-2 ст. 7 212-ФЗ
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '721',
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 2),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 7),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 8),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 9),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 12),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP = 'В3.4'

-- Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 8
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '723', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

--Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 9
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '725',
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 1 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 2 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 2 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 3 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 4 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
	    Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 5 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 6 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 7 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 7 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 8 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 8 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 9 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 9 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 10 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 11 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 12 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B34) FROM #SALARY_SUM2 WHERE MON = 12 ),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP ='В3.4'

--База для начисления страховых взносов																														
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '727',
		ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
		ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
		ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
		ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
		ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
		ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
		ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
		ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
		ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
		ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
		ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
		ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '721'
	WHERE R2.CODE_STR IN ('725')

---***Начислено страховых взносов
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT
	'729',
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA ELSE 0 END),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP = 'В3.4'

/*******Выплаты по видам работ, указанным в подпункте 2—18 пункта 1 статьи 27 Федерального закона от 17.12.2001 г. № 173-ФЗ, по рабочим местам с классом условий труда В3.3 (вредные 3.3)  ******/
--- Выплаты в соответствии с ч. 1-2 ст. 7 212-ФЗ
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '731',
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 2),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 7),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 8),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 9),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 12),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP = 'В3.3'	

-- Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 8
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '733', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

--Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 9
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '735',
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 1 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 2 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 2 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 3 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 4 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
	    Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 5 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 6 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 7 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 7 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 8 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 8 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 9 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 9 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 10 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 11 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 12 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B33) FROM #SALARY_SUM2 WHERE MON = 12 ),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP ='В3.3'	

--База для начисления страховых взносов																														
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '737',
		ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
		ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
		ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
		ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
		ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
		ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
		ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
		ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
		ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
		ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
		ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
		ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '731'
	WHERE R2.CODE_STR IN ('735')

---***Начислено страховых взносов
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT
	'739',
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA ELSE 0 END),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP = 'В3.3'	

/********Выплаты по видам работ, указанным в подпункте 2—18 пункта 1 статьи 27 Федерального закона от 17.12.2001 г. № 173-ФЗ, по рабочим местам с классом условий труда В3.2 (вредные 3.2)**********/
--- Выплаты в соответствии с ч. 1-2 ст. 7 212-ФЗ
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '741',
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 2),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 7),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 8),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 9),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 12),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP = 'В3.2'	

-- Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 8
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '743', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

--Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 9
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '745',
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 1 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 2 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 2 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 3 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 4 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
	    Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 5 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 6 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 7 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 7 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 8 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 8 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 9 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 9 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 10 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 11 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 12 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B32) FROM #SALARY_SUM2 WHERE MON = 12 ),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP ='В3.2'	

--База для начисления страховых взносов																														
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '747',
		ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
		ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
		ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
		ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
		ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
		ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
		ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
		ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
		ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
		ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
		ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
		ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '741'
	WHERE R2.CODE_STR IN ('745')

---***Начислено страховых взносов
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT
	'749',
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA ELSE 0 END),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA ELSE 0 END),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP = 'В3.2'	

/*******Выплаты по видам работ, указанным в подпункте 2—18 пункта 1 статьи 27 Федерального закона от 17.12.2001 г. № 173-ФЗ, по рабочим местам с классом условий труда В3.1 (вредные 3.1) *****/
--- Выплаты в соответствии с ч. 1-2 ст. 7 212-ФЗ
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '751',
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 2),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 7),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 8),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 9),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA_BASE ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 12),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP = 'В3.1'	

-- Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 8
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '753', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0

--Из них суммы,не подлежащие обложению в соответствии с 212-ФЗ ст. 9
INSERT INTO #RES(CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '755',
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 1 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 1 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 2 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 2 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 3 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 3 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 4 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 4 ),0)),
	    Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 5 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 5 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 6 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 6 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 7 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 7 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 8 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 8 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 9 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 9 ),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 10 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 10),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 11 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 11),0)),
		Convert(numeric(18,2),ISNULL(SUM(CASE WHEN MONTH_BASE = 12 THEN DED_M + INV_M ELSE 0 END),0) + ISNULL( (SELECT SUM(SUM_NO_D2_B31) FROM #SALARY_SUM2 WHERE MON = 12 ),0))
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP ='В3.1'	

--База для начисления страховых взносов																														
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
	SELECT '757',
		ISNULL( MIN(R1.SUM01) - SUM(R2.SUM01) ,0),
		ISNULL( MIN(R1.SUM02) - SUM(R2.SUM02) ,0),
		ISNULL( MIN(R1.SUM03) - SUM(R2.SUM03) ,0),
		ISNULL( MIN(R1.SUM04) - SUM(R2.SUM04) ,0),
		ISNULL( MIN(R1.SUM05) - SUM(R2.SUM05) ,0),
		ISNULL( MIN(R1.SUM06) - SUM(R2.SUM06) ,0),
		ISNULL( MIN(R1.SUM07) - SUM(R2.SUM07) ,0),
		ISNULL( MIN(R1.SUM08) - SUM(R2.SUM08) ,0),
		ISNULL( MIN(R1.SUM09) - SUM(R2.SUM09) ,0),
		ISNULL( MIN(R1.SUM10) - SUM(R2.SUM10) ,0),
		ISNULL( MIN(R1.SUM11) - SUM(R2.SUM11) ,0),
		ISNULL( MIN(R1.SUM12) - SUM(R2.SUM12) ,0)
	FROM #RES R1 INNER JOIN #RES R2 ON R1.CODE_STR = '751'
	WHERE R2.CODE_STR IN ('755')

---***Начислено страховых взносов
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT
	'759',
		ISNULL(Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = 1 THEN SUMMA ELSE 0 END)),0),
		ISNULL(Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = 2 THEN SUMMA ELSE 0 END)),0),
		ISNULL(Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = 3 THEN SUMMA ELSE 0 END)),0),
		ISNULL(Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = 4 THEN SUMMA ELSE 0 END)),0),
		ISNULL(Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = 5 THEN SUMMA ELSE 0 END)),0),
		ISNULL(Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = 6 THEN SUMMA ELSE 0 END)),0),
		ISNULL(Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = 7 THEN SUMMA ELSE 0 END)),0),
		ISNULL(Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = 8 THEN SUMMA ELSE 0 END)),0),
		ISNULL(Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = 9 THEN SUMMA ELSE 0 END)),0),
		ISNULL(Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = 10 THEN SUMMA ELSE 0 END)),0),
		ISNULL(Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = 11 THEN SUMMA ELSE 0 END)),0),
		ISNULL(Convert(numeric(18,2),SUM(CASE WHEN MONTH_BASE = 12 THEN SUMMA ELSE 0 END)),0)
FROM #SPR_ESN
WHERE WAY_CALC = 11 AND SP = 'В3.1'	


-------- ТАблица 5   -  8xx строки
---	
	
SELECT 
	EMPL_LINK = E.LINK ,
	mon = month(a0.date1) ,
	--- по временной нетрудоспособности (без учета работающих иностранных граждан и лиц без гражданства)
	SUMMA801 = SUM((CASE WHEN COALESCE(A.DEKRET,0) = 1 THEN 0 ELSE 1 END) * ISNULL(A0.SUMMA,0)),
	DAYS803 = SUM( (CASE WHEN COALESCE(A.DEKRET,0) = 1 THEN 0 ELSE 1 END) * ISNULL(A0.[DAY],0)), --(DATEDIFF(DAY,T.DATE1,T.DATE2)+1) ),	
	--по беременности и родам записывать все оплачиваемые дни, а не только те, которые входят в оплачиваемый период
	SUMMA804 = SUM( COALESCE(A.DEKRET,0)  * ISNULL(A0.SUMMA,0)),
	DAYS806 = SUM(  COALESCE(A.DEKRET,0)  * ISNULL(A0.[DAY],0))--* (DATEDIFF(DAY,T.DATE1,T.DATE2)+1) ),	
INTO #posob_tab
  FROM 
	DBO.DOCUMENTS_ADD_ARCHE A
	INNER JOIN dbo.SD_EMPL E ON A.REF_EMPL = E.LINK 
	INNER JOIN DBO.DOCUMENTS_ADD_ARCHE_table0 A0 on A0.LINK =  A.link
	INNER JOIN dbo.person P ON p.LINK = e.PERS_LINK
	left JOIN dbo.CITIZENSHIP c ON c.LINK = p.CITIZ_LINK 
WHERE 
	E.LINK = @Link_empl
	and LINK_DEP = @DEP_LINK 
	AND FLAG_JC = 1 --НАЧИСЛЕННЫЕ
	AND YEAR(DATE) = @Year --НАЧИСЛЕННЫЕ В ЗАДАННОМ ГОДУ
	AND MONTH(DATE) <= MONTH(@EndYear) --НАЧИСЛЕННЫЕ ПО ЗАДАННЫЙ МЕСЯЦ
GROUP BY E.LINK,month(a0.date1)


SELECT J.LINK_EMPL, P.F4FSS, E.[STATUS], RESIDENT = (CASE c.CODE WHEN '1' then 2 when '2' then 2 ELSE 1 end) , CNT_EMPL = COUNT(DISTINCT J.LINK_EMPL), CNT = COUNT( J.LINK_EMPL),SUMMA = SUM(SUMMA), CNT_DAYS = SUM([DAYS]), mon = Month(period_begin)
INTO #posob_tab1
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(@EndYear, DEFAULT) E ON E.EMPL_LINK = J.LINK_EMPL 	
	INNER JOIN dbo.sd_empl se ON  sE.LINK = E.EMPL_LINK 
	INNER JOIN dbo.PERSON pe ON pe.LINK=se.PERS_LINK
	INNER JOIN dbo.CITIZENSHIP c ON c.LINK = pe.CITIZ_LINK
WHERE
	Year(period_begin) = @YEAR and Month(period_begin) <= month(@EndYear)
	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')
	and J.LINK_EMPL = @LINK_EMPL	
 
GROUP BY 	
	P.F4FSS, E.[STATUS],c.CODE , Month(period_begin), J.LINK_EMPL
order by link_empl 


--ВЫПЛАТА ПОСОБИЙ По временной нетрудоспособности
-----Число дней на больничном

--- Сумма По временной нетрудоспособности
 --код=табл. 05, строка 801
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '801', 
	ISNULL((SELECT SUM(SUMMA801) FROM #posob_tab WHERE MON = 1 ),0), 
	ISNULL((SELECT SUM(SUMMA801) FROM #posob_tab WHERE MON = 2 ),0), 
	ISNULL((SELECT SUM(SUMMA801) FROM #posob_tab WHERE MON = 3 ),0), 
	ISNULL((SELECT SUM(SUMMA801) FROM #posob_tab WHERE MON = 4 ),0), 
	ISNULL((SELECT SUM(SUMMA801) FROM #posob_tab WHERE MON = 5 ),0), 
	ISNULL((SELECT SUM(SUMMA801) FROM #posob_tab WHERE MON = 6 ),0), 
	ISNULL((SELECT SUM(SUMMA801) FROM #posob_tab WHERE MON = 7 ),0), 
	ISNULL((SELECT SUM(SUMMA801) FROM #posob_tab WHERE MON = 8 ),0), 
	ISNULL((SELECT SUM(SUMMA801) FROM #posob_tab WHERE MON = 9 ),0), 
	ISNULL((SELECT SUM(SUMMA801) FROM #posob_tab WHERE MON = 10 ),0), 
	ISNULL((SELECT SUM(SUMMA801) FROM #posob_tab WHERE MON = 11 ),0), 
	ISNULL((SELECT SUM(SUMMA801) FROM #posob_tab WHERE MON = 12 ),0)
	--ISNULL(@P02014,0), 
--	@P02013, @P02010, ''

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '802',0,0,0,0, 0,0,0,0,0,0,0,0

--- Количество дней По временной нетрудоспособности
--код=табл. 05, строка 803
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '803', 
	ISNULL((SELECT SUM(DAYS803) FROM #posob_tab WHERE MON = 1 ),0), 
	ISNULL((SELECT SUM(DAYS803) FROM #posob_tab WHERE MON = 2 ),0), 
	ISNULL((SELECT SUM(DAYS803) FROM #posob_tab WHERE MON = 3 ),0), 
	ISNULL((SELECT SUM(DAYS803) FROM #posob_tab WHERE MON = 4 ),0), 
	ISNULL((SELECT SUM(DAYS803) FROM #posob_tab WHERE MON = 5 ),0), 
	ISNULL((SELECT SUM(DAYS803) FROM #posob_tab WHERE MON = 6 ),0), 
	ISNULL((SELECT SUM(DAYS803) FROM #posob_tab WHERE MON = 7 ),0), 
	ISNULL((SELECT SUM(DAYS803) FROM #posob_tab WHERE MON = 8 ),0), 
	ISNULL((SELECT SUM(DAYS803) FROM #posob_tab WHERE MON = 9 ),0), 
	ISNULL((SELECT SUM(DAYS803) FROM #posob_tab WHERE MON = 10),0), 
	ISNULL((SELECT SUM(DAYS803) FROM #posob_tab WHERE MON = 11),0), 
	ISNULL((SELECT SUM(DAYS803) FROM #posob_tab WHERE MON = 12),0) 

--- Сумма По беременности и родам
--код=табл. 05, строка 804
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '804', 
	ISNULL((SELECT SUM(SUMMA804) FROM #posob_tab WHERE MON = 1),0), 
	ISNULL((SELECT SUM(SUMMA804) FROM #posob_tab WHERE MON = 2),0), 
	ISNULL((SELECT SUM(SUMMA804) FROM #posob_tab WHERE MON = 3),0), 
	ISNULL((SELECT SUM(SUMMA804) FROM #posob_tab WHERE MON = 4),0), 
	ISNULL((SELECT SUM(SUMMA804) FROM #posob_tab WHERE MON = 5),0), 
	ISNULL((SELECT SUM(SUMMA804) FROM #posob_tab WHERE MON = 6),0), 
	ISNULL((SELECT SUM(SUMMA804) FROM #posob_tab WHERE MON = 7),0), 
	ISNULL((SELECT SUM(SUMMA804) FROM #posob_tab WHERE MON = 8),0), 
	ISNULL((SELECT SUM(SUMMA804) FROM #posob_tab WHERE MON = 9),0), 
	ISNULL((SELECT SUM(SUMMA804) FROM #posob_tab WHERE MON = 10),0), 
	ISNULL((SELECT SUM(SUMMA804) FROM #posob_tab WHERE MON = 11),0), 
	ISNULL((SELECT SUM(SUMMA804) FROM #posob_tab WHERE MON = 12),0)


INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '805',0,0,0,0, 0,0,0,0,0,0,0,0

--- Количество дней По беременности и родам
--код=табл. 05, строка 806
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '806', 
	ISNULL((SELECT SUM(DAYS806) FROM #posob_tab WHERE MON = 1 ),0), 
	ISNULL((SELECT SUM(DAYS806) FROM #posob_tab WHERE MON = 2 ),0), 
	ISNULL((SELECT SUM(DAYS806) FROM #posob_tab WHERE MON = 3 ),0), 
	ISNULL((SELECT SUM(DAYS806) FROM #posob_tab WHERE MON = 4 ),0), 
	ISNULL((SELECT SUM(DAYS806) FROM #posob_tab WHERE MON = 5 ),0), 
	ISNULL((SELECT SUM(DAYS806) FROM #posob_tab WHERE MON = 6 ),0), 
	ISNULL((SELECT SUM(DAYS806) FROM #posob_tab WHERE MON = 7 ),0), 
	ISNULL((SELECT SUM(DAYS806) FROM #posob_tab WHERE MON = 8 ),0), 
	ISNULL((SELECT SUM(DAYS806) FROM #posob_tab WHERE MON = 9 ),0), 
	ISNULL((SELECT SUM(DAYS806) FROM #posob_tab WHERE MON = 10),0), 
	ISNULL((SELECT SUM(DAYS806) FROM #posob_tab WHERE MON = 11),0), 
	ISNULL((SELECT SUM(DAYS806) FROM #posob_tab WHERE MON = 12),0) 	

--- Сумма на Единовременное пособие женщинам, вставшим на учет в медицинских организациях в ранние сроки беременности
--код=табл. 05, строка 807
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '807', 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 1 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 2 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 3 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 4 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 5 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 6 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 7 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 8 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 9 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 10 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 11 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 12 and F4FSS = 4),0)

--- кол-во выплат на Единовременное пособие женщинам, вставшим на учет в медицинских организациях в ранние сроки беременности
--код=табл. 05, строка 808
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '808', 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 1 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 2 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 3 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 4 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 5 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 6 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 7 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 8 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 9 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 10 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 11 and F4FSS = 4),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 12 and F4FSS = 4),0)


--- Сумма на Единовременное пособие при рождении ребенка
--код=табл. 05, строка 809
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '809', 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 1 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 2 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 3 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 4 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 5 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 6 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 7 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 8 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 9 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 10 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 11 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 12 and F4FSS = 5),0)

--- кол-во выплат на Единовременное пособие при рождении ребенка
--код=табл. 05, строка 810
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '810', 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 1 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 2 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 3 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 4 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 5 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 6 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 7 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 8 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 9 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 10 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 11 and F4FSS = 5),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 12 and F4FSS = 5),0)


--- Сумма на Ежемесячное пособие по уходу за ребенком
--код=табл. 05, строка 811
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '811', 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 1 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 2 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 3 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 4 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 5 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 6 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 7 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 8 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 9 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 10 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 11 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 12 and F4FSS in (6,7)),0)


INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '812',0,0,0,0, 0,0,0,0,0,0,0,0

--- кол-во дней на Ежемесячное пособие по уходу за ребенком
 --код=табл. 05, строка 813
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '813', 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 1 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 2 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 3 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 4 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 5 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 6 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 7 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 8 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 9 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 10 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 11 and F4FSS in (6,7)),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 12 and F4FSS in (6,7)),0)


--- Сумма  по уходу за первым ребенком
 --код=табл. 05, строка 814
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '814', 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 1 and F4FSS = 6),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 2 and F4FSS = 6),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 3 and F4FSS = 6),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 4 and F4FSS = 6),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 5 and F4FSS = 6),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 6 and F4FSS = 6),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 7 and F4FSS = 6),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 8 and F4FSS = 6),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 9 and F4FSS = 6),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 10 and F4FSS = 6),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 11 and F4FSS = 6),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 12 and F4FSS = 6),0)

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '815',0,0,0,0, 0,0,0,0,0,0,0,0

--- Сумма  по уходу за вторым и последующими детьми
 --код=табл. 05, строка 816
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '816', 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 1 and F4FSS = 7),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 2 and F4FSS = 7),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 3 and F4FSS = 7),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 4 and F4FSS = 7),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 5 and F4FSS = 7),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 6 and F4FSS = 7),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 7 and F4FSS = 7),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 8 and F4FSS = 7),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 9 and F4FSS = 7),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 10 and F4FSS = 7),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 11 and F4FSS = 7),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 12 and F4FSS = 7),0)

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '817',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '818',0,0,0,0, 0,0,0,0,0,0,0,0
--- Сумма : Оплата 4-х дополнительных выходных дней для ухода за детьми-инвалидами
 --код=табл. 05, строка 819
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '819', 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 1 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 2 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 3 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 4 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 5 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 6 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 7 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 8 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 9 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 10 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 11 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 12 and F4FSS = 8),0)

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '820',0,0,0,0, 0,0,0,0,0,0,0,0
--- кол-во выплат: Оплата 4-х дополнительных выходных дней для ухода за детьми-инвалидами
 --код=табл. 05, строка 821
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '821', 
	ISNULL((SELECT SUM(CNT_DAYS) FROM #posob_tab1 WHERE MON = 1 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(CNT_DAYS) FROM #posob_tab1 WHERE MON = 2 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(CNT_DAYS) FROM #posob_tab1 WHERE MON = 3 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(CNT_DAYS) FROM #posob_tab1 WHERE MON = 4 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(CNT_DAYS) FROM #posob_tab1 WHERE MON = 5 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(CNT_DAYS) FROM #posob_tab1 WHERE MON = 6 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(CNT_DAYS) FROM #posob_tab1 WHERE MON = 7 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(CNT_DAYS) FROM #posob_tab1 WHERE MON = 8 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(CNT_DAYS) FROM #posob_tab1 WHERE MON = 9 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(CNT_DAYS) FROM #posob_tab1 WHERE MON = 10 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(CNT_DAYS) FROM #posob_tab1 WHERE MON = 11 and F4FSS = 8),0), 
	ISNULL((SELECT SUM(CNT_DAYS) FROM #posob_tab1 WHERE MON = 12 and F4FSS = 8),0)

--- Сумма : Социальное пособие на погребение или возмещение стоимости гарантированного перечня услуг по погребению
 --код=табл. 05, строка 822
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '822', 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 1 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 2 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 3 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 4 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 5 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 6 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 7 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 8 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 9 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 10 and F4FSS =9),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 11 and F4FSS =9),0), 
	ISNULL((SELECT SUM(SUMMA) FROM #posob_tab1 WHERE MON = 12 and F4FSS =9),0)

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '823',0,0,0,0, 0,0,0,0,0,0,0,0
--- кол-во выплат: Социальное пособие на погребение или возмещение стоимости гарантированного перечня услуг по погребению
--код=табл. 05, строка 824
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '824', 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 1 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 2 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 3 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 4 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 5 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 6 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 7 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 8 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 9 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 10 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 11 and F4FSS = 9),0), 
	ISNULL((SELECT SUM(CNT) FROM #posob_tab1 WHERE MON = 12 and F4FSS = 9),0)

INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '825',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '826',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '827',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '828',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '829',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '830',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '831',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '832',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '833',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '834',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '835',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '836',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '837',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '838',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '839',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '840',0,0,0,0, 0,0,0,0,0,0,0,0
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT '841',0,0,0,0, 0,0,0,0,0,0,0,0



UPDATE r 
SEt SUM01 = (select SUM(SUM01) FROM  #RES WHERE CODE_STR IN ('801','804','807','809','811','814','816','819','822')), 
	SUM02 = (select SUM(SUM02) FROM  #RES WHERE CODE_STR IN ('801','804','807','809','811','814','816','819','822')), 
	SUM03 = (select SUM(SUM03) FROM  #RES WHERE CODE_STR IN ('801','804','807','809','811','814','816','819','822')), 
	SUM04 = (select SUM(SUM04) FROM  #RES WHERE CODE_STR IN ('801','804','807','809','811','814','816','819','822')), 
	SUM05 = (select SUM(SUM05) FROM  #RES WHERE CODE_STR IN ('801','804','807','809','811','814','816','819','822')), 
	SUM06 = (select SUM(SUM06) FROM  #RES WHERE CODE_STR IN ('801','804','807','809','811','814','816','819','822')), 
	SUM07 = (select SUM(SUM07) FROM  #RES WHERE CODE_STR IN ('801','804','807','809','811','814','816','819','822')), 
	SUM08 = (select SUM(SUM08) FROM  #RES WHERE CODE_STR IN ('801','804','807','809','811','814','816','819','822')), 
	SUM09 = (select SUM(SUM09) FROM  #RES WHERE CODE_STR IN ('801','804','807','809','811','814','816','819','822')), 
	SUM10 = (select SUM(SUM10) FROM  #RES WHERE CODE_STR IN ('801','804','807','809','811','814','816','819','822')), 
	SUM11 = (select SUM(SUM11) FROM  #RES WHERE CODE_STR IN ('801','804','807','809','811','814','816','819','822')), 
	SUM12 = (select SUM(SUM12) FROM  #RES WHERE CODE_STR IN ('801','804','807','809','811','814','816','819','822'))
FROM #RES r
WHERE r.code_str = '131' 


UPDATE r 
SEt SUM01 = (select SUM(SUM01) FROM  #RES WHERE CODE_STR IN ('825','827','829','831','833','835','837','839','841')), 
	SUM02 = (select SUM(SUM02) FROM  #RES WHERE CODE_STR IN ('825','827','829','831','833','835','837','839','841')), 
	SUM03 = (select SUM(SUM03) FROM  #RES WHERE CODE_STR IN ('825','827','829','831','833','835','837','839','841')), 
	SUM04 = (select SUM(SUM04) FROM  #RES WHERE CODE_STR IN ('825','827','829','831','833','835','837','839','841')), 
	SUM05 = (select SUM(SUM05) FROM  #RES WHERE CODE_STR IN ('825','827','829','831','833','835','837','839','841')), 
	SUM06 = (select SUM(SUM06) FROM  #RES WHERE CODE_STR IN ('825','827','829','831','833','835','837','839','841')), 
	SUM07 = (select SUM(SUM07) FROM  #RES WHERE CODE_STR IN ('825','827','829','831','833','835','837','839','841')), 
	SUM08 = (select SUM(SUM08) FROM  #RES WHERE CODE_STR IN ('825','827','829','831','833','835','837','839','841')), 
	SUM09 = (select SUM(SUM09) FROM  #RES WHERE CODE_STR IN ('825','827','829','831','833','835','837','839','841')), 
	SUM10 = (select SUM(SUM10) FROM  #RES WHERE CODE_STR IN ('825','827','829','831','833','835','837','839','841')), 
	SUM11 = (select SUM(SUM11) FROM  #RES WHERE CODE_STR IN ('825','827','829','831','833','835','837','839','841')), 
	SUM12 = (select SUM(SUM12) FROM  #RES WHERE CODE_STR IN ('825','827','829','831','833','835','837','839','841'))
FROM #RES r
WHERE r.code_str = '133' 
-------<<<<<Конец по ДОП ТАРИФАМ>>>>
	
--Суммы с начала года
INSERT INTO #RES (CODE_STR, SUM01, SUM02, SUM03, SUM04, SUM05, SUM06, SUM07, SUM08, SUM09, SUM10, SUM11, SUM12)
SELECT 
	CONVERT(VARCHAR(3), CONVERT(INT,CODE_STR) + 1),
	R.SUM01,
	R.SUM01 + R.SUM02,
	R.SUM01 + R.SUM02 + R.SUM03,
	R.SUM01 + R.SUM02 + R.SUM03 + R.SUM04,
	R.SUM01 + R.SUM02 + R.SUM03 + R.SUM04 + R.SUM05,
	R.SUM01 + R.SUM02 + R.SUM03 + R.SUM04 + R.SUM05 + R.SUM06,
	R.SUM01 + R.SUM02 + R.SUM03 + R.SUM04 + R.SUM05 + R.SUM06 + R.SUM07,
	R.SUM01 + R.SUM02 + R.SUM03 + R.SUM04 + R.SUM05 + R.SUM06 + R.SUM07 + R.SUM08,
	R.SUM01 + R.SUM02 + R.SUM03 + R.SUM04 + R.SUM05 + R.SUM06 + R.SUM07 + R.SUM08 + R.SUM09,
	R.SUM01 + R.SUM02 + R.SUM03 + R.SUM04 + R.SUM05 + R.SUM06 + R.SUM07 + R.SUM08 + R.SUM09 + R.SUM10,
	R.SUM01 + R.SUM02 + R.SUM03 + R.SUM04 + R.SUM05 + R.SUM06 + R.SUM07 + R.SUM08 + R.SUM09 + R.SUM10 + R.SUM11,
	R.SUM01 + R.SUM02 + R.SUM03 + R.SUM04 + R.SUM05 + R.SUM06 + R.SUM07 + R.SUM08 + R.SUM09 + R.SUM10 + R.SUM11 + R.SUM12
FROM #RES R WHERE CONVERT(INT,CODE_STR) % 2 > 0  and CONVERT(INT,CODE_STR) < 800

UPDATE r 
SEt SUM01 = (select SUM(SUM01) FROM  #RES WHERE CODE_STR IN ('131','133')), 
	SUM02 = (select SUM(SUM02) FROM  #RES WHERE CODE_STR IN ('131','133')), 
	SUM03 = (select SUM(SUM03) FROM  #RES WHERE CODE_STR IN ('131','133')), 
	SUM04 = (select SUM(SUM04) FROM  #RES WHERE CODE_STR IN ('131','133')), 
	SUM05 = (select SUM(SUM05) FROM  #RES WHERE CODE_STR IN ('131','133')), 
	SUM06 = (select SUM(SUM06) FROM  #RES WHERE CODE_STR IN ('131','133')), 
	SUM07 = (select SUM(SUM07) FROM  #RES WHERE CODE_STR IN ('131','133')), 
	SUM08 = (select SUM(SUM08) FROM  #RES WHERE CODE_STR IN ('131','133')), 
	SUM09 = (select SUM(SUM09) FROM  #RES WHERE CODE_STR IN ('131','133')), 
	SUM10 = (select SUM(SUM10) FROM  #RES WHERE CODE_STR IN ('131','133')), 
	SUM11 = (select SUM(SUM11) FROM  #RES WHERE CODE_STR IN ('131','133')), 
	SUM12 = (select SUM(SUM12) FROM  #RES WHERE CODE_STR IN ('131','133'))
FROM #RES r
WHERE r.code_str = '129' 

UPDATE r 
SEt SUM01 = (select SUM(SUM01) FROM  #RES WHERE CODE_STR IN ('132','134')), 
	SUM02 = (select SUM(SUM02) FROM  #RES WHERE CODE_STR IN ('132','134')), 
	SUM03 = (select SUM(SUM03) FROM  #RES WHERE CODE_STR IN ('132','134')), 
	SUM04 = (select SUM(SUM04) FROM  #RES WHERE CODE_STR IN ('132','134')), 
	SUM05 = (select SUM(SUM05) FROM  #RES WHERE CODE_STR IN ('132','134')), 
	SUM06 = (select SUM(SUM06) FROM  #RES WHERE CODE_STR IN ('132','134')), 
	SUM07 = (select SUM(SUM07) FROM  #RES WHERE CODE_STR IN ('132','134')), 
	SUM08 = (select SUM(SUM08) FROM  #RES WHERE CODE_STR IN ('132','134')), 
	SUM09 = (select SUM(SUM09) FROM  #RES WHERE CODE_STR IN ('132','134')), 
	SUM10 = (select SUM(SUM10) FROM  #RES WHERE CODE_STR IN ('132','134')), 
	SUM11 = (select SUM(SUM11) FROM  #RES WHERE CODE_STR IN ('132','134')), 
	SUM12 = (select SUM(SUM12) FROM  #RES WHERE CODE_STR IN ('132','134'))
FROM #RES r
WHERE r.code_str = '130' 

--SELECT * FROM #RES
--exec SA_PERS_CARD_ESN_15  94,'2015'
---
CREATE TABLE #SPR_TARIF (NUM_STR INT IDENTITY(1,1), LINK2 INT, CODE VARCHAR(20))

INSERT INTO #SPR_TARIF (LINK2, CODE)
SELECT DISTINCT 
	K.LINK2, K.CODE
FROM #RES R
	INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = CONVERT(INT,LEFT(CODE_STR,1)) AND @YEAR BETWEEN YBEG AND YEND
ORDER BY
	K.CODE	



DECLARE @Sex TINYINT, @YearB  INT, @Type INT

SELECT TOP 1 @Sex = SEX, @YearB =ISNULL(YEAR(BIRTHDATE),0) FROM dbo.PERSON WHERE LINK = @LINK_PERSON
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)
--Тариф ФОМС и ФСС
SELECT 
	T.LINK2, T.CODE, WC = W.CODE, W.NAME, PERCENT1 , PREDEL = 0
INTO #TARIF	
FROM 
	#SPR_TARIF T
	INNER JOIN dbo.WAY_CALC W ON 1=1
	INNER JOIN dbo.PAYS P ON P.[OBJECT] = 3 AND P.WAY_CALC = W.CODE
	INNER JOIN dbo.STAVKI S ON S.LINK_PAYS = P.LINK AND S.TARIF = T.LINK2
WHERE
	W.[TYPE] = 2
	AND W.CODE BETWEEN 2 AND 4 
	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 = W.CODE WHERE S.TARIF = T.LINK2 AND [DATE] < @EndYear ORDER BY [DATE] DESC) 
	AND S.PERCENT1 > 0
--Тариф Страховая и накопительная для 
UNION ALL
SELECT 
	T.LINK2, T.CODE, WC = W.CODE, W.NAME, (CASE WHEN @Type = 1 THEN PERCENT1 WHEN @Type = 2 THEN PERCENT2 ELSE PERCENT3 END) , PREDEL = 0
FROM 
	#SPR_TARIF T
	INNER JOIN dbo.WAY_CALC W ON 1=1
	INNER JOIN dbo.PAYS P ON P.[OBJECT] = 3 AND P.WAY_CALC = W.CODE
	INNER JOIN dbo.STAVKI_PF S ON S.LINK_PAYS = P.LINK AND S.TARIF = T.LINK2
WHERE
	W.[TYPE] = 2 
	AND W.CODE BETWEEN 6 AND 7 
	AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = W.CODE WHERE S.TARIF = T.LINK2 AND [DATE] < @EndYear ORDER BY [DATE] DESC) 
	AND (S.PERCENT1 > 0 OR S.PERCENT2 > 0 OR S.PERCENT3 > 0)
	AND s.PREDEL <> 999999999.00

	
UNION ALL
SELECT 
	T.LINK2, T.CODE, WC = W.CODE, W.NAME, (CASE WHEN @Type = 1 THEN PERCENT1 WHEN @Type = 2 THEN PERCENT2 ELSE PERCENT3 END) , PREDEL = 1
FROM 
	#SPR_TARIF T
	INNER JOIN dbo.WAY_CALC W ON 1=1
	INNER JOIN dbo.PAYS P ON P.[OBJECT] = 3 AND P.WAY_CALC = W.CODE
	INNER JOIN dbo.STAVKI_PF S ON S.LINK_PAYS = P.LINK AND S.TARIF = T.LINK2
WHERE
	W.[TYPE] = 2 
	AND W.CODE BETWEEN 6 AND 7 
	AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = W.CODE WHERE S.TARIF = T.LINK2 AND [DATE] < @EndYear ORDER BY [DATE] DESC) 
	AND (S.PERCENT1 > 0 OR S.PERCENT2 > 0 OR S.PERCENT3 > 0)	
	AND s.PREDEL = 999999999.00
	
--Доп тарифы
UNION ALL
SELECT 
	T.LINK2, T.CODE, WC = W.CODE, W.NAME, (CASE WHEN @Type = 1 THEN PERCENT1 WHEN @Type = 2 THEN PERCENT2 ELSE PERCENT3 END), PREDEL = 0
FROM 
	#SPR_TARIF T
	INNER JOIN dbo.WAY_CALC W ON 1=1
	INNER JOIN dbo.PAYS P ON P.[OBJECT] = 3 AND P.WAY_CALC = W.CODE
	INNER JOIN dbo.STAVKI_PF S ON S.LINK_PAYS = P.LINK AND S.TARIF = T.LINK2
WHERE
	W.[TYPE] = 2 
	AND W.CODE BETWEEN 10 AND 11 
	AND [DATE] = (SELECT TOP 1 [DATE] FROM dbo.STAVKI_PF S INNER JOIN DBO.PAYS P ON S.LINK_PAYS = P.LINK AND P.[OBJECT] = 3 AND P.WAY_CALC = W.CODE WHERE S.TARIF = T.LINK2 AND [DATE] < @EndYear ORDER BY [DATE] DESC) 
	AND (S.PERCENT1 > 0 OR S.PERCENT2 > 0 OR S.PERCENT3 > 0)	

DECLARE @FULL_NAME VARCHAR(254), @INN VARCHAR(20), @KPP VARCHAR(20)	
SELECT TOP 1 @FULL_NAME = FULL_NAME, @INN = INN, @KPP = KPP FROM dbo.DEPARTMENTS WHERE LINK = @DEP_LINK



SELECT distinct
	[YEAR] = @YEAR, DEP_NAME = @FULL_NAME, INN = @INN, KPP = @KPP,
	P.FM,
	P.IM,
	P.OT,
	DIF.DOC_NUM,
	P.INSUR_NUM,
	P.INN,
	GRAZH = S.NAME,
	BIRTHDATE = CONVERT(VARCHAR(10),P.BIRTHDATE,104),
	INV = CASE WHEN DIF.LINK IS NULL THEN 'НЕТ' ELSE 'ЕСТЬ' END,
	CONVERT(VARCHAR(10),DIF.DATE_BEGIN,104) AS PER_BEG,
	CONVERT(VARCHAR(10),DIF.DATE_END,104) AS PER_END,
	ORDER_NUM = CASE WHEN @LINK_EMPL IS NOT NULL  THEN  LTRIM(RTRIM(SUBSTRING ((SELECT
							', ' + LTRIM(RTRIM(ISNULL (o.NUMBER, '')))
							FROM dbo.ITEM_MOVE  im 
							INNER join orders o on o.link = im.ORDER_LINK
							WHERE im.empl_link = @LINK_EMPL AND im.ACTIVE = 1 AND im.[STATUS] IN(1,3)  AND im.date_end > @BYearDate
							FOR XML PATH ('')),
							3,
							1000) ))
					 ELSE 	LTRIM(RTRIM(SUBSTRING ((SELECT
							', ' + ISNULL (number, '')
							FROM dbo.salary_reestr_dgh 
							WHERE pers_link = @LINK_PERSON AND year(@BYearDate) BETWEEN year(date1) AND year(date2)  
							FOR XML PATH ('')),
							3,
							1000) ))
	                END ,
	ORDER_DATE= CASE WHEN @LINK_EMPL IS NOT NULL  THEN  (select max(im.date_begin) from ITEM_MOVE im
						INNER join orders o on o.link = im.ORDER_LINK
						WHERE im.empl_link = @LINK_EMPL AND im.ACTIVE = 1 AND im.[STATUS] IN(1,3)  AND im.date_end > @BYearDate)	
					ELSE 	(select max(date1) FROM salary_reestr_dgh WHERE pers_link =  @LINK_PERSON AND   year(@BYearDate) BETWEEN  year(date1) AND  year(date2) ) END ,				
	T.NUM_STR,
	T.LINK2,
	CT = T.CODE, --Код тарифа
	OPS_SC = ISNULL((SELECT TOP 1 T2.PERCENT1 FROM #TARIF T2 WHERE T2.LINK2 = T.LINK2 AND T2.WC = 6 AND T2.PREDEL = 0 ),0),
	OPS_NC = ISNULL((SELECT TOP 1 T2.PERCENT1 FROM #TARIF T2 WHERE T2.LINK2 = T.LINK2 AND T2.WC = 7 AND T2.PREDEL = 0 ),0),
	OPS_PR = ISNULL((SELECT TOP 1 T2.PERCENT1 FROM #TARIF T2 WHERE T2.LINK2 = T.LINK2 AND T2.WC = 6 AND T2.PREDEL = 1 ),0),
	OPS_D1 = ISNULL((SELECT TOP 1 T2.PERCENT1 FROM #TARIF T2 WHERE T2.LINK2 = T.LINK2 AND T2.WC = 10),0),
	OPS_D2 = ISNULL((SELECT TOP 1 T2.PERCENT1 FROM #TARIF T2 WHERE T2.LINK2 = T.LINK2 AND T2.WC = 11),0),
	OMS_F = ISNULL((SELECT TOP 1 T2.PERCENT1 FROM #TARIF T2 WHERE T2.LINK2 = T.LINK2 AND T2.WC = 3),0),
	OMS_T = ISNULL((SELECT TOP 1 T2.PERCENT1 FROM #TARIF T2 WHERE T2.LINK2 = T.LINK2 AND T2.WC = 4),0),
	FSS = ISNULL((SELECT TOP 1 T2.PERCENT1 FROM #TARIF T2 WHERE T2.LINK2 = T.LINK2 AND T2.WC = 2),0),
	DGH = CASE WHEN @LINK_EMPL IS NOT NULL THEN '1' ELSE '2' END   
	
FROM 
	#SPR_TARIF T
	INNER JOIN dbo.PERSON P ON 1=1
	LEFT JOIN dbo.CITIZENSHIP S ON S.LINK = P.CITIZ_LINK
	LEFT JOIN dbo.KU_PERS_INVALID DIF ON DIF.PERS_LINK = P.LINK AND COALESCE(DIF.DATE_BEGIN,@EndYear) <= @EndYear AND COALESCE(DIF.DATE_END,@BYearDate) >= @BYearDate
WHERE 
	P.LINK = @LINK_PERSON
ORDER BY
	T.NUM_STR	
	


SELECT LINK2 = CONVERT(INT,LEFT(CODE_STR,1)), * FROM #RES ORDER BY CODE_STR


IF object_id('tempdb..#SPR_ESN') IS NOT NULL
	DROP TABLE #SPR_ESN

IF object_id('tempdb..#DGH_FAKT_BASE') IS NOT NULL
	DROP TABLE #DGH_FAKT_BASE

IF object_id('tempdb..#DGH_FAKT_BASE1') IS NOT NULL
	DROP TABLE #DGH_FAKT_BASE1

IF object_id('tempdb..#SALARY_SUM2') IS NOT NULL
	DROP TABLE #SALARY_SUM2

IF object_id('tempdb..#RES') IS NOT NULL
	DROP TABLE #RES

IF object_id('tempdb..#SPR_ESN1') IS NOT NULL
	DROP TABLE #SPR_ESN1

IF object_id('tempdb..#SPR_ESN1_F') IS NOT NULL
	DROP TABLE #SPR_ESN1_F	

IF object_id('tempdb..#SPR_ESN2') IS NOT NULL
	DROP TABLE #SPR_ESN2

IF object_id('tempdb..#SPR_ESN2_F') IS NOT NULL
	DROP TABLE #SPR_ESN2_F
	

IF object_id('tempdb..#DGH_FSS') IS NOT NULL
	DROP TABLE #DGH_FSS

IF object_id('tempdb..#SUM_FSS') IS NOT NULL
	DROP TABLE #SUM_FSS

IF object_id('tempdb..#SPR_ESN1I') IS NOT NULL
	DROP TABLE #SPR_ESN1I

IF object_id('tempdb..#SPR_ESN2I') IS NOT NULL
	DROP TABLE #SPR_ESN2I

IF object_id('tempdb..#SPR_ESN1I') IS NOT NULL
	DROP TABLE #SPR_ESN1FI

IF object_id('tempdb..#SPR_ESN2I') IS NOT NULL
	DROP TABLE #SPR_ESN2FI

IF object_id('tempdb..#SPR_ESN1E') IS NOT NULL
	DROP TABLE #SPR_ESN1E

IF object_id('tempdb..#SPR_ESN2E') IS NOT NULL
	DROP TABLE #SPR_ESN2E

IF object_id('tempdb..#SPR_ESN1E') IS NOT NULL
	DROP TABLE #SPR_ESN1_FE

IF object_id('tempdb..#SPR_ESN2E') IS NOT NULL
	DROP TABLE #SPR_ESN2_FE

IF object_id('tempdb..#TARIF') IS NOT NULL
	DROP TABLE #TARIF

IF object_id('tempdb..#SPR_TARIF') IS NOT NULL
	DROP TABLE #SPR_TARIF

END

RETURN 0











GO


GRANT EXECUTE ON dbo.[SA_PERS_CARD_ESN_15] TO PUBLIC

GO


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


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

GO

CREATE PROCEDURE DBO.SD_N_TABEL_FILL
	@VARKSNLINK	 INT = 0, @MODE TINYINT =0, 	@VARKSDDATE DATETIME = NULL, @BUFFERCODE VARCHAR(15) = '', @DEP_LINK INT = NULL, @LINK_R INT = 0
/*ЕСЛИ @MODE = 0, ТО @VARKSNLINK - ССЫЛКА НА ТАБЕЛЬ, 
ЕСЛИ @MODE= 1, ТО @VARKSNLINK - ССЫЛКА НА СОТРУДНИКА И @VARKSDDATE - ПЕРИОД
ЕСЛИ @MODE= 2, ТО @VARKSDDATE - ПЕРИОД И ЛИНКИ СОТРУДНИКОВ ИЗ БУФФЕРА С КОДОМ @BUFFERCODE 
РЕЗУЛЬТАТ СРАЗУ СОХРАНИТЬ В РАСЧЕТЕ С ЛИНКОМ @LINK_R
*/
AS

/*
C КЕЙСИСТЕМС (KEYSYSTEMS), 2005
*/

SET NOCOUNT ON
DECLARE 	@VARKSDAT 	[DATETIME], 
	  	@VARKSDAT1 [DATETIME],
		@VARKSDAT2 [DATETIME]

---------------------------------------------------
IF @MODE = 0
	SET 	@VARKSDAT = CONVERT(DATETIME,ISNULL((SELECT TOP 1 TAB.PERIOD FROM DBO.TABELS TAB WHERE TAB.LINK_DOC = @VARKSNLINK),GETDATE()),104)
ELSE
	SET 	@VARKSDAT = @VARKSDDATE

SET 	@VARKSDAT = DBO.DATEENDOFMONTH(@VARKSDAT)

---------------------------------------------------
DECLARE @P INT
SET @P = (CASE @MODE WHEN 0 THEN -1 WHEN 1 THEN @VARKSNLINK WHEN 2 THEN -1 END)

---------------------------------------------------
CREATE TABLE #VARKSTMP
([LINK]					[INT],
 [ORDERS]				[INT] IDENTITY(1,1),
 [TAB_NUMER]			[VARCHAR] (6),
 [NAME_EMPL]			[VARCHAR] (30),
 [LINK_EMPL]			[INT],
 [LINK_SOVM]			[INT],
 [DATE1]				[DATETIME],		
 [DATE2]				[DATETIME],		
 [DAY]					[NUMERIC] (4,0),
 [HOUR]					[NUMERIC] (10,2),
 [DAY_NORM]				[NUMERIC] (4,0),
 [HOUR_NORM]			[NUMERIC] (10,2),
 [GRAPH_NAME]			[VARCHAR] (30),
 [GRAPH_LINK]			[INT],
 [SUMMA_BASE]			[NUMERIC] (18,2),
 [SUMMA] 				[NUMERIC] (18,2),
 [SUMMA_VIPL]			[NUMERIC] (18,2),
 [SUMMA_ALL]			[NUMERIC] (18,2),
 [PERCENT]				[NUMERIC] (18,4),
 [RATE]					[NUMERIC] (5,2),
 [REF_PAY]				[INT],
 [CODE_PAY]				[VARCHAR] (10),
 [NAME_PAY]				[VARCHAR] (60),
 [WAY_CALC]				[TINYINT],
 [DATE1_PAY]			[DATETIME],  
 [DATE2_PAY]			[DATETIME],
 LINK_KBK				INT,
 CODE_KBK				VARCHAR(30),
 SYST_PAY				INT,
 ORD					INT,
 [DAY_OLD]				[NUMERIC] (18,2),
 [HOUR_OLD]				[NUMERIC] (18,2),
 NO_TIME				BIT 		
)

---------------------------------------------------
IF NOT EXISTS ( --ЕСЛИ ТАБЕЛЯ НЕ СУЩЕСТВУЕТ, ТО ВЫДАТЬ ПУСТОЙ КУРСОР
	SELECT *
	FROM 
		DBO.SDOC DOC
		INNER JOIN DBO.TABELS T ON DOC.LINK = T.LINK_DOC
	WHERE 
		(
			DOC.LINK = @VARKSNLINK AND @MODE = 0) 
			OR 
			(@MODE IN (1,2) AND YEAR(T.PERIOD) = YEAR(@VARKSDDATE) AND MONTH(T.PERIOD) = MONTH(@VARKSDDATE)
		)
		AND DOC.OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SA_TABELS') 
)
BEGIN
	SELECT 
		[LINK],[ORDERS],[TAB_NUMER],[NAME_EMPL],[LINK_EMPL],[LINK_SOVM],[DATE1],[DATE2],		
		CONVERT(INT,[DAY]) AS [DAY],[HOUR],CONVERT(INT,[DAY_NORM]) AS [DAY_NORM],
		[HOUR_NORM],[GRAPH_NAME],[GRAPH_LINK],[SUMMA_BASE],[SUMMA],
		[SUMMA_VIPL],[SUMMA_ALL],[PERCENT],[RATE],[REF_PAY],[CODE_PAY],[NAME_PAY],[WAY_CALC],
		[DATE1_PAY],[DATE2_PAY], LINK_KBK, CODE_KBK
	FROM #VARKSTMP	

	RETURN 0	
END

--ДЛЯ КОГО СЧИТАТЬ
DECLARE @BUF_ID VARCHAR(20)
DECLARE @SQL VARCHAR(1000)

IF @MODE < 2 BEGIN
	EXEC DBO.GETRANDSTR 20, @BUF_ID OUT

	SET @SQL = '
	INSERT INTO DBO.BUFFER (ID, LINK)
	SELECT DISTINCT ''' + @BUF_ID + ''', T.LINK_EMPL
	FROM
		DBO.TABELS T WITH (NOLOCK) 
	WHERE
		T.LINK_DOC = ' + CONVERT(VARCHAR(20),@VARKSNLINK) + ' AND ' + CONVERT(VARCHAR(20),@MODE) + ' = 0'

	EXEC (@SQL)
	

	SET @SQL = '
	INSERT INTO DBO.BUFFER (ID, LINK)
	SELECT DISTINCT ''' + @BUF_ID + ''', ' + CONVERT(VARCHAR(20),@VARKSNLINK) + '
		WHERE ' + CONVERT(VARCHAR(20),@MODE) + ' = 1'

	EXEC (@SQL)

END
ELSE
BEGIN
	SET @BUF_ID = @BUFFERCODE
	SET @VARKSNLINK = -1 --По всем табелям за период
END

---------------------------------------------------
SET	@VARKSDAT1 	= DATEADD(DAY,1-DAY(@VARKSDAT),@VARKSDAT)
SET	@VARKSDAT2 	= DATEADD(DAY,-1,DATEADD(MONTH,1,@VARKSDAT1))

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

CREATE TABLE #DPEE (
	LINK_EMPL INT,
	LINK_SOVM INT,
	LINK_PAYS INT,
	CODE_PAYS VARCHAR(10),
	NAME_PAYS VARCHAR(60),
	DATE_BEGIN DATETIME,
	DATE_END DATETIME,
	WAY_CALC TINYINT,
	SUMMA_BASE NUMERIC(18,2),
	PERC NUMERIC(18,4),
	SUMMA NUMERIC(18,2),
	LINK_KBK INT,
	CODE_KBK VARCHAR(30),
	[DAYS] NUMERIC(5,2), 
	[HOURS] NUMERIC(18,2),
	NO_TIME BIT 
)

---select @P,@VARKSDAT2,@BUF_ID, @DEP_LINK, @VARKSNLINK

INSERT INTO #DPEE (LINK_EMPL, LINK_SOVM, LINK_PAYS, CODE_PAYS, NAME_PAYS, DATE_BEGIN, DATE_END, WAY_CALC, SUMMA_BASE, PERC, SUMMA, LINK_KBK, CODE_KBK, DAYS, HOURS, NO_TIME)
SELECT LINK_EMPL, LINK_SOVM, LINK_PAYS, CODE_PAYS, NAME_PAYS, DATE_BEGIN, DATE_END, WAY_CALC, SUMMA_BASE, PERC, SUMMA, LINK_KBK, CODE_KBK, DAYS, HOURS, NO_TIME
FROM DBO.SA_ALL_PAYS_ALL(@P,@VARKSDAT2,@BUF_ID, @DEP_LINK, @VARKSNLINK)

CREATE TABLE #SA_EMPLS_W (LINK_EMPL INT, LINK_SOVM INT, GRAPH_LINK INT, NUM_STAKE NUMERIC(5,2), SYST_PAY TINYINT, DATE_BEGIN DATETIME, DATE_END DATETIME, LINK_SFIN INT, SALPERC NUMERIC(18,2), link_type INT)
INSERT INTO #SA_EMPLS_W (LINK_EMPL, LINK_SOVM, GRAPH_LINK, NUM_STAKE, SYST_PAY, DATE_BEGIN, DATE_END, LINK_SFIN, SALPERC, link_type)
SELECT LINK_EMPL, LINK_SOVM, GRAPH_LINK, NUM_STAKE, SYST_PAY, DATE_BEGIN, DATE_END, LINK_SFIN, SALPERC, link_type FROM DBO.SA_EMPLS_W_LITE_FN (@P,@VARKSDAT2,@BUF_ID)

---
SET @SQL = 'DELETE FROM DBO.BUFFER WHERE ID = ''' + @BUF_ID + ''''
EXEC (@SQL)

-------------  ИНФОРМАЦИЯ НА БАЗЕ ОСНОВНОГО ТАБЕЛЯ ---------------
INSERT INTO #VARKSTMP ([LINK], [TAB_NUMER],[NAME_EMPL],[LINK_EMPL],[LINK_SOVM],[DATE1],[DATE2],		
						[DAY],[HOUR],[DAY_NORM],[HOUR_NORM],[GRAPH_NAME],[GRAPH_LINK],[SUMMA_BASE],[SUMMA],
						[SUMMA_VIPL],[SUMMA_ALL],[PERCENT],[RATE],[REF_PAY],[CODE_PAY],[NAME_PAY],[WAY_CALC],
						[DATE1_PAY],[DATE2_PAY], LINK_KBK, CODE_KBK, SYST_PAY,[DAY_OLD],[HOUR_OLD], NO_TIME)
SELECT 
	[LINK]			= DOC.LINK,
	[TAB_NUMER]		= SUBSTRING(RTRIM(LTRIM(EM.TAB)),1,6),
	[NAME_EMPL]		= SUBSTRING(LTRIM(RTRIM(ISNULL(P.FM,''))) + ' ' + LEFT(LTRIM(RTRIM(ISNULL(P.IM,''))),1) + '.' + LEFT(LTRIM(RTRIM(ISNULL(P.OT,''))),1) + '.',1,30),
	[LINK_EMPL] 	= E.LINK_EMPL,
	[LINK_SOVM] 	= E.LINK_SOVM,
	[DATE1]			= DPE.DATE_BEGIN,
	[DATE2]			= ISNULL(DPE.DATE_END,CONVERT(DATETIME,'01.01.3000',104)),
	[DAY]			= DPE.DAYS,
	[HOUR]			= DPE.HOURS,
	[DAY_NORM]		= ISNULL(CONVERT(NUMERIC(4,0),G1.DAY_NORM),0),
	[HOUR_NORM] 	= ISNULL(CONVERT(NUMERIC(10,2),G1.HOUR_NORM),0),
	[GRAPH_NAME]	= SUBSTRING(RTRIM(LTRIM(G.NAME)),1,30),
	[GRAPH_LINK]	= E.GRAPH_LINK,
	[SUMMA_BASE]	= CONVERT(NUMERIC(18,2),ISNULL( DPE.SUMMA_BASE ,0)),
	[SUMMA]		  	= 0.00,
	[SUMMA_VIPL]	= (CASE WHEN @MODE = 0 THEN CONVERT(NUMERIC(18,2),ISNULL(OLD.SUMMA,0)) ELSE CONVERT(NUMERIC(18,2),ISNULL(OLDA.SUMMA,0)) END),
	[SUMMA_ALL]		= CONVERT(NUMERIC(18,2),ISNULL( DPE.SUMMA,0)),
	[PERCENT] 		= CONVERT(NUMERIC(18,4),ISNULL( DPE.PERC,0)),
	[RATE]			= ISNULL(E.NUM_STAKE,0),
	[REF_PAY]		= DPE.LINK_PAYS,
	[CODE_PAY]		= SUBSTRING(RTRIM(LTRIM(DPE.CODE_PAYS)),1,10),
	[NAME_PAY]		= SUBSTRING(RTRIM(LTRIM(DPE.NAME_PAYS)),1,60),
	[WAY_CALC]		= DPE.WAY_CALC,
	[DATE1_PAY]		= DPE.DATE_BEGIN,
	[DATE2_PAY]		= ISNULL(DPE.DATE_END,CONVERT(DATETIME,'01.01.3000',104)),
	DPE.LINK_KBK, LEFT(DPE.CODE_KBK,30),
	E.SYST_PAY,
	DAY_OLD = (CASE WHEN @MODE = 0 THEN CONVERT(NUMERIC(18,2),ISNULL(OLD.DAYS,0)) ELSE CONVERT(NUMERIC(18,2),ISNULL(OLDA.DAYS,0)) END), 
	HOUR_OLD = (CASE WHEN @MODE = 0 THEN CONVERT(NUMERIC(18,2),ISNULL(OLD.HOURS,0)) ELSE CONVERT(NUMERIC(18,2),ISNULL(OLDA.HOURS,0)) END),
	DPE.NO_TIME
FROM 
	DBO.SDOC DOC INNER JOIN DBO.TABELS T ON DOC.LINK = T.LINK_DOC
	INNER JOIN DBO.EMPL EM ON T.LINK_EMPL = EM.LINK
	INNER JOIN DBO.PERSON P ON EM.PERS_LINK = P.LINK
	INNER JOIN #SA_EMPLS_W  E ON T.LINK_EMPL = E.LINK_EMPL --DBO.SA_EMPLS_W_LITE_FN (@P,@VARKSDAT2,@BUF_ID) E ON T.LINK_EMPL = E.LINK_EMPL 
	INNER JOIN #DPEE DPE ON DPE.LINK_EMPL = E.LINK_EMPL AND DPE.LINK_SOVM = E.LINK_SOVM
	INNER JOIN DBO.GRAPH G ON E.GRAPH_LINK = G.LINK
	INNER JOIN DBO.GRAPHICS G1 ON G1.GRAPH_LINK = G.LINK AND MONTH(G1.PERIOD) = MONTH(@VARKSDDATE) AND YEAR(G1.PERIOD) = YEAR(@VARKSDDATE)
	LEFT JOIN ( 
		SELECT LINK_EMPL, LINK_SOVM = ISNULL(LINK_SOVM,0), LINK_PAYS, LINK_VKR, [DAYS] = MAX([DAYS]), [HOURS] = MAX([HOURS]), SUMMA = SUM(SUMMA) 
		FROM DBO.CALCULATE_JURNAL SJC 
			INNER JOIN DBO.SDOC_TABEL ST ON (SJC.LINK_DOC = ST.LINK_UP)
		WHERE 
			ST.REF_DOC = @VARKSNLINK 
		GROUP BY LINK_EMPL, LINK_SOVM, LINK_PAYS, LINK_VKR) OLD 
		ON OLD.LINK_EMPL = E.LINK_EMPL AND OLD.LINK_SOVM = E.LINK_SOVM AND OLD.LINK_PAYS = DPE.LINK_PAYS AND OLD.LINK_VKR = DPE.LINK_KBK
	LEFT JOIN ( 
		SELECT SJC.LINK_EMPL, LINK_SOVM = ISNULL(LINK_SOVM,0), LINK_PAYS, LINK_VKR, [DAYS] = MAX([DAYS]), [HOURS] = MAX([HOURS]), SUMMA = SUM(SUMMA) 
		FROM DBO.CALCULATE_JURNAL SJC INNER JOIN DBO.SDOC_TABEL ST ON (SJC.LINK_DOC = ST.LINK_UP)
		WHERE 
			MONTH(DATE_BEGIN) = MONTH(@VARKSDAT) AND YEAR(DATE_BEGIN) = YEAR(@VARKSDAT) 
		GROUP BY SJC.LINK_EMPL, LINK_SOVM, LINK_PAYS, LINK_VKR) OLDA 
		ON OLDA.LINK_EMPL = E.LINK_EMPL  AND OLDA.LINK_SOVM = E.LINK_SOVM AND OLDA.LINK_PAYS = DPE.LINK_PAYS AND OLDA.LINK_VKR = DPE.LINK_KBK
WHERE 	
	((DOC.LINK = @VARKSNLINK AND @MODE = 0) OR (@MODE IN (1,2) AND YEAR(T.PERIOD) = YEAR(@VARKSDDATE) AND MONTH(T.PERIOD) = MONTH(@VARKSDDATE)))
ORDER BY 
	SUBSTRING(LTRIM(RTRIM(ISNULL(P.FM,''))) + ' ' + LEFT(LTRIM(RTRIM(ISNULL(P.IM,''))),1) + '.' + LEFT(LTRIM(RTRIM(ISNULL(P.OT,''))),1) + '.',1,30)

--------------------------------------------------
DELETE FROM #VARKSTMP 
WHERE 
	(ISNULL([HOUR],0) = 0 AND NO_TIME <> 1)
	OR 
	SUMMA_ALL = 0

---------------------------------------------------
SELECT LINK_EMPL, LINK_SOVM, LINK_PAY = REF_PAY, LINK_KBK, SUMMA = SUM(SUMMA_ALL) INTO #TMP FROM #VARKSTMP GROUP BY LINK_EMPL, LINK_SOVM, REF_PAY, LINK_KBK

-------------------------------------------------
UPDATE #VARKSTMP  
SET 
	SUMMA_VIPL = SUMMA_VIPL * SUMMA_ALL / (SELECT TOP 1 (CASE WHEN ISNULL(SUMMA,0) <> 0 THEN ISNULL(SUMMA,0) ELSE 1 END) FROM #TMP T WHERE T.LINK_EMPL = T1.LINK_EMPL AND T.LINK_SOVM = T1.LINK_SOVM AND LINK_PAY = REF_PAY AND T.LINK_KBK=T1.LINK_KBK),
	[DAY] = [DAY]  - [DAY_OLD] * SUMMA_ALL / (SELECT TOP 1 (CASE WHEN ISNULL(SUMMA,0) <> 0 THEN ISNULL(SUMMA,0) ELSE 1 END) FROM #TMP T WHERE T.LINK_EMPL = T1.LINK_EMPL AND T.LINK_SOVM = T1.LINK_SOVM AND LINK_PAY = REF_PAY AND T.LINK_KBK=T1.LINK_KBK), 
	[HOUR] = [HOUR] - [HOUR_OLD] * SUMMA_ALL / (SELECT TOP 1 (CASE WHEN ISNULL(SUMMA,0) <> 0 THEN ISNULL(SUMMA,0) ELSE 1 END) FROM #TMP T WHERE T.LINK_EMPL = T1.LINK_EMPL AND T.LINK_SOVM = T1.LINK_SOVM AND LINK_PAY = REF_PAY AND T.LINK_KBK=T1.LINK_KBK)
FROM #VARKSTMP T1

---------------------------------------------------
UPDATE #VARKSTMP SET [SUMMA] = ISNULL([SUMMA_ALL],0)-ISNULL([SUMMA_VIPL],0)
FROM #VARKSTMP T1

------------------------------------------------
IF ISNULL(@LINK_R,0) <> 0 BEGIN
	DECLARE @PREVORD INT
	SET @PREVORD = ISNULL((SELECT MAX(ORDERS) FROM DBO.SDOC_TABEL_TABLE WHERE LINK_UP  = @LINK_R),0)

	INSERT INTO DBO.SDOC_TABEL_TABLE (
		LINK_UP,ORDERS,LINK_EMPL,LINK_SOVM,LINK_PAY,SUMMA_ALL,SUMMA_VIPL,SUMMA,SUMMA_BASE,DATE1,DATE2,DAYS,HOURS,DAY_NORM,HOUR_NORM,PERC,RATE,LINK_KBK
	)
	SELECT @LINK_R, ORDERS + @PREVORD, [LINK_EMPL],LINK_SOVM,[REF_PAY],ISNULL([SUMMA_ALL],0),ISNULL([SUMMA_VIPL],0),ISNULL([SUMMA],0),ISNULL([SUMMA_BASE],0),[DATE1],[DATE2],
			ISNULL(CONVERT(INT,[DAY]),0) AS [DAY],ISNULL([HOUR],0),ISNULL(CONVERT(INT,[DAY_NORM]),0) AS [DAY_NORM],ISNULL([HOUR_NORM],0),ISNULL([PERCENT],0),ISNULL([RATE],0), LINK_KBK
	FROM #VARKSTMP
	ORDER BY [NAME_EMPL], LINK_SOVM, CONVERT(INT,[CODE_PAY]), [DATE1_PAY]

	UPDATE dbo.SDOC
	SET SUMMA_T = ISNULL((SELECT SUM(SUMMA) FROM #VARKSTMP),0)
	WHERE LINK = @LINK_R
	
	IF @MODE = 0 AND ISNULL(@VARKSNLINK,0) > 0 BEGIN
		UPDATE dbo.SDOC SET FLAG_JC = 1 WHERE LINK = @VARKSNLINK
		DELETE FROM dbo.SA_DOCFR WHERE LINK = @VARKSNLINK
	END	

END ELSE
	SELECT [LINK],[ORDERS],[TAB_NUMER],[NAME_EMPL],[LINK_EMPL],[LINK_SOVM],[DATE1],[DATE2],		
 			 CONVERT(INT,[DAY]) AS [DAY],[HOUR],CONVERT(INT,[DAY_NORM]) AS [DAY_NORM],
		   [HOUR_NORM],[GRAPH_NAME],[GRAPH_LINK],[SUMMA_BASE],[SUMMA],
			 [SUMMA_VIPL],[SUMMA_ALL],[PERCENT],[RATE],[REF_PAY],[CODE_PAY],[NAME_PAY],[WAY_CALC],
			 [DATE1_PAY],[DATE2_PAY], LINK_KBK, CODE_KBK
	FROM #VARKSTMP
	ORDER BY [NAME_EMPL], LINK_SOVM, CONVERT(INT,[CODE_PAY]), [DATE1_PAY]

SET NOCOUNT OFF

RETURN 0







GO


GRANT EXECUTE ON dbo.[SD_N_TABEL_FILL] TO PUBLIC

GO


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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE dbo.KD_VACATION_VID_SAVE
	@varKSparLINK	int	OUTPUT,
	@varKSparCODE           CHAR(2) 		= '',
	@varKSparNAME           VARCHAR(150) = '',
	@varKSparTYPE_LINK      INT,
	@varKSparLINK_PAYS      INT		= null,
	@varKSparPERIOD1        TINYINT 	= 0,
	@BonusTakeTime		TINYINT 	= 0,
	@Time_Arche		TINYINT 	= 0,
	@NO_SAL			TINYINT 	= 0,
	@HOLIDAY		TINYINT 	= 0,
	@ADM			TINYINT 	= 0,
	@NOT_LGOT_EXPIR	TINYINT 	= 0,
	@IS_DOP VARCHAR(20) = NULL,
	@VAC_V TINYINT = 0
AS

DECLARE @varKSSQLError	int, 
		@varKSEventText	varchar(7000),
		@varKStrancount	int,  
		@varKSObjLink int, 
		@varKSRowCount INT


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

Set @BonusTakeTime = COALESCE(@BonusTakeTime,0)
Set @Time_Arche = COALESCE(@Time_Arche,0)
Set @NO_SAL = COALESCE(@NO_SAL,0)
SET @ADM = COALESCE(@ADM,0)

IF LEN(@varKSparNAME) = 0 OR LEN(@varKSparCODE) = 0 OR @varKSparTYPE_LINK IS NULL
BEGIN
	ROLLBACK
	RETURN 5
END

SET @VAC_V = CASE WHEN @VAC_V = 1 THEN 0 
				  WHEN @VAC_V = 2 THEN 1
				  WHEN @VAC_V = 3 THEN 2 
				  WHEN @VAC_V = 4 THEN 3
				  WHEN @VAC_V = 5 THEN 4
				  WHEN @VAC_V = 6 THEN 5 
				  END

SELECT @varKSObjLink = LINK FROM S_OBJECTS WHERE CODE = 'KD_VACATION_VID'

IF @varKSparLINK is null OR @varKSparLINK = 0
BEGIN
	INSERT INTO dbo.VACATION_VID WITH (ROWLOCK) (CODE,NAME,TYPE_LINK,LINK_PAYS,PERIOD1,BonusTakeTime,Time_Arche,NO_SAL,HOLIDAY,ADM, NOT_LGOT_EXPIR, IS_DOP,VAC_V) 
	VALUES (@varKSparCODE,@varKSparNAME,@varKSparTYPE_LINK,@varKSparLINK_PAYS,@varKSparPERIOD1, @BonusTakeTime,@Time_Arche,@NO_SAL,@HOLIDAY,@ADM,@NOT_LGOT_EXPIR, @IS_DOP,@VAC_V)
	SELECT @varKSSQLError = @@ERROR, @varKSparLINK = @@IDENTITY
	IF @varKSSQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
END
ELSE
BEGIN
	UPDATE dbo.VACATION_VID WITH (ROWLOCK) 
	SET CODE = @varKSparCODE,NAME = @varKSparNAME,TYPE_LINK = @varKSparTYPE_LINK,LINK_PAYS = @varKSparLINK_PAYS, 
        PERIOD1 = @varKSparPERIOD1, BonusTakeTime = @BonusTakeTime, Time_Arche = @Time_Arche, NO_SAL = @NO_SAL, HOLIDAY = @HOLIDAY, ADM = @ADM, NOT_LGOT_EXPIR = @NOT_LGOT_EXPIR,
        IS_DOP = @IS_DOP,VAC_V = @VAC_V
	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	


SET @varKSEventText = 'Виды отпусков' + ' ' +  RTRIM(CONVERT(VARCHAR(7000), @varKSparNAME))
EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @varKSEventText, @varKSObjLink, 'VACATION_VID', @varKSparLINK

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0





GO


GRANT EXECUTE ON dbo.[KD_VACATION_VID_SAVE] TO PUBLIC

GO


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

GO

CREATE  PROCEDURE [dbo].KU_PERS_MED_POL_SAVE
	@varKSparLINK	int	OUTPUT,
	@varKSparLINK_PERS	int	= null,
	@varKSparSER	varchar(15)	= null,
	@varKSparNUMBER	varchar(25)	= null,
	@varKSparDATE	datetime = null,
	@varKSparORG_WHOM varchar(254)= null,
	@varKSparORG_ADDR varchar(254)= null,
	@varKSparORG_PR_FIO	varchar(50)= null
	
AS
DECLARE @varKStrancount int, @varKSSQLError int, @varKSRowCount int, @varKScomment varchar(254), @varKSEventText varchar(254), @varKSObjectLink int


	set @varKSparDATE = LTRIM(RTRIM(ISNULL(@varKSparDATE, ''))) 
	set @varKSparSER = LTRIM(RTRIM(ISNULL(@varKSparSER,'')))
	SET @varKSparNUMBER = LTRIM(RTRIM(ISNULL(@varKSparNUMBER,'')))
	SET @varKSparORG_WHOM = LTRIM(RTRIM(ISNULL(@varKSparORG_WHOM,'')))

IF @varKSparSER ='' AND @varKSparNUMBER = ''
	BEGIN
		RETURN 0
	END				


SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	---СОХРАНЕНИЕ НОВОЙ ЗАПИСИ
	--- Если запись новая и нет других записей по физ лицу 	
IF (@varKSparLINK is null OR @varKSparLINK = 0)
BEGIN	

	IF not exists (select * from MED_POL where LINK_PERS = @varKSparLINK_PERS )  
	BEGIN
		IF @varKSparLINK = 0 or @varKSparLINK is NULL
		BEGIN
			IF isnull(@varKSparNUMBER,'') = '' AND (@varKSparSER<>'' OR  @varKSparORG_WHOM<>'' OR @varKSparORG_ADDR<>'' OR @varKSparORG_PR_FIO<> '')
			BEGIN
				RAISERROR('Требуется указать номер страхового медицинского полиса!', 11, 1)
				ROLLBACK
				RETURN 5
			END	
			IF isnull(@varKSparDATE,'19000101') ='19000101'   AND (@varKSparSER<>'' OR  @varKSparNUMBER<>'' OR @varKSparORG_WHOM<>'' OR @varKSparORG_ADDR<>'' OR @varKSparORG_PR_FIO<> '')
			BEGIN
				RAISERROR('Требуется указать дату выдачи страхового медицинского полиса!', 11, 1)
				ROLLBACK
				RETURN 5
			END	
			
			INSERT INTO MED_POL WITH (ROWLOCK) (LINK_PERS, SER,  NUMBER, [DATE], ORG_WHOM, ORG_ADDR, ORG_PR_FIO)
			VALUES (@varKSparLINK_PERS, @varKSparSER, @varKSparNUMBER, @varKSparDATE, @varKSparORG_WHOM, @varKSparORG_ADDR,
					@varKSparORG_PR_FIO)

			SELECT @varKSSQLError = @@ERROR, @varKSparLINK = @@IDENTITY
			IF @varKSSQLError <> 0
			BEGIN
				ROLLBACK
				RETURN 7
			END
			---- обновление PERSON 
			IF exists (select * from person where link = @varKSparLINK_PERS and ISNULL(MED_POL_LINK,0) = 0 )
			BEGIN
				UPDATE PERSON SET MED_POL_LINK = @varKSparLINK, MED_POL_SER = @varKSparSER,MED_POL_NUM = @varKSparNUMBER			
				WHERE link=@varKSparLINK_PERS
				SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
				IF @varKSSQLError <> 0
				BEGIN
					ROLLBACK
					RETURN 7
				END
				IF @varKSRowCount = 0
				BEGIN
					ROLLBACK
					RETURN 2
				END
			END
		END	
	END
	ELSE
	BEGIN
		--- Если запись новая и есть другие записи но с другой датой по физ лицу 	
			IF isnull(@varKSparNUMBER,'') = '' AND (@varKSparSER<>'' OR  @varKSparORG_WHOM<>'' OR @varKSparORG_ADDR<>'' OR @varKSparORG_PR_FIO<> '')
			BEGIN
				RAISERROR('Требуется указать номер страхового медицинского полиса!', 11, 1)
				ROLLBACK
				RETURN 5
			END	
			IF isnull(@varKSparDATE,'19000101') ='19000101' AND (@varKSparSER<>'' OR  @varKSparNUMBER<>'' OR @varKSparORG_WHOM<>'' OR @varKSparORG_ADDR<>'' OR @varKSparORG_PR_FIO<> '')
			BEGIN
				RAISERROR('Требуется указать дату выдачи страхового медицинского полиса!', 11, 1)
				ROLLBACK
				RETURN 5
			END	
		
		IF exists (select * from MED_POL where LINK_PERS = @varKSparLINK_PERS and  [DATE] <> @varKSparDATE)  
		BEGIN

			IF not exists (select * from MED_POL where LINK_PERS = @varKSparLINK_PERS and  [DATE] = @varKSparDATE) 
			BEGIN
				INSERT INTO MED_POL WITH (ROWLOCK) (LINK_PERS, SER, NUMBER, [DATE], ORG_WHOM, ORG_ADDR, ORG_PR_FIO)
					VALUES (@varKSparLINK_PERS, @varKSparSER, @varKSparNUMBER, @varKSparDATE, @varKSparORG_WHOM, @varKSparORG_ADDR,
							@varKSparORG_PR_FIO)

				SELECT @varKSSQLError = @@ERROR, @varKSparLINK = @@IDENTITY
				IF @varKSSQLError <> 0
				BEGIN
					ROLLBACK
					RETURN 7
				END
				---- обновление PERSON 
				IF (select max([date]) from MED_POL where LINK_PERS = @varKSparLINK_PERS and [DATE] <> @varKSparDATE) < @varKSparDATE
				BEGIN
					IF exists (select * from person where link = @varKSparLINK_PERS and ISNULL(MED_POL_LINK,0) <> 0 )
					BEGIN
						UPDATE PERSON SET MED_POL_LINK = @varKSparLINK, MED_POL_SER = @varKSparSER, MED_POL_NUM = @varKSparNUMBER			
						WHERE link=@varKSparLINK_PERS
						SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
						IF @varKSSQLError <> 0
						BEGIN
							ROLLBACK
							RETURN 7
						END
						IF @varKSRowCount = 0
						BEGIN
							ROLLBACK
							RETURN 2
						END
					END
				END
			END
			ELSE BEGIN
				RAISERROR('Страховой полис с указанной датой уже существует!', 11, 1)
				RETURN 5
			END		
		END
	END
END
ELSE
BEGIN
				--ОБНОВЛЕНИЕ

			IF isnull(@varKSparNUMBER,'') = '' AND (@varKSparSER<>'' OR  @varKSparORG_WHOM<>'' OR @varKSparORG_ADDR<>'' OR @varKSparORG_PR_FIO<> '')
			BEGIN
				RAISERROR('Требуется указать номер страхового медицинского полиса!', 11, 1)
				ROLLBACK
				RETURN 5
			END	
	
			IF isnull(@varKSparDATE,'19000101') ='19000101' AND (@varKSparSER<>'' OR  @varKSparNUMBER<>'' OR @varKSparORG_WHOM<>'' OR @varKSparORG_ADDR<>'' OR @varKSparORG_PR_FIO<> '')
			BEGIN
				RAISERROR('Требуется указать дату выдачи страхового медицинского полиса!', 11, 1)
				ROLLBACK
				RETURN 5
			END		
				
			UPDATE MED_POL SET LINK_PERS = @varKSparLINK_PERS, SER = @varKSparSER, NUMBER = @varKSparNUMBER, [DATE] = @varKSparDATE, 
				ORG_WHOM = @varKSparORG_WHOM, ORG_ADDR = @varKSparORG_ADDR, ORG_PR_FIO = @varKSparORG_PR_FIO
			WHERE link=@varKSparLINK
			SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
			IF @varKSSQLError <> 0
			BEGIN
				ROLLBACK
				RETURN 7
			END
			IF @varKSRowCount = 0
			BEGIN
				if (@varKSparLINK is null OR @varKSparLINK = 0) and exists (select * from MED_POL where LINK_PERS = @varKSparLINK_PERS and  [DATE] =  @varKSparDATE)
				BEGIN
				
					ROLLBACK
					
					RETURN 8
				END
				ELSE
				BEGIN
					ROLLBACK
					RETURN 2
				END
			END
			--- обновим PERSON
			IF exists (select * from person where link = @varKSparLINK_PERS and ISNULL(MED_POL_LINK,0) = @varKSparLINK and  ISNULL(MED_POL_SER,0) <> @varKSparSER  and  ISNULL(MED_POL_NUM,0) <> @varKSparNUMBER  )
				BEGIN
						UPDATE PERSON SET MED_POL_SER= @varKSparSER ,MED_POL_NUM = @varKSparNUMBER		
						WHERE link=@varKSparLINK_PERS
						SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
						IF @varKSSQLError <> 0
						BEGIN
							ROLLBACK
							RETURN 7
						END
						IF @varKSRowCount = 0
						BEGIN
							ROLLBACK
							RETURN 2
						END
				END
		
		
		
END	
	SELECT @varKSObjectLink = link FROM s_objects WHERE code='MED_POL'
	SET @varKSEventText = 'История полиса ' + dbo.ku_GetPersFIO(@varKSparLINK_PERS)
	EXECUTE WF_GENERATEEVENT 'Сохранение строки', @varKSEventText, @varKSObjectLink, 'ACAD_DEGREE', @varKSparLINK


IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0





GO


GRANT EXECUTE ON dbo.[KU_PERS_MED_POL_SAVE] TO PUBLIC

GO



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

GO





/*
© Кейсистемс (Keysystems), 2006
Информация об отправителе для выгрузки БО
*/




CREATE          PROCEDURE [dbo].BB_EXPORT_BN
		--@iTableNum	tinyint,
		@cBuffId	varchar(30) = ''
AS
DECLARE @iDepLink	int,
		@iLinkOld	int,
		@iLink		int,
		@iNumRec	int,
		@iLinkG		int

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

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


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


declare @tTemp table (LINK int, NUMBER varchar(25), DATE_PROV datetime, ACC int, OSN_LINK int, KOR_ACC INT)
insert into @tTemp
select distinct PO.LINK,
				PO.NUMBER, 
				PO.DATE_PROV, 
				ACC = isnull(PO.ACC, BO.LINK_ACCOUNT), 
				O.LINK,
				KOR_ACC = isnull(FC.LINK_G_PROV,(select top 1 GAP.DEP_ACC
											from dbo.G_PROV_AP GAP
											inner join dbo.G_PROV2 G2 on G2.LINK = GAP.LINK_UP
											inner join dbo.G_PROV1 G1 on G1.LINK = G2.LINK_UP and G1.LINK_UP = O.DOC_LINK 
											inner join dbo.DEPARTMENT_ACCOUNTS DA on GAP.DEP_ACC = DA.LINK and DA.LINK_UP <> GAP.DEP)) 
from dbo.G_PROV PO
inner join dbo.G_PROV1 POG1 on PO.LINK = POG1.LINK_UP
inner join dbo.G_PROV2 POG2 on POG1.LINK = POG2.LINK_UP 
inner join dbo.JURN_BO BO on BO.LINK_PO_PROV = POG2.LINK
inner join dbo.BD_OSNOV O on BO.LINK_DOC = O.LINK
--inner join dbo.G_PROV DOC on DOC.LINK = O.DOC_LINK
left join dbo.FINANSE_CONTRACT_HEAD FC ON O.DOC_LINK = FC.LINK_G_PROV
where PO.link in (select LINK from dbo.BufferGetTableByID(@cBuffId))

-- Блок BN
select		LINK = T.LINK,
			LINK_UP = T.LINK,
			GUID_FK = '',
			KOD_UBP_PBS = D.DEP_B_CODE,
			NAME_UBP_PBS = D.DEP_FNAME,
			LS_NUM = D.ACC_CODE,
			GLAVA_GRBS = D.GRBS_CODE,
			NAME_GRBS = D.GRBS_NAME,
			NAME_BUD = D.BUDG_NAME,
			NAME_FO = D.FO_NAME,
			KOD_TOFK = D.TOFK_CODE,
			NAME_TOFK = D.TOFK_NAME,
			DOL_RUK = B.POST_NAME, 
			NAME_RUK = B.SHORT_NAME,
			DATE_POD = T.DATE_PROV,
			NOM_BO = '',
			DATE_FK = '',
			NOTE_FK = '',
			DOL_ISP = '',
			NAME_ISP = '',
			TEL_ISP = ''
from @tTemp T 
inner join dbo.BB_DEP_ACC_DOP(null) D on D.ACC_LINK = T.ACC 
left join dbo.GetOtvFaceData(@iDepLink, 'Руководитель') B on D.DEP_LINK = B.LINK_DEP


-- Блок BNOSN
select	LINK = T.LINK,
		LINK_UP = T.LINK,
		DOC_VID_OSN = case FC.GZ when 1 then '1' else '2' end,
		NOM_DOC = O.NUMBER,
		DATE_DOC = O.DATE,
		DATE_DOC_BEG = ISNULL(FC.DATE_BEGIN, O.DATE),
		DATE_DOC_END = FC.DATE_END,
		SUM_S = G.SUMMA,
		KOD_CUR = '643',
		SUM_R = 0,
		PROC_PRERPAY = '',
		SUM_PREPAY = G.SUMMA
from @tTemp T 
inner join dbo.BD_OSNOV O on T.OSN_LINK = O.LINK
inner join dbo.G_PROV G on O.DOC_LINK = G.LINK
left join dbo.FINANSE_CONTRACT_HEAD FC on O.DOC_LINK = FC.LINK_G_PROV 


-- Блок BNCONTR
select	LINK = T.LINK,
		LINK_UP = T.LINK,
		NAME_CONTR = D.FULL_NAME,
		INN = D.INN_LONG,
		KPP = D.KPP,
		COUNTRY = 'Российская Федерация',
		OKSM = '643',
		ADDRESS = dbo.GetAddressByKladr(D.REF_LINK_A),
		TEL = '',
		STATUS = DEP_TYPE2,
		BS_R_SCH = DA.CODE,
		NAME_BIC = DA.BANK_NAME,
		BIC = DA.BANK_CODE,
		BS_K_SCH = DA.BANK_KS

		
from @tTemp T 
inner join dbo.DICTIONARY_ACCOUNTS DA on T.KOR_ACC = DA.LINK
inner join dbo.DICTIONARY_DEPARTMENT D on DA.REF_LINK_D = D.LINK


-- Блок BNEXREQ
select	LINK = T.LINK,
		LINK_UP = T.LINK,
		ORDER_VID = cast((case when FC.DOG_LINK is not null then '8'
						 when FC.TYPE in (3,4,6) then FC.TYPE - 1
						 when FC.TYPE in (1,7) then FC.TYPE 
						 when FC.TYPE = 8 then 4 else '0' end) as char(1)),
		DATE_ITOG = GZ_DATE,
		DOC_VID_GK = case when charindex('№', FC.MAINTENANCE) > 0 then ltrim(rtrim(left(FC.MAINTENANCE,charindex('№', FC.MAINTENANCE) - 1))) else '' end,
		NOM_DOC_GK = case when charindex('№', FC.MAINTENANCE) > 0  and charindex(' от ', FC.MAINTENANCE) > 0 then ltrim(rtrim(substring(FC.MAINTENANCE,charindex('№', FC.MAINTENANCE) + 2, len(FC.MAINTENANCE) - charindex(' от ', FC.MAINTENANCE) - 7))) else '' end,
		DATE_DOC_GK = convert(datetime, case when charindex(' от ', FC.MAINTENANCE) > 0 then ltrim(rtrim(right(FC.MAINTENANCE,len(FC.MAINTENANCE) - charindex(' от ', FC.MAINTENANCE) - 3))) else '' end,104),
		NOM_REGISTER = GZ_NUM
from @tTemp T 
inner join dbo.BD_OSNOV O on T.OSN_LINK = O.LINK
inner join dbo.FINANSE_CONTRACT_HEAD FC on O.DOC_LINK = FC.LINK_G_PROV and FC.GZ = 1
inner join dbo.G_PROV G on FC.Link_G_Prov = G.LINK
 


-- Блок BOST
--if @iTableNum = 5


declare @tTemp1 table (LINK int identity(1,1), NOM_LINE int, [SOURCE] char(1), KBK int, SGU int, DCL int, G_LINK INT, COMMENT varchar(254), 
						sum1 numeric(20,2), sum2 numeric(20,2), sum3 numeric(20,2), sum4 numeric(20,2), sum5 numeric(20,2), sum6 numeric(20,2), 
						sum7 numeric(20,2), sum8 numeric(20,2), sum9 numeric(20,2), sum10 numeric(20,2), sum11 numeric(20,2), sum12 numeric(20,2))

insert into @tTemp1([SOURCE], KBK, SGU, DCL, G_LINK, COMMENT, sum1, sum2, sum3, sum4, sum5, sum6, sum7, sum8, sum9, sum10, sum11, sum12)
select SA.cSource, GAP.KBK, GAP.SGU, GAP.AP2, G.LINK, OG.COMMENT,
		sum(case month(isnull(GAP.INDATE,G.DATE_PROV)) when 1 then g2.summa else 0 end),
		sum(case month(isnull(GAP.INDATE,G.DATE_PROV)) when 2 then g2.summa else 0 end),
		sum(case month(isnull(GAP.INDATE,G.DATE_PROV)) when 3 then g2.summa else 0 end),
		sum(case month(isnull(GAP.INDATE,G.DATE_PROV)) when 4 then g2.summa else 0 end),
		sum(case month(isnull(GAP.INDATE,G.DATE_PROV)) when 5 then g2.summa else 0 end),
		sum(case month(isnull(GAP.INDATE,G.DATE_PROV)) when 6 then g2.summa else 0 end),
		sum(case month(isnull(GAP.INDATE,G.DATE_PROV)) when 7 then g2.summa else 0 end),
		sum(case month(isnull(GAP.INDATE,G.DATE_PROV)) when 8 then g2.summa else 0 end),
		sum(case month(isnull(GAP.INDATE,G.DATE_PROV)) when 9 then g2.summa else 0 end),
		sum(case month(isnull(GAP.INDATE,G.DATE_PROV)) when 10 then g2.summa else 0 end),
		sum(case month(isnull(GAP.INDATE,G.DATE_PROV)) when 11 then g2.summa else 0 end),
		sum(case month(isnull(GAP.INDATE,G.DATE_PROV)) when 12 then g2.summa else 0 end)
from dbo.G_PROV G
inner join dbo.G_PROV1 G1 on G.LINK = G1.LINK_UP 
inner join dbo.G_PROV2 G2 on G1.LINK = G2.LINK_UP 
inner join dbo.G_PROV_AP GAP on G2.LINK = GAP.LINK_UP and GAP.DB_KR = 1
inner join dbo.JURN_BO BO on BO.LINK_PO_PROV = G2.LINK
inner join dbo.BD_OSNOV O on BO.LINK_DOC = O.LINK
inner join dbo.G_PROV OG on O.DOC_LINK = OG.LINK
inner join dbo.S_ACCOUNTS SA on SA.LINK = GAP.ACCOUNT 
where G.link in (select LINK from dbo.BufferGetTableByID(@cBuffId))
group by SA.cSource, GAP.KBK, GAP.SGU, GAP.AP2, G.LINK, OG.COMMENT


DECLARE NumCur CURSOR LOCAL STATIC READ_ONLY FOR
SELECT LINK, G_LINK
FROM  @tTemp1 
order by G_LINK, LINK
SET @iLinkOld = 0


OPEN NumCur
FETCH NEXT FROM NumCur INTO @iLink, @iLinkG
WHILE @@FETCH_STATUS = 0
BEGIN
	if @iLinkOld <> @iLinkG
		select @iNumRec = 1, @iLinkOld = @iLinkG
	else 
		SET @iNumRec = @iNumRec + 1
	update @tTemp1 set NOM_LINE = @iNumRec where LINK = @iLink
	FETCH NEXT FROM NumCur INTO @iLink, @iLinkG
END

CLOSE NumCur
DEALLOCATE NumCur



select	LINK = T.LINK,
		LINK_UP = T.G_LINK,
		T.NOM_LINE,
		SR_FIN  = T.[SOURCE],
		KBK = left(replace(KBK.CODE + SGU.CODE,'.',''),30),
		TYPE_KBK = case KBK.TYPE when 1 then '10'
								 when 2 then '20'
								 when 4 then '31'
								 when 8 then '32'	 else '' end,
		SUBJ = T.COMMENT,
		SUM_JAN = T.SUM1,
		SUM_FEB = T.SUM2,
		SUM_MAR = T.SUM3,
		SUM_APR = T.SUM4,
		SUM_MAY = T.SUM5,
		SUM_JUN = T.SUM6,
		SUM_JUL = T.SUM7,
		SUM_AUG = T.SUM8,
		SUM_SEP = T.SUM9,
		SUM_OCT = T.SUM10,
		SUM_NOV = T.SUM11,
		SUM_DEC = T.SUM12,
		SUM_YEAR = T.SUM1 + T.SUM2 + T.SUM3 + T.SUM4 + T.SUM5 + T.SUM6 + T.SUM7 + T.SUM8 + T.SUM9 + T.SUM10 + T.SUM11 + T.SUM12,
		NOTE = '',
		ADD_KLASS = isnull(DCL.CODE,''),
		SUM_2_YEAR = 0,
		SUM_3_YEAR = 0,
		SUM_4_YEAR = 0,
		SUM_5_YEAR = 0
	from @tTemp1 T 
	left join dbo.KL_KBK KBK on KBK.LINK = T.KBK 
	left join dbo.KOSGU SGU on SGU.LINK = T.SGU 
	left join dbo.DOP_CLASSIF DCL on DCL.LINK = T.DCL 


GO


GRANT EXECUTE ON dbo.[BB_EXPORT_BN] TO PUBLIC

GO



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

GO

CREATE PROCEDURE [dbo].SD_N_TABEL_FILL_EMPL
	@LINK_EMPL INT = -1,	
	@VARKSDDATE DATETIME = NULL,
	@LINK_KBK INT = NULL,
	@DEP_LINK INT = NULL
AS
/*
ИСПОЛЬЗУЕТСЯ В НАЧИСЛЕНИИ СВЕРХУРОЧНЫХ
*/
SET @LINK_KBK = COALESCE(@LINK_KBK,0)

SET NOCOUNT ON

DECLARE 	
		@VARKSDAT  [DATETIME], 
		@VARKSDAT1 [DATETIME],
		@VARKSDAT2 [DATETIME],
		@EM DATETIME

SET @EM	 = DBO.DATEENDOFMONTH(@VARKSDDATE)
SET @VARKSDAT	=CONVERT(DATETIME,ISNULL(@VARKSDDATE,GETDATE()),104)
SET @VARKSDAT1 	= DATEADD(DAY,1-DAY(@VARKSDAT),@VARKSDAT)
SET @VARKSDAT2 	= DATEADD(DAY,-1,DATEADD(MONTH,1,@VARKSDAT1))

DECLARE @BASIS_SUM TABLE (LINK_EMPL INT, LINK_SOVM INT, LINK_PAY INT, SUMMA_BASE NUMERIC(18,2), PERC NUMERIC(18,2), SUMMA NUMERIC(18,2), LINK_KBK INT, WAY_CALC TINYINT, DATE_BEGIN DATETIME, DATE_END DATETIME )

IF DBO.SA_GET_OPTION_BY_CODE('DOC_ADD_PREMIUM_OPT3') = 1 BEGIN
	INSERT INTO @BASIS_SUM (LINK_EMPL, LINK_SOVM, LINK_PAY, SUMMA_BASE, PERC, SUMMA, LINK_KBK, WAY_CALC, DATE_BEGIN, DATE_END)
	SELECT LINK_EMPL, LINK_SOVM, LINK_PAYS, SUMMA_BASE, PERC, SUMMA, LINK_KBK, WAY_CALC, DATE_BEGIN, DATE_END FROM DBO.SA_ALL_PAYS_ALL(@LINK_EMPL, @EM, DEFAULT, @DEP_LINK, DEFAULT) WHERE LINK_SOVM = 0
END
ELSE BEGIN
	INSERT INTO @BASIS_SUM (LINK_EMPL, LINK_SOVM, LINK_PAY, SUMMA_BASE, PERC, SUMMA, LINK_KBK, WAY_CALC, DATE_BEGIN, DATE_END)
	SELECT LINK_EMPL, LINK_SOVM, LINK_PAY, SUMMA_BASE, PERC, SUMMA, LINK_KBK, 1, @VARKSDDATE, @EM FROM DBO.SA_ALL_PAYS_ALL_DATE0(@LINK_EMPL,@EM, DEFAULT, @DEP_LINK)  WHERE LINK_SOVM = 0
END

DECLARE @VARKSTMP TABLE
([LINK] 				[INT],
 [ORDERS]			[INT],
 [TAB_NUMER]			[VARCHAR] (6),
 [NAME_EMPL]			[VARCHAR] (30),
 [REF_EMPL]			[INT],
 [DATE1]				[DATETIME],
 [DATE2]				[DATETIME],
 [DAY]				[NUMERIC] (4,0),
 [HOUR]				[NUMERIC] (10,2),
 [DAY_NORM]			[NUMERIC] (10,4),
 [HOUR_NORM]			[NUMERIC] (10,2),
 [GRAPH_NAME]			[VARCHAR] (30),
 [GRAPH_LINK]			[INT],
 [SUMMA_BASE]			[NUMERIC] (18,2),
 [SUMMA] 			[NUMERIC] (18,2),
 [SUMMA_VIPL]			[NUMERIC] (18,2),
 [SUMMA_ALL]			[NUMERIC] (18,2),
 [PERCENT]			[NUMERIC] (18,2),
 [RATE]				[NUMERIC] (5,2),
 [REF_PAY]			[INT],
 [CODE_PAY]			[VARCHAR] (10),
 [NAME_PAY]			[VARCHAR] (60),
 [WAY_CALC]			[TINYINT],
 [DATE1_PAY]			[DATETIME],  
 [DATE2_PAY]			[DATETIME], 
 LINK_KBK			INT,
 CODE_KBK			VARCHAR(30))


INSERT INTO @VARKSTMP ([LINK],[ORDERS],[TAB_NUMER],[NAME_EMPL],[REF_EMPL],[DATE1],[DATE2],		
						[DAY],[HOUR],[DAY_NORM],[HOUR_NORM],[GRAPH_NAME],[GRAPH_LINK],[SUMMA_BASE],[SUMMA],
						[SUMMA_VIPL],[SUMMA_ALL],[PERCENT],[RATE],[REF_PAY],[CODE_PAY],[NAME_PAY],[WAY_CALC],
						[DATE1_PAY],[DATE2_PAY],LINK_KBK,CODE_KBK)
SELECT 
	[LINK]				= 0,
	[ORDERS]			= 0,
	[TAB_NUMER]			= LEFT(E.TAB,6),
	[NAME_EMPL]			= LEFT(DBO.SD_GETEMPLNAME(E.LINK),30),
	[REF_EMPL] 			= E.LINK,
	[DATE1]				= @VARKSDAT1,
	[DATE2]				= @VARKSDAT2,
	[DAY]				= ISNULL(CONVERT(NUMERIC(4,0),DBO.SA_GET_EMPL_WD(E.LINK, 0, 0, DPE.DATE_BEGIN, DPE.DATE_END, DEFAULT, DEFAULT)),0),
	[HOUR]				= ISNULL(CONVERT(NUMERIC(10,2),DBO.SA_GET_EMPL_WH(E.LINK, 0, 0, DPE.DATE_BEGIN, DPE.DATE_END, DEFAULT, DEFAULT)),0),
	[DAY_NORM]			= ISNULL(CONVERT(NUMERIC(4,0),DBO.NORM_DAYS(E.LINK,MONTH(@VARKSDAT1),YEAR(@VARKSDAT1))),0),
	[HOUR_NORM] 			= ISNULL(CONVERT(NUMERIC(10,2),DBO.NORM_HOURS(E.LINK,MONTH(@VARKSDAT1),YEAR(@VARKSDAT1))),0),
	[GRAPH_NAME]			= LEFT(G.NAME,30),
	[GRAPH_LINK]			= E.GRAPH_LINK,
	[SUMMA_BASE]			= ISNULL(CONVERT(NUMERIC(18,2), DPE.SUMMA_BASE ),0),
	[SUMMA]			= ISNULL(CONVERT(NUMERIC(18,2), DPE.SUMMA ),0),
	[SUMMA_VIPL]			= 0,
	[SUMMA_ALL]			= ISNULL(CONVERT(NUMERIC(18,2), DPE.SUMMA ),0),
	[PERCENT] 			= PERC,
	[RATE]				= COALESCE(NS.NUM_STAKE,0),
	[REF_PAY]			= DPE.LINK_PAY,
	[CODE_PAY]			= SUBSTRING(RTRIM(LTRIM(PS.CODE)),1,10),
	[NAME_PAY]			= SUBSTRING(RTRIM(LTRIM(PS.NAME)),1,60),
	[WAY_CALC]			= DPE.WAY_CALC,
	[DATE1_PAY]			= DPE.DATE_BEGIN,
	[DATE2_PAY]			= DPE.DATE_END,
	DPE.LINK_KBK, LEFT(SFIN.CODE,20)
FROM 
	DBO.EMPL E INNER JOIN @BASIS_SUM DPE ON DPE.LINK_EMPL = E.LINK 
	INNER JOIN DBO.PAYS PS ON PS.LINK = DPE.LINK_PAY
	INNER JOIN DBO.GRAPH G ON G.LINK = E.GRAPH_LINK
	LEFT JOIN DBO.SA_EMPLSNUMSTAKE(@LINK_EMPL,@EM) NS ON NS.EMPL_LINK = E.LINK
	LEFT JOIN DBO.SAL_SFIN SFIN ON SFIN.LINK = DPE.LINK_KBK
WHERE 
	E.LINK = @LINK_EMPL 
	AND DPE.SUMMA  > 0
	AND (@LINK_KBK = 0 OR @LINK_KBK = DPE.LINK_KBK)
ORDER BY 3

SET NOCOUNT OFF

SELECT 
	[LINK],[ORDERS],[TAB_NUMER],[NAME_EMPL],[REF_EMPL],[DATE1],[DATE2],		
	CONVERT(INT,[DAY]) AS [DAY],[HOUR],CONVERT(INT,[DAY_NORM]) AS [DAY_NORM],
	[HOUR_NORM],[GRAPH_NAME],[GRAPH_LINK],[SUMMA_BASE],[SUMMA],
	[SUMMA_VIPL],[SUMMA_ALL],[PERCENT],[RATE],[REF_PAY],[CODE_PAY],[NAME_PAY],[WAY_CALC],
	[DATE1_PAY],[DATE2_PAY], LINK_KBK, CODE_KBK
FROM 
	@VARKSTMP




GO


GRANT EXECUTE ON dbo.[SD_N_TABEL_FILL_EMPL] TO PUBLIC

GO



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

GO


/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE [dbo].KU_PERSON_MED_POL_SAVE
	@varKSparMED_POL_LINK	 int  output  ,
	@varKSparLINK	int = null,
	@varKSparMED_POL_SER	varchar(15) = '',
	@varKSparMED_POL_NUM	varchar(25) = '',
	@varKSparMED_POL_DATE	datetime = null,
	@varKSparMED_POL_WHOM	varchar(254) = '',
	@varKSparMED_POL_ADDR	varchar(254) = '',
	@varKSparMED_POL_PR_FIO	varchar(50) = ''

AS

SET @varKSparMED_POL_SER = RTRIM(LTRIM(@varKSparMED_POL_SER))
SET @varKSparMED_POL_NUM = RTRIM(LTRIM(@varKSparMED_POL_NUM))
SET @varKSparMED_POL_WHOM = RTRIM(LTRIM(@varKSparMED_POL_WHOM))
SET @varKSparMED_POL_ADDR = RTRIM(LTRIM(@varKSparMED_POL_ADDR))
SET @varKSparMED_POL_PR_FIO = RTRIM(LTRIM(@varKSparMED_POL_PR_FIO))

IF @varKSparMED_POL_SER ='' AND @varKSparMED_POL_NUM = ''
	BEGIN
		RETURN 0
	END				


DECLARE @varKSERROR tinyint, @varKStrancount int, @varKSSQLError int, @varKSRowCount int, @varKScomment varchar(254) , @UPD_OLD tinyint

SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	
	IF @varKSparLINK IS NULL
	BEGIN
		ROLLBACK
		RETURN 5
	END
		
	IF exists(SELECT link FROM person WHERE link=@varKSparLINK)
	BEGIN
		IF @varKSparMED_POL_LINK = 0 or @varKSparMED_POL_LINK is NULL
		BEGIN
				IF isnull(@varKSparMED_POL_NUM,'') = '' AND (@varKSparMED_POL_SER<>'' OR  @varKSparMED_POL_WHOM<>'' OR @varKSparMED_POL_ADDR<>'' OR @varKSparMED_POL_PR_FIO<> '')
			BEGIN
				RAISERROR('Требуется указать номер страхового медицинского полиса!', 11, 1)
				ROLLBACK
				RETURN 5
			END	
			IF isnull(@varKSparMED_POL_DATE,'19000101') = '19000101' AND (@varKSparMED_POL_SER<>'' OR  @varKSparMED_POL_NUM<>'' OR @varKSparMED_POL_WHOM<>'' OR @varKSparMED_POL_ADDR<>'' OR @varKSparMED_POL_PR_FIO<> '')
			BEGIN
				RAISERROR('Требуется указать дату выдачи страхового медицинского полиса!', 11, 1)
				ROLLBACK
				RETURN 5
			END	


			INSERT INTO MED_POL WITH (ROWLOCK) (LINK_PERS,SER, [NUMBER],[DATE],ORG_WHOM,ORG_ADDR,ORG_PR_FIO)
			VALUES (@varKSparLINK, @varKSparMED_POL_SER, @varKSparMED_POL_NUM,@varKSparMED_POL_DATE,@varKSparMED_POL_WHOM,@varKSparMED_POL_ADDR,@varKSparMED_POL_PR_FIO)
			SELECT @varKSSQLError = @@ERROR, @varKSparMED_POL_LINK = @@IDENTITY
			IF @varKSSQLError <> 0
			BEGIN
				ROLLBACK
				RETURN 7
			END	
			
			UPDATE person set MED_POL_LINK = @varKSparMED_POL_LINK  
			where link = @varKSparLINK
			SELECT @varKSSQLError = @@ERROR
			IF @varKSSQLError <> 0
			BEGIN
				ROLLBACK
				RETURN 7
			END			
		END
		ELSE
		BEGIN	
			---------- Если линк полиса в PERSON есть , то проверим есть ли в MED_POL полис по этому человеку на эту же дату - если есть ОБНОВЛЯЕМ ЗАПИСЬ
			IF isnull(@varKSparMED_POL_NUM,'') = '' AND (@varKSparMED_POL_SER<>'' OR  @varKSparMED_POL_WHOM<>'' OR @varKSparMED_POL_ADDR<>'' OR @varKSparMED_POL_PR_FIO<> '')
			BEGIN
				RAISERROR('Требуется указать номер страхового медицинского полиса!', 11, 1)
				ROLLBACK
				RETURN 5
			END	
	
			IF isnull(@varKSparMED_POL_DATE,'19000101') = '19000101' AND (@varKSparMED_POL_SER<>'' OR  @varKSparMED_POL_NUM<>'' OR @varKSparMED_POL_WHOM<>'' OR @varKSparMED_POL_ADDR<>'' OR @varKSparMED_POL_PR_FIO<> '')
			BEGIN
	
				RAISERROR('Требуется указать дату выдачи страхового медицинского полиса!', 11, 1)
				ROLLBACK
				RETURN 5
			END	


			IF @varKSparMED_POL_NUM is not null and @varKSparMED_POL_SER is NOT NULL AND isnull(@varKSparMED_POL_DATE,'19000101') <> '19000101'
			BEGIN

					if exists (select * from MED_POL where  link_pers=@varKSparLINK and date = @varKSparMED_POL_DATE  )
					BEGIN  
					    DECLARE @LINK_MED int 
						set @LINK_MED = (select link from MED_POL where  link_pers=@varKSparLINK and date = @varKSparMED_POL_DATE)
	
						UPDATE M SET  SER = @varKSparMED_POL_SER, NUMBER = @varKSparMED_POL_NUM, DATE = @varKSparMED_POL_DATE, ORG_WHOM = @varKSparMED_POL_WHOM,
							ORG_ADDR = @varKSparMED_POL_ADDR, ORG_PR_FIO = @varKSparMED_POL_PR_FIO
						from dbo.MED_POL m	
						WHERE m.link_pers=@varKSparLINK and link = @LINK_MED
						
						SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
						IF @varKSSQLError <> 0
						BEGIN
							ROLLBACK
							RETURN 7
						END
						IF @varKSRowCount = 0
						BEGIN
							ROLLBACK
							RETURN 2
						END
						
						UPDATE person set MED_POL_LINK = @varKSparMED_POL_LINK   
						where link = @varKSparLINK
						SELECT @varKSSQLError = @@ERROR
						IF @varKSSQLError <> 0
						BEGIN
							ROLLBACK
							RETURN 7
						END		
					END 
					ELSE 
					BEGIN
					
	
						---- если мед полиса с такой же датой нет , то создадим новую запись в MED_POL и обновим линк в PERSON
						INSERT INTO MED_POL WITH (ROWLOCK) (LINK_PERS,SER, [NUMBER],[DATE],ORG_WHOM,ORG_ADDR,ORG_PR_FIO)
						VALUES (@varKSparLINK, @varKSparMED_POL_SER, @varKSparMED_POL_NUM,@varKSparMED_POL_DATE,@varKSparMED_POL_WHOM,@varKSparMED_POL_ADDR,@varKSparMED_POL_PR_FIO)
						SELECT @varKSSQLError = @@ERROR, @varKSparMED_POL_LINK = @@IDENTITY
						IF @varKSSQLError <> 0
						BEGIN
							ROLLBACK
							RETURN 7
						END	
						
						UPDATE person set MED_POL_LINK = @varKSparMED_POL_LINK 
						where link = @varKSparLINK
						SELECT @varKSSQLError = @@ERROR
						IF @varKSSQLError <> 0
						BEGIN
							ROLLBACK
							RETURN 7
						END		
					END	
			END
		END	
	END ELSE BEGIN
		ROLLBACK
		RETURN 2
	END

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0











GO


GRANT EXECUTE ON dbo.[KU_PERSON_MED_POL_SAVE] TO PUBLIC

GO


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

GO

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

CREATE PROCEDURE dbo.[RB_PRINT_0503128G_2015]
	@LSF	bigint,
	@bDeleteEmptyRows BIT = NULL,  --  NULL - данные выбираются не для печати, 1 - удаление пустых строк (поле DEL = 1), 0 - не удалять.
    @data int=1, -- c_nastr не будет создаваться!
	@notNullCol tinyint = 0,
	@AtrInOnePage tinyint = 0,
	@WEB_excel tinyint = 0 -- 1 - вызывается для печати из WEB для excel-генератора
AS

if isnull(@WEB_excel, 0) <> 1
	select '' as col1

declare @varKSiParam int, @iLF int, @iLT INT -- 0 - без подитогов, 1 бит - подитоги по ЭКР, 2 бит - подитоги по ВР, 3 бит - подитоги по ЦСР, 4 бит - подитоги по подразделу, 5 бит - подитоги по раздеру, 6 бит - подитоги по администратору
DECLARE @varKSiNoItog INT, @dBeginDate DATETIME

select @iLF = Link_Form, @dBeginDate = Begin_Date from report_saved_forms where link_saved_form = @LSF

set @varKSiParam = 0

if object_id('tempdb..#Param_Print') is NOT NULL
BEGIN
	select @varKSiParam = convert(int, Value) from #Param_Print where Param = 'Poditog'
	select @varKSiNoItog = convert(int, Value) from #Param_Print where Param = 'NoPoditog'
END   

	create table #all (OrderTable tinyint, CODE varchar(50), COL1 varchar(8000), COL2 varchar(10), COL3 varchar(50), COL4 float, COL5 float, COL6 float, COL7 float, COL8 float, COL9 float, COL10 float, COL11 float, COL12 float, orders int IDENTITY(1,1))
	declare @table varchar(100), @RunStr varchar(8000)


------------------------------------------------------------------------------------------------
--- ТАБЛИЦА РАСХОДЫ С ПОДИТОГАМИ
	create table #rash (checked tinyint, Upd tinyint, del tinyint, link_saved_form int, link_row int, orders int, Calc_orders int, Print_NULL tinyint, Code varchar(50), Col1 varchar(2000), Col2 varchar(1000), Col3 varchar(1000), Col4 varchar(1000), Col5 varchar(1000), Col6 varchar(1000), Col7 float, Col8 float, Col9 float, Col10 float, Col11 float, Col12 float, Col13 float, Col14 float, Col15 float, Col16 varchar(50))

	insert #rash (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	exec dbo.rn_get_all_adm_table 	@LSF, 1, @bDeleteEmptyRows, @AtrInOnePage, 1


	select * into #rash_itog from #rash where 0 > 1

	insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
	SELECT 1, '00096000000000000000', '1. Бюджетные обязательства по расходам, всего:', '200', '00096000000000000000', sum(COL7), sum(COL8), sum(COL9), sum(COL10), sum(COL11), sum(COL12), sum(COL13), sum(COL14), sum(COL15)
	from #rash 
	where right(rtrim(CODE),17) = '96000000000000000'



---------------------------------------------
/*col1 - наименование показателя
col2 - код строки
col3 - РЗПР
col4 - ЦСР
col5 - ВР
col6 - ЭКР
col15 - Код = АДМ(3) + РЗПР(4) + ЦСР(7) + ВР(3) + ЭКР(3)
*/
select @iLT = Link_Table from report_tables where Link_Form = @iLF and orders = 2
-- добавляем подитоги
if @varKSiParam & 2 = 2 -- подитоги по целевой статье
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,14) + '000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(Col16,14) + '000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,14) + '000000', left(Col16,14) + '000000'
end

if @varKSiParam & 4 = 4 -- подитоги по подразделу
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,7) + '0000000000000', '', max(Col2),max(Col3), '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(col16,7) + '0000000000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,7) + '0000000000000', left(col16,7) + '0000000000000'
end

if @varKSiParam & 8 = 8 -- подитоги по разделу
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,5) + '000000000000000', '', max(Col2),left(col3,2) + '00', '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(col16,5) + '000000000000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,5) + '000000000000000', left(Col16,5) + '000000000000000',left(col3,2) + '00'
end

if @varKSiParam & 16 = 16 -- подитоги по администратору
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,3) + '00000000000000000', '', max(Col2),'000', '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(col16,3) + '00000000000000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,3) + '00000000000000000', left(Col16,3) + '00000000000000000'
end

if @varKSiParam & 32 = 32 -- обнуляем подпрограмму в целевой статье
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,12) + '00000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(Col16,12) + '00000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,12) + '00000000', left(Col16,12) + '00000000'
end

if @varKSiParam & 64 = 64 -- обнуляем программу в целевой статье
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,10) + '0000000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(Col16,10) + '0000000000'
	from #rash
	where col6 = '000' and col5 <> '000'
	group by left(Code,10) + '0000000000', left(Col16,10) + '0000000000'
end

select @iLT = Link_Table from report_tables where Link_Form = @iLF and orders = 1

exec ro_get_name_spr @iLT, 'COL5=SUBSTRING(CODE,15,3)=000#COL4=SUBSTRING(CODE,8,7)=0000000#COL3=SUBSTRING(CODE,4,4)=0000#RN_VIEW_KBK_ADM_M=LEFT(CODE,3)=000', '#rash_itog', @varKScNameCode = 'CODE', @varKScNameName = 'COL1', @varKSiLSF = @LSF



-----------------------------------------------------------------
-----------------------------------------------------------------
------------------------------------------------------------------------------------------------
--- ТАБЛИЦА 3 РАСХОДЫ следующего года С ПОДИТОГАМИ
/*	create table #rash3 (checked tinyint, Upd tinyint, del tinyint, link_saved_form int, link_row int, orders int, Calc_orders int, Print_NULL tinyint, Code varchar(50), Col1 varchar(2000), Col2 varchar(1000), Col3 varchar(1000), Col4 varchar(1000), Col5 varchar(1000), Col6 varchar(1000), Col7 float, Col8 float, Col9 float, Col10 float, Col11 float, Col12 float, Col13 float, Col14 float, Col15 float, Col16 varchar(50))

	insert #rash3 (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	exec dbo.rn_get_all_adm_table 	@LSF, 3, @bDeleteEmptyRows, @AtrInOnePage, 1


	INSERT into #rash_itog 
	select checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16 
	from #rash3 where 0 > 1

	insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
	SELECT 3, '00097000000000000000', '3. Обязательства финансовых годов, следующих за текущим (отчетным) финансовым годом, всего:', '900', '00097000000000000000', sum(COL7), sum(COL8), sum(COL9), sum(COL10), sum(COL11), sum(COL12), sum(COL13), sum(COL14), sum(COL15)
	from #rash3 
	where right(rtrim(CODE),17) = '97000000000000000'

---------------------------------------------
/*col1 - наименование показателя
col2 - код строки
col3 - РЗПР
col4 - ЦСР
col5 - ВР
col6 - ЭКР
col15 - Код = АДМ(3) + РЗПР(4) + ЦСР(7) + ВР(3) + ЭКР(3)
*/
select @iLT = Link_Table from report_tables where Link_Form = @iLF and orders = 3
-- добавляем подитоги
if @varKSiParam & 2 = 2 -- подитоги по целевой статье
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,14) + '000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(Col16,14) + '000000'
	from #rash3
	where col6 = '000' and col5 <> '000'
	group by left(Code,14) + '000000', left(Col16,14) + '000000'
end

if @varKSiParam & 4 = 4 -- подитоги по подразделу
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,7) + '0000000000000', '', max(Col2),max(Col3), '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(col16,7) + '0000000000000'
	from #rash3
	where col6 = '000' and col5 <> '000'
	group by left(Code,7) + '0000000000000', left(col16,7) + '0000000000000'
end

if @varKSiParam & 8 = 8 -- подитоги по разделу
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,5) + '000000000000000', '', max(Col2),left(col3,2) + '00', '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(col16,5) + '000000000000000'
	from #rash3
	where col6 = '000' and col5 <> '000'
	group by left(Code,5) + '000000000000000', left(Col16,5) + '000000000000000',left(col3,2) + '00'
end

if @varKSiParam & 16 = 16 -- подитоги по администратору
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,3) + '00000000000000000', '', max(Col2),'000', '0000000', '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(col16,3) + '00000000000000000'
	from #rash3
	where col6 = '000' and col5 <> '000'
	group by left(Code,3) + '00000000000000000', left(Col16,3) + '00000000000000000'
end

if @varKSiParam & 32 = 32 -- обнуляем подпрограмму в целевой статье
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,12) + '00000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(Col16,12) + '00000000'
	from #rash3
	where col6 = '000' and col5 <> '000'
	group by left(Code,12) + '00000000', left(Col16,12) + '00000000'
end

if @varKSiParam & 64 = 64 -- обнуляем программу в целевой статье
begin
	insert #rash_itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16)
	select 0, 0, 0, max(link_saved_form), 0, 0, 0, 0, left(Code,10) + '0000000000', '', max(Col2),max(Col3), max(Col4), '000', max(Col6), sum(Col7), sum(Col8), sum(Col9), sum(Col10), sum(Col11), sum(Col12), sum(Col13), sum(Col14), sum(Col15), left(Col16,10) + '0000000000'
	from #rash3
	where col6 = '000' and col5 <> '000'
	group by left(Code,10) + '0000000000', left(Col16,10) + '0000000000'
end

select @iLT = Link_Table from report_tables where Link_Form = @iLF and orders = 3

exec ro_get_name_spr @iLT, 'COL5=SUBSTRING(CODE,15,3)=000#COL4=SUBSTRING(CODE,8,7)=0000000#COL3=SUBSTRING(CODE,4,4)=0000#RN_VIEW_KBK_ADM_M=LEFT(CODE,3)=000', '#rash_itog', @varKScNameCode = 'CODE', @varKScNameName = 'COL1', @varKSiLSF = @LSF
*/
-----------------------------------------------------------------
-----------------------------------------------------------------
----------------------------------------------
IF isnull(@varKSiNoItog, 0) = 1
BEGIN
   insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
   select 1, R.CODE, COL1, COL2, CODE, COL7, COL8, COL9, COL10, COL11, COL12, COL13, COL14, COL15
   from #rash R
   where right(rtrim(R.CODE),17) <> '96000000000000000' AND right(rtrim(R.CODE),3) NOT IN ('200','000','210','220','230','240','250','260','300','500','600') 
   order by R.Code

/*   insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
   select 3, R3.CODE, COL1, COL2, CODE, COL7, COL8, COL9, COL10, COL11, COL12, COL13, COL14, COL15
   from #rash3 R3
   where right(rtrim(R3.CODE),17) <> '97000000000000000' AND right(rtrim(R3.CODE),3) NOT IN ('200','000','210','220','230','240','250','260','300','500','600') 
   order by R3.Code
 */  
   
END
ELSE BEGIN     
-- убираем целевые которых нет в справочнике
   insert #rash
   select distinct checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16
   from #rash_itog A
   WHERE 
   EXISTS (SELECT * FROM R_SPR_CSR_USER_2011 B WHERE ISNULL(begin_date,'20000101') <= @dBeginDate AND isnull(end_date,'20200101') >= @dBeginDate
        AND SUBSTRING(A.CODE,8,7) = B.code)
-- убираем целевые которых нет в справочнике
  /* insert #rash3
   select distinct checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13, Col14, Col15, Col16
   from #rash_itog A
   WHERE 
   EXISTS (SELECT * FROM R_SPR_CSR_USER_2011 B WHERE ISNULL(begin_date,'20000101') <= @dBeginDate AND isnull(end_date,'20200101') >= @dBeginDate
        AND SUBSTRING(A.CODE,8,7) = B.code)
*/

   insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
   select 1, R.CODE, COL1, COL2, CODE, COL7, COL8, COL9, COL10, COL11, COL12, COL13, COL14, COL15
   from #rash R
   where right(rtrim(R.CODE),17) <> '96000000000000000'
   order by R.Code

 /*  insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
   select 3, R3.CODE, COL1, '910', CODE, COL7, COL8, COL9, COL10, COL11, COL12, COL13, COL14, COL15
   from #rash3 R3
   where right(rtrim(R3.CODE),17) <> '97000000000000000'
   order by R3.Code	
*/END 

drop table #rash_itog
drop table #rash
--drop table #rash3



-------------------------------------------------------------------------------------------------
-- ИСТОЧНИКИ
	create table #ist (checked tinyint, Upd tinyint, del tinyint, link_saved_form int, link_row int, orders int, Calc_orders int, Print_NULL tinyint, Code varchar(1000), Col1 varchar(1000), Col2 varchar(1000), Col3 varchar(1000), Col4 float, Col5 float, Col6 float, Col7 float, Col8 float, Col9 float, Col10 float, Col11 float, Col12 float, Col13 varchar(1000))

	insert #ist (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13)
	exec dbo.rn_get_all_adm_table 	@LSF, 2, @bDeleteEmptyRows, @AtrInOnePage, 1


	insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
	SELECT 2, '00090000000000000000', '2. Бюджетные обязательства по выплатам источников финансирования дефицита бюджета, всего:', '510', '00090000000000000000', sum(COL4), sum(COL5), sum(COL6), sum(COL7), sum(COL8), sum(COL9), sum(COL10), sum(COL11), sum(COL12)
	from #ist 
	where right(rtrim(COL3),17) = '90000000000000000'

-------------------------------------------------------------------------------------------------
-- ОБЯЗАТЕЛЬСТВА финансовых годов


	create table #all1 (OrderTable tinyint, CODE varchar(50), COL1 varchar(8000), COL2 varchar(10), COL3 varchar(1000), COL4 float, COL5 float, COL6 float, COL7 float, COL8 float, COL9 float, COL10 float, COL11 float, COL12 float, orders int IDENTITY(1,1))
	--declare @table varchar(100), @RunStr varchar(8000)

	create table #ist3(checked tinyint, Upd tinyint, del tinyint, link_saved_form int, link_row int, orders int, Calc_orders int, Print_NULL tinyint, Code varchar(1000), Col1 varchar(1000), Col2 varchar(1000), Col3 varchar(1000), Col4 float, Col5 float, Col6 float, Col7 float, Col8 float, Col9 float, Col10 float, Col11 float, Col12 float, Col13 varchar(1000))

	insert #ist3(checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12, Col13 )
	exec dbo.rn_get_all_adm_table 	@LSF, 3, @bDeleteEmptyRows, @AtrInOnePage, 1


	insert #all1 (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
	SELECT 3, '00091000000000000000', '3.Обязательства финансовых годов, следующих за текущим (отчетным) финансовым годом, всего:', '900',  '00091000000000000000', sum(COL4), sum(COL5), sum(COL6), sum(COL7), sum(COL8), sum(COL9), sum(COL10), sum(COL11), sum(COL12)
	from #ist3 
	where right(rtrim(COL2),3) = '900'


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


IF isnull(@varKSiNoItog, 0) = 1
BEGIN
	insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
	select 2, CODE, COL1, COL2, RIGHT(CODE,3) + COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12
	from #ist
	where RIGHT(RTRIM(CODE),17) not in (select RIGHT(RTRIM(CD), 17) from dbo.RO_SELECT_FORM_TOTALS_IST_20(0,@iLF ,1) where link_table=@iLT )
	     or code like '%510%01000000000000000%' or code like '%520%01000000000000000%' or code like '%620%02000000000000000%' or code like '%520%02000000000000000%' or code like '%700%01000000000000000%' or code like '%710%01050000000000500%' or code like '%720%01050000000000600%' or code like '%82%000000000000000%'
	
	insert #all1 (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
	select 3, CODE, COL1, RIGHT(COL2,3), RIGHT(CODE,3) + COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12
	from #ist3
	where RIGHT(RTRIM(CODE),3) not in (select RIGHT(RTRIM(CD), 3) from dbo.RO_SELECT_FORM_TOTALS_IST_20(0,@iLF ,1) where link_table=@iLT )
	     or code like '%910%' or code like '%920%' 

END
ELSE BEGIN
	insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
	select 2, CODE, COL1, COL2, LEFT(CODE,3) + COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12
	from #ist
	where right(rtrim(COL3),17) <> '90000000000000000'
	
	insert #all1 (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
	select 3, CODE, COL1, RIGHT(COL2,3), RIGHT(CODE,3) + COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12
	from #ist3
	where right(rtrim(CODE),3) <> '900'

END           

	insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
	select 3, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12
	from #all1



	create table #itog (checked tinyint, Upd tinyint, del tinyint, link_saved_form int, link_row int, orders int, Calc_orders int, Print_NULL tinyint, Code varchar(50), Col1 varchar(1000), Col2 varchar(1000), Col3 varchar(1000), Col4 float, Col5 float, Col6 float, Col7 float, Col8 float, Col9 float, Col10 float, Col11 float, Col12 float)

	insert #itog (checked, Upd, del, link_saved_form, link_row, orders, Calc_orders, Print_NULL, Code, Col1, Col2, Col3, Col4, Col5, Col6, Col7, Col8, Col9, Col10, Col11, Col12)
	exec dbo.rn_get_all_adm_table 	@LSF, 4, @bDeleteEmptyRows, @AtrInOnePage, 1

	insert #all (OrderTable, CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12)
	select 4,max(CODE), max(COL1), max(COL2), '              Х', sum(COL4), sum(COL5), sum(COL6), sum(COL7), sum(COL8), sum(COL9), sum(COL10), sum(COL11), sum(COL12)
	from #itog

	drop table #ist
	drop table #itog

	select * from #all order by OrderTable, left(code,3), orders
	drop table #all

	if isnull(@WEB_excel, 0) <> 1
		select cells as style,style as value from report_print_style where link_form=@iLF order by cells




GO


GRANT EXECUTE ON dbo.[RB_PRINT_0503128G_2015] TO PUBLIC

GO

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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE [dbo].SD_N_TABEL_FILL_EMPL_PAY
	@varKSnRefPay		int		= 0, 		
	@varKSnLinkEmpl		int 	= 0,	
	@varKSdDate		datetime	= null 	
AS



Create  TABLE #varKSTemp
([LINK] 				[int],
 [ORDERS]				[int],
 [TAB_NUMER]			[varchar] (6),
 [NAME_EMPL]			[varchar] (30),
 [REF_EMPL]				[int],
 [DATE1]				[datetime],		
 [DATE2]				[datetime],		
 [DAY]					[numeric] (4,0),
 [HOUR]					[numeric] (10,2),
 [DAY_NORM]				[numeric] (10,4),
 [HOUR_NORM]			[numeric] (10,2),
 [GRAPH_NAME]			[varchar] (30),
 [GRAPH_LINK]			[int],
 [SUMMA_BASE]			[numeric] (19,2),
 [SUMMA] 				[numeric] (19,2),
 [SUMMA_VIPL]		[numeric] (19,2),
 [SUMMA_ALL]		[numeric] (19,2),
 [PERCENT]			[numeric] (19,2),
 [RATE]				[numeric] (5,2),
 [REF_PAY]			[int],
 [CODE_PAY]			[varchar] (10),
 [NAME_PAY]			[varchar] (60),
 [WAY_CALC]			[tinyint],
 [DATE1_PAY]		[datetime],  
 [DATE2_PAY]		[datetime],
 LINK_KBK				INT,
 CODE_KBK				VARCHAR(30)	
)

INSERT INTO #varKSTemp
EXEC SD_N_TABEL_FILL_EMPL @varKSnLinkEmpl, @varKSdDate

SELECT tmp.* FROM #varKSTemp tmp INNER JOIN dbo.group_pays(@varKSnRefPay) T 
			ON tmp.REF_PAY=T.PAY_LINK







GO


GRANT EXECUTE ON dbo.[SD_N_TABEL_FILL_EMPL_PAY] TO PUBLIC

GO



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

GO

CREATE PROCEDURE [dbo].SD_N_RESERV_TABLE_SAVE
	@varKSparLINK			int,
	@varKSparORDERS			numeric(5,0),
	@varKSparLINK_EMPL		int,
	@varKSparSUMMA_BASE		numeric(20,2),
	@varKSparAMOUNT_DED		numeric(20,2),
	@varKSparSUMMA_DED		numeric(20,2),
	@varKSparAMOUNT_TR		numeric(20,2),
	@varKSparSUMMA_TR		numeric(20,2),
	@varKSparOST_VAC_D		numeric(10,2),
	@varKSparSUMMA_RESERV	numeric(20,2)
AS
DECLARE @varKSERROR	tinyint, @varKStrancount	int,  @varKSSQLError int

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


IF @varKSparLINK IS NULL OR @varKSparLINK =0 OR  @varKSparORDERS IS NULL  OR  @varKSparLINK_EMPL IS NULL
BEGIN
	ROLLBACK
	RETURN 5
END

INSERT INTO SDOC_RESERV_TABLE WITH (ROWLOCK) (LINK_UP,ORDERS, LINK_EMPL,SUMMA_BASE,AMOUNT_DED, SUMMA_DED,AMOUNT_TR,SUMMA_TR, OST_VAC_D,SUMMA_RESERV) 
				VALUES (@varKSparLINK, @varKSparORDERS,@varKSparLINK_EMPL,@varKSparSUMMA_BASE,@varKSparAMOUNT_DED,@varKSparSUMMA_DED,@varKSparAMOUNT_TR,@varKSparSUMMA_TR,@varKSparOST_VAC_D,@varKSparSUMMA_RESERV)

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

WHILE @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0






GO


GRANT EXECUTE ON dbo.[SD_N_RESERV_TABLE_SAVE] TO PUBLIC

GO



GO

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

GO

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

CREATE PROCEDURE dbo.[RO_PRINT_125_2015]
	@LSF	bigint,
	@bDeleteEmptyRows BIT = NULL,  --  NULL - данные выбираются не для печати, 1 - удаление пустых строк (поле DEL = 1), 0 - не удалять.
    @data int=1, -- c_nastr не будет создаваться!
	@notNullCol tinyint = 0,
	@AtrInOnePage tinyint = 0,
	@WEB_excel tinyint = 0 -- 1 - вызывается для печати из WEB для excel-генератора
AS

	if isnull(@WEB_excel, 0) <> 1
		select '' col1 
	declare  @atr varchar(254), @atr_value varchar(254)
	if YEAR((select begin_date from dbo.report_saved_forms where link_saved_form = @LSF)) > 2010
		set @atr = 'REPORTS_ATR_ACC_2011'
	else
		set @atr = 'REPORTS_ATR_ACC'
	set @atr_value = dbo.RN_GET_ATR_Value(@LSF, @atr)
	create table #all (ATR varchar(100), COL1 varchar(8000), COL2 varchar(8000), COL3 varchar(8000), COL4 varchar(8000), COL5 varchar(8000), COL6 varchar(8000), COL7 float, COL8 float, COL9 varchar (8000), COL10 varchar (8000), COL11 varchar (8000), COL12 varchar (8000), COL13 varchar (8000), COL14 varchar (8000), COL15 varchar (8000), COL16 varchar (8000), COL17 varchar (8000), COL18 varchar (8000), COL19 varchar (8000), CODE varchar(50), DEL bit, ITOG int, orders int IDENTITY(1,1))
	create table #doh (checked tinyint, Upd tinyint, del tinyint, link_saved_form int, link_row int, orders int, Calc_orders int, Print_NULL tinyint, 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 float, col9 float, col10 varchar(8000), col11 varchar(8000), col12 varchar(8000), col13 varchar(8000), col14 varchar(8000), col15 varchar(8000), col16 varchar(8000), col17 varchar(8000), atr varchar(250) )
	create table #rash (checked tinyint, Upd tinyint, del tinyint, link_saved_form int, link_row int, orders int, Calc_orders int, Print_NULL tinyint, 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 float, col11 float, col12 varchar(8000), col13 varchar(8000), col14 varchar(8000), col15 varchar(8000), col16 varchar(8000), col17 varchar(8000), col18 varchar(8000), col19 varchar(8000), atr varchar(250) )
	create table #ist (checked tinyint, Upd tinyint, del tinyint, link_saved_form int, link_row int, orders int, Calc_orders int, Print_NULL tinyint, 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 float, Col9 float, col10 varchar(8000), col11 varchar(8000), col12 varchar(8000), col13 varchar(8000), col14 varchar(8000), col15 varchar(8000), col16 varchar(8000), col17 varchar(8000), atr varchar(250) )
	create table #itog (checked tinyint, Upd tinyint, del tinyint, link_saved_form int, link_row int, orders int, Calc_orders int, Print_NULL tinyint, Code varchar(50), Col1 varchar(8000), Col2 varchar(8000), Col3 varchar(8000), Col4 varchar(8000), Col5 varchar(8000), Col6 varchar(8000), Col7 float, Col8 float, col9 varchar(8000), col10 varchar(8000), col11 varchar(8000), col12 varchar(8000), col13 varchar(8000), col14 varchar(8000), atr varchar(250))

	insert #doh exec dbo.ro_get_all_atr_table @LSF, 1, @bDeleteEmptyRows, @AtrInOnePage, @atr
	insert #rash exec dbo.ro_get_all_atr_table @LSF, 2, @bDeleteEmptyRows, @AtrInOnePage, @atr
	insert #ist exec dbo.ro_get_all_atr_table @LSF, 3, @bDeleteEmptyRows, @AtrInOnePage, @atr
	insert #itog exec dbo.ro_get_all_atr_table @LSF, 4, @bDeleteEmptyRows, @AtrInOnePage, @atr

	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, code, del, itog)
	SELECT atr, RTRIM(COL1), COL2, COL3, COL4, COL5, COL6+COL7+ ( case when atr <>'' then '' else COL10 end),COL8,COL9,COL10,COL12,COL13, col14,CODE, 0 as DEL, 0 from #doh ORDER BY 1,3,4,5,6

	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, code, del, itog)
--	SELECT atr, RTRIM(COL1), COL2, COL3, COL4, COL5, COL6+COL7+COL8+COL9+col12,COL10,COL11, col12, col14, col15, col16,CODE, 0 as DEL, 0 from #rash ORDER BY 1,3,4,5,6
	SELECT atr, RTRIM(COL1), COL2, COL3, COL4, COL5, COL6+COL7+COL8+COL9,COL10,COL11, col12, col14, col15, col16,CODE, 0 as DEL, 0 from #rash ORDER BY 1,3,4,5,6	

	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, code, del, itog)
	SELECT atr, RTRIM(COL1), COL2, COL3, COL4, col5, COL6+COL7+(case when atr <>'' then '' else COL10 end),col8, col9, col10, col12, col13, col14,CODE, 0 as DEL, 0 from #ist ORDER BY 1,3,4,5,6


	if not exists(select top 1 * from #all)
		insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, code, del, itog)
		select atr, '', '', '', '', '','', NULL, NULL,'','','','', '', 0, 0
		from #itog 
		group by atr

	if not exists(select top 1 * from #all)
		insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, code, del, itog)
		select @atr_value, '', '', '', '', '', '', null, null,'','','','', '', 0, 0

	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, code, del, itog)
	SELECT atr, 'Итого:', max(COL2), 'X' AS COL3, 'X' AS COL4, 'X' AS COL5, 'X' AS COL6, max(COL7) , max(COL8),max(COL9),max(COL10),max(COL11), 'X' AS COL12, max(CODE) AS CODE, 0 as DEL, 1  
	from #itog WHERE RTRIM(LTRIM(CODE)) = 'Итого'
	group by atr

	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, code, del, itog)
	SELECT atr, 'Итого:', '' AS COL2, 'X' AS COL3, 'X' AS COL4, 'X' AS COL5, 'X' AS COL6, 0 as COL7 , 0 as COL8, '' AS COL9, '' AS COL10, '' AS COL11, 'X' AS COL12, '' AS CODE, 0 as DEL, 1  
	from #all A
	where not exists(select top 1 * from #itog A1 where A.atr = A1.atr and RTRIM(LTRIM(A1.CODE)) = 'Итого')
	group by atr

	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, col9, col10, col11, col12, CODE, DEL, ITOG)
	select atr, 'в том числе по', '', '', '', '', '', NULL, NULL, '', '', '', '', '', 0, 1
	from #all
	group by atr

	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, col9, col10, col11, col12, CODE, DEL, ITOG)
	SELECT atr, 'номеру (коду) счета:', COL2, COL3, COL4, COL5,COL6,COL7, col8, col9, col10, col11,'X' AS COL12, CODE, 0 as DEL, 1  from #itog 
	WHERE RIGHT(RTRIM(CODE),2) = 'ИП' ORDER BY 1, 2, 3, 4, 5,6

	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, col9, col10, col11, col12, CODE, DEL, ITOG)
	select atr, 'номеру (коду) счета:', '', '', '', '', '', NULL, NULL, '', '', '', 'X', '', 0, 1
	from #all A
	where not exists(select top 1 * from #itog A1 where A.atr = A1.atr and RIGHT(RTRIM(A1.CODE),2) = 'ИП')
	group by atr

	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, col9, col10, col11, col12, CODE, DEL, ITOG)
	select atr, 'номеру (коду) счета:', '', '', '', '', '', NULL, NULL, '', '', '', 'X', '', 0, 1
	from #all A
	where not exists(select top 1 * from #itog A1 where A.atr = A1.atr and RIGHT(RTRIM(A1.CODE),2) = 'ИП')
	group by atr

	update A
	set col1 = ''
	from #all A
	where col1 = 'номеру (коду) счета:' and exists(select top 1 * from #all A1 where A.atr = A1.atr and A1.col1 = 'номеру (коду) счета:' and A1.orders < A.orders)

	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, col9, col10, col11, col12, CODE, DEL, ITOG)
	select atr, 'из них:', '', '', '', '', '', NULL, NULL, '', '', '', '',  '', 0, 1
	from #all 
	group by atr

	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, col9, col10, col11, col12, CODE, DEL, ITOG)
	SELECT atr, 'денежные расчеты', '', '', '', '', '',COL7,COL8, '', '', '', '', CODE, 0 as DEL, 1   from #itog 
	WHERE RTRIM(LTRIM(CODE)) = 'итог_денежные_рассчёты'

	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, code, del, itog)
	SELECT atr, 'денежные расчеты', '', '', '', '', '',0 as COL7,0 as COL8, '', '', '', '', '' as CODE, 0 as DEL, 1   
	from #all A
	where not exists(select top 1 * from #itog A1 where A.atr = A1.atr and RTRIM(LTRIM(A1.CODE)) = 'итог_денежные_рассчёты')
	group by atr

	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, col9, col10, col11, col12, CODE, DEL, ITOG)
	SELECT atr, '', COL2,COL3,COL4,COL5,COL6, COL7,COL8, col9, col10, col11, col12, CODE, 0 as DEL, 1 from #itog WHERE RIGHT(RTRIM(LTRIM(CODE)),2) = 'ИД'  ORDER BY 1, 2, 3, 4, 5,6
   
	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, code, del, itog)
	SELECT atr, '', '', '', '', '', '',0 as COL7,0 as COL8, '', '', '', '', '' as CODE, 0 as DEL, 1   
	from #all A
	where not exists(select top 1 * from #itog A1 where A.atr = A1.atr and RIGHT(RTRIM(LTRIM(A1.CODE)),2) = 'ИД')
	group by atr


	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, col9, col10, col11, col12, CODE, DEL, ITOG)
	SELECT atr, 'неденежные расчеты', '', '', '', '', '',COL7,COL8, '', '', '', '',CODE, 0 as DEL,1  
	from #itog WHERE LTRIM(RTRIM(CODE)) = 'итог_неденежные_рассчёты'

	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, code, del, itog)
	SELECT atr,'неденежные расчеты', '', '', '', '', '',0 as COL7,0 as COL8, '', '', '', '', '' as CODE, 0 as DEL, 1   
	from #all A
	where not exists(select top 1 * from #itog A1 where A.atr = A1.atr and LTRIM(RTRIM(A1.CODE)) = 'итог_неденежные_рассчёты')
	group by atr
	
	insert #all (atr, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, col9, col10, col11, col12, CODE, DEL, ITOG)
	SELECT atr, '', COL2,COL3,COL4,COL5,COL6,COL7,COL8, col9, col10, col11, col12,CODE, 0 as DEL, 1  from #itog WHERE RIGHT(LTRIM(RTRIM(CODE)),2) = 'ИН'  ORDER BY 1, 2, 3, 4, 5,6

	insert #all (atr, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, code, del, itog)
	SELECT atr, '', '', '', '', '', '',0 as COL7,0 as COL8, '', '', '', '', '' as CODE, 0 as DEL, 1   
	from #all A
	where not exists(select top 1 * from #itog A1 where A.atr = A1.atr and RIGHT(RTRIM(LTRIM(A1.CODE)),2) =  'ИН')
	group by atr

	select atr as colatr, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, code, del, itog as colitog, orders from #all order by atr, orders

	drop table #all
	drop table #ist
	drop table #doh
	drop table #rash
	drop table #itog

	if isnull(@WEB_excel, 0) <> 1
	select cells as style,style as value from report_print_style where 1=0 order by cells




GO


GRANT EXECUTE ON dbo.[RO_PRINT_125_2015] TO PUBLIC

GO

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

GO


CREATE  PROCEDURE dbo.SD_REP_VEDOM_DGH_PREPARE_DATA 
	@nLink INT = NULL,
	@BUFFER_ID VARCHAR(20) = NULL
AS
 BEGIN

DECLARE @SPISOK_VEDOM TABLE (LINK INT)
INSERT INTO @SPISOK_VEDOM (LINK)
SELECT LINK FROM DBO.BUFFER WITH (NOLOCK) WHERE ID = @BUFFER_ID

IF @nLink IS NOT NULL AND NOT EXISTS (SELECT * FROM @SPISOK_VEDOM WHERE LINK = @nLink)
	INSERT INTO @SPISOK_VEDOM (LINK) VALUES (@nLink)

IF @BUFFER_ID IS NOT NULL
	SET @nLink = NULL
IF COALESCE((SELECT COUNT(*) FROM @SPISOK_VEDOM),0) =1
	SET @nLink = (SELECT LINK FROM @SPISOK_VEDOM)




CREATE TABLE #DOCUMENTS_DED_PR_TABLE_DGH1 (LINK INT, PERS_LINK INT, FIO varchar(150), LINK_SFIN INT, LINK_EKR INT, ORDERS INT, DISBURS NUMERIC(18,2), 
		CODE_EKR VARCHAR(3), CODE_KBK VARCHAR(30), CODE_DT VARCHAR(13), CODE_KT VARCHAR(13) , NOTE VARCHAR(254))

INSERT INTO 
	#DOCUMENTS_DED_PR_TABLE_DGH1 (LINK, PERS_LINK, FIO, ORDERS, DISBURS, NOTE)
SELECT 
	D.LINK, D.PERS_LINK, FIO,  ORDERS = MAX(d.ORDERS), DISBURS = SUM(d.DISBURS) , ltrim(rtrim(NOTE))
FROM 
	dbo.DOCUMENTS_DED_PR_TABLE_DGH D
WHERE 
	(D.LINK = @nLink AND @nLink IS NOT NULL
	OR
	D.LINK IN (SELECT LINK FROM @SPISOK_VEDOM))
GROUP BY 
	LINK, PERS_LINK, FIO , NOTE

--	inner join dbo.DOCUMENTS_DED_PR_DGH_TABLE2 d2 on d2.link = d.link and d2.pers_link = d.pers_link 

----Для каждой ведомости определяются КБК и корреспондирующие счета
----Но только если указан конкретный источник и ЭКР в ведомости

DECLARE @CUR_ACC CURSOR, @LINK_VEDOM INT, @KBK_CODE VARCHAR(30), @EKR_CODE VARCHAR(3), @DT_CODE VARCHAR(40), @KT_CODE VARCHAR(40)

SET @CUR_ACC = CURSOR FORWARD_ONLY
FOR SELECT LINK FROM @SPISOK_VEDOM
OPEN @CUR_ACC
FETCH NEXT FROM @CUR_ACC INTO @LINK_VEDOM
WHILE (@@FETCH_STATUS <> -1)
BEGIN
	IF (@@FETCH_STATUS <> -2)
	BEGIN

		CREATE TABLE #VED_ACC_T (DT_CODE VARCHAR(40),KT_CODE VARCHAR(40), link_sfin INT,EKR_CODE VARCHAR(3) ,KBK_CODE VARCHAR(30))
		INSERT INTO #VED_ACC_T(DT_CODE,KT_CODE,link_sfin,EKR_CODE,KBK_CODE)
		EXEC dbo.[SA_VEDOM_ACCOUNTS_TAB] @LINK_VEDOM = @LINK_VEDOM
		
		UPDATE   a 
		SET CODE_KBK = T.KBK_CODE  , 
			CODE_EKR = ISNULL(t.EKR_CODE, a.CODE_EKR), 
			CODE_DT = t.DT_CODE, 
			CODE_KT = t.KT_CODE
		FROM #DOCUMENTS_DED_PR_TABLE_DGH1 a  left JOIN #VED_ACC_T t  ON 1 = 1
		WHERE a.LINK = @LINK_VEDOM
		DROP TABLE #VED_ACC_T

	END
	FETCH NEXT FROM @CUR_ACC INTO @LINK_VEDOM
END

CLOSE @CUR_ACC
DEALLOCATE @CUR_ACC
------------------------------------------------------------------

DECLARE	@res TABLE 
		(
		 LINK_DOC INT, 
		 DOC_DATE DATETIME, 
		 DOC_DATE1 varchar(10), 
		 EXCH_DATE datetime,
		 DOC_NUM VARCHAR(60), 
		 KASSIR VARCHAR(120), 
		 KASS_POST VARCHAR(254),
		 KASS_PHONE VARCHAR(40),
		 DIV_NAME VARCHAR(254), 
		 DIV_CODE VARCHAR(10),
		 TI_NAME VARCHAR(254), 
		 TI_CODE VARCHAR(10),
		 VR_NAME VARCHAR(254), 
		 VR_CODE VARCHAR(10),
	 	 NAME_PAYR VARCHAR(254),
		 NAME_PAY VARCHAR(120), 
		 CODE_PAY VARCHAR(10),
		 DATE_BEGIN DATETIME,
		 DATE_END DATETIME, 
		 [MONTH] VARCHAR(20), 
		 MON int,
		 [YEAR] VARCHAR(4), 
		 NPP INT IDENTITY, 
		 LINK_EMPL INT, 
	 	 TN VARCHAR(15), 
		 FIO VARCHAR(254),
		 S_FIO VARCHAR(100),
		 FM VARCHAR(50), 
		 IM VARCHAR(50), 
		 OT VARCHAR(50), 
		 INN VARCHAR(12),
		 SUMMA NUMERIC(15,2), 
		 SUMMA1 VARCHAR(18), 
		 ACCT VARCHAR(254), 
		 ACCT_V VARCHAR(254),
		 BANK_LINK INT, BANK_NAME VARCHAR(254), BIK VARCHAR(9), DEP_ACCT VARCHAR(30), DEP_ACC_M VARCHAR(20),
		 CARD_LINK INT, CARD_NAME VARCHAR(254), CARD_CODE VARCHAR(3), CARD_POSTF VARCHAR(2),
		 NOSB VARCHAR(4), NFSB VARCHAR(5), NDOG_SB VARCHAR(20), DATE_DOGSB datetime,
		 POST VARCHAR(254),
		 SERNUM VARCHAR(20),
		 SUM_ALL NUMERIC(20,2), 
		 COUNT_OP INT,
		 DEP_NAME VARCHAR(254), FULLNAME VARCHAR(2000),
 		 PASSPORT VARCHAR(254),
		 ADDRESS VARCHAR(254),
		 PINDEX VARCHAR(10),
		 PHONE VARCHAR(20),
		 FD_CODE varchar(2),
		 FD_DATE varchar(8),
		 FD_ROVD varchar(254),
		 SUBDIV_CODE varchar(20),
		 SUBDIV varchar(254),
		 BIRTHDAY varchar(8),
		 ADDR varchar(254),
		 shild int,
		REGION  VARCHAR(120), ABR_REGION  VARCHAR(12),
		RAION   VARCHAR(120), ABR_RAION  VARCHAR(12),
		GOROD	VARCHAR(50), ABR_GOROD  VARCHAR(12),
		NAS_PUNKT   VARCHAR(120), ABR_NAS_PUNKT  VARCHAR(12),
		ULICA	VARCHAR(120), ABR_ULICA  VARCHAR(12),
		DOM	VARCHAR(5), KORPUS VARCHAR(5), KVARTIRA VARCHAR(5),
		DEP_INN VARCHAR(12), DEP_KPP VARCHAR(9), DEP_OKPO VARCHAR(20), DEP_OGRN VARCHAR(13),
		EXRT INT, EXRT_D INT, LINK_DEP INT, FRMT_LINK INT,
		DD VARCHAR(2), MM VARCHAR(2), YYYY VARCHAR(4),
		CODE_EKR VARCHAR(3), LINK_EKR INT,
		EKR_ANALIT VARCHAR(3),
		CODE_KBK VARCHAR(30),
		CODE_DT VARCHAR(13),
		CODE_KT VARCHAR(13),
		NOTE VARCHAR(254),
/*+*/	RND varchar(16), [DATE] varchar(8), [TIME] varchar(8) , rko_num char(25), rko_date datetime 		 
)	

	DECLARE 
		@ORGNAME VARCHAR(254), @DEP_LINK INT, @ORGFULLNAME VARCHAR(2000),
		@DOC_DATE DATETIME, @DOC_DATE1 varchar(10),@EXCH_DATE datetime, @DOC_NUM VARCHAR(60), 
		@KASSIR VARCHAR(254), @KASS_POST VARCHAR(254),@KASS_PHONE VARCHAR(40),
		@DIV_NAME VARCHAR(254), @DIV_CODE VARCHAR(10),
		@TI_NAME VARCHAR(254), @TI_CODE VARCHAR(10),
		@VR_NAME VARCHAR(254), @VR_CODE VARCHAR(10),
		@NAME_PAY VARCHAR(254), @CODE_PAY VARCHAR(10), @NAME_PAYR VARCHAR(254),
		@DATE_BEGIN DATETIME, @DATE_END DATETIME,
		@Month VARCHAR(20),@MON int, @Year VARCHAR(4),
		@DEP_ACCT VARCHAR(30),@DEP_ACC_M VARCHAR(20),
		@CARD_LINK int,
		@DEP_INN VARCHAR(12), @DEP_KPP VARCHAR(9), @DEP_OKPO VARCHAR(20), @DEP_OGRN VARCHAR(13)
				

	SELECT top 1
			@ORGNAME 	= DEP.NAME , 
			@ORGFULLNAME  = LEFT(DEP.[FULL_NAME],2000),
			@DEP_LINK 	= DEP.LINK,
			@DEP_INN = INN, @DEP_KPP = KPP, @DEP_OKPO = OKPO, @DEP_OGRN = OGRN, @DEP_ACC_M = DEP.MAIN_LINK,
			@EXCH_DATE = getdate()
	FROM DICTIONARY_DEPARTMENT DEP, USER_DEP UI WHERE DEP.LINK = UI.DEP_LINK



	SELECT top 1
		@DOC_DATE = [DATE], @DOC_DATE1 = convert(varchar(10), [DATE], 103), @DOC_NUM = NUMBER,
		@KASSIR = ISNULL(NAME_EMPL, 0),
		@KASS_POST = (SELECT POST_NAME FROM dbo.KU_EMPL_PLACING EP WHERE EP.LINK = ISNULL(D.REF_EMPL, 0) ),
		@KASS_PHONE = LEFT((SELECT top 1 PHONE_WORK from KU_EMPL_PLACING WHERE LINK = ISNULL(D.REF_EMPL, 0)),40),
		@DIV_NAME = ISNULL(NAME_FKR_D, ''), @DIV_CODE = ISNULL(CODE_FKR_D, ''),
		@TI_NAME = ISNULL(NAME_FKR_T, ''), @TI_CODE = ISNULL(CODE_FKR_T, ''),
		@VR_NAME = ISNULL(NAME_FKR_E, ''), @VR_CODE = ISNULL(CODE_FKR_E, ''),
		@NAME_PAY = ISNULL(NAME_PAY, ''), @CODE_PAY = ISNULL(CODE_PAY, ''),  
		@NAME_PAYR = ISNULL(NAME_PAYROLL, ''),
		@DATE_BEGIN = dbo.ConvertDMY2Date(1, month_base, year_base),
		@Year = YEAR_BASE,
		@Month = (SELECT m.mon FROM MONTHS M WHERE M.NUM = D.month_base),
		@MON  = D.month_base,
		@CARD_LINK = CARD_LINK
 	FROM DOCUMENTS_DED_PR_DGH D LEFT OUTER JOIN BI_DICTION_VKR F ON D.LINK_VKR = F.LINK_KBK
	WHERE 
		@nLink IS NOT NULL AND D.LINK = @nLink
		OR
		D.LINK = (SELECT TOP 1 LINK FROM DBO.BUFFER WHERE ID = @BUFFER_ID)

	SELECT 	@DATE_END = dbo.DateEndOfMonth(@DATE_BEGIN)

	SELECT PERS_LINK, LINK_DOC, LINK_EKR, SUM(SUMMA) AS SUMM
	INTO #SUM_EKR
 	FROM DBO.CALCULATE_JURNAL
	WHERE LINK_DOC = @nLink
	GROUP BY PERS_LINK, LINK_DOC, LINK_EKR 

/*+*/
--Ищем xml формат по названию, для xml нужна замена кавычек в названии организации на &quot;
declare @isxml bit
if exists (
		select top 1 * FROM
		dbo.SDOC S
		INNER JOIN dbo.SDOC_VEDOM SD ON S.LINK = SD.LINK_UP
		LEFT JOIN dbo.cards C ON SD.LINK_CARD = C.LINK and SD.LINK_CARD = @CARD_LINK
		LEFT JOIN dbo.S_BANK_FORMATS F ON F.LINK = C.FRMT_LINK
		where s.LINK = @nLink and f.NAME like '%xml%'
		)
set @isxml = 1

--Читаем РКО (нужен номер и дата - для печати)
declare @rko_n char(25), @rko_d datetime
select @rko_n = g.NUMBER, @rko_d = g.DATE from sdoc s
inner join sdoc_vedom_rko bdoc on s.LINK = bdoc.LINK_VEDOM
inner join G_PROV g on g.LINK = bdoc.LINK_RKO
inner join S_OBJECTS so on so.LINK = g.OBJECT and so.code = 'DOCUMENTS_RKO'
where s.LINK = @nLink

--Выводить вместо подписи лицевой счёт
DECLARE @VEDOM_OPTIONS_2_12 INT
SET @VEDOM_OPTIONS_2_12 = dbo.SA_GET_OPTION_BY_CODE ('VEDOM_OPTIONS_2_12')
/*+*/

	INSERT INTO @res
	(
		LINK_DOC, 
		DOC_DATE, DOC_DATE1, EXCH_DATE,  DOC_NUM, 
		KASSIR, KASS_POST,KASS_PHONE,
		DIV_NAME, DIV_CODE,
		TI_NAME, TI_CODE,
		VR_NAME, VR_CODE,
		NAME_PAYR,
		name_pay, CODE_PAY,
		DATE_BEGIN, DATE_END, 
		[month], MON, [YEAR], 
		LINK_EMPL, 
		TN, 
		FIO, FM, IM, OT, S_FIO,INN,
		SUMMA, SUMMA1, 
		ACCT,ACCT_V, BANK_LINK, BANK_NAME, BIK, DEP_ACCT,DEP_ACC_M,
		NOSB, NFSB, NDOG_SB, DATE_DOGSB,
		CARD_LINK, CARD_NAME, CARD_CODE, CARD_POSTF,
		POST,
		SERNUM,
		DEP_NAME, FULLNAME,
		PASSPORT,
		ADDRESS,
		PINDEX,
		PHONE,
		FD_CODE,
		FD_DATE,
		FD_ROVD,
		SUBDIV_CODE,
		SUBDIV,
		BIRTHDAY,
		ADDR,
	REGION, ABR_REGION, RAION, ABR_RAION, 
	GOROD, ABR_GOROD, NAS_PUNKT, ABR_NAS_PUNKT,
	ULICA, ABR_ULICA, DOM, KORPUS, KVARTIRA,
	DEP_INN, DEP_KPP, DEP_OKPO, DEP_OGRN,
	EXRT, EXRT_D, LINK_DEP, FRMT_LINK,
	DD, MM, YYYY, CODE_EKR, LINK_EKR,
	EKR_ANALIT, CODE_KBK, CODE_DT, CODE_KT, NOTE
	/*+*/, RND, [DATE], [TIME] , rko_num, rko_date
	)
	SELECT 
		@nLink, 
		@DOC_DATE, @DOC_DATE1, @EXCH_DATE, @DOC_NUM, 
		@KASSIR, @KASS_POST, LEFT(@KASS_PHONE,40),
		@DIV_NAME, @DIV_CODE,
		@TI_NAME, @TI_CODE,
		@VR_NAME, @VR_CODE,
		@NAME_PAYR,
		@NAME_PAY, @CODE_PAY,
		@DATE_BEGIN, @DATE_END, 
		@Month,@MON, @Year,
		D.PERS_LINK, 
  '',
		dbo.ku_GetPersFIO(D.PERS_LINK),
		P.FM, P.IM, P.OT,
		D.FIO, LEFT(p.INN,12),
		ISNULL(EKR.SUMM,ISNULL(DISBURS, 0)),
		LEFT(dbo.sa_convert_numeric_to_char(ISNULL(EKR.SUMM,ISNULL(DISBURS, 0)), 2, '.', ','),18),
		[acct] = ISNULL(PE.LIC_SCHET, '0'), 
		ACCT_V = CASE WHEN @VEDOM_OPTIONS_2_12 = 0 THEN '0' ELSE LEFT(ISNULL(PE.LIC_SCHET, '0'),254) END, 
		PE.BANK_LINK,
		[BANK_NAME] = (SELECT NAME FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),
		[BANK_CODE] = (SELECT BIK FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),
		[DEP_ACCT]  = (SELECT TOP 1 CODE FROM DICTIONARY_ACCOUNTS 
                       WHERE REF_LINK_B = PE.BANK_LINK 
						AND [TYPE_NAME] = 'РАСЧЕТНЫЙ' 
						AND REF_LINK_D = @DEP_LINK),
		[DEP_ACC_M]	 = (SELECT TOP 1 LEFT(CODE,20) FROM DICTIONARY_ACCOUNTS 
                      WHERE link = @DEP_ACC_M
						AND REF_LINK_D = @DEP_LINK),				
		[OSB] = ISNULL((SELECT OSB FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),''),
		[FILIAL] = 
			CASE WHEN NOT LTRIM(RTRIM(ISNULL(PE.FILIAL,''))) = '' 
				THEN PE.FILIAL
				ELSE ISNULL((SELECT top 1 LEFT(FILIAL,5) FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),'')
			END,
		[DOGOVOR] = 
			CASE WHEN NOT LTRIM(RTRIM(ISNULL(PE.DOGOVOR,''))) = '' 
				THEN PE.DOGOVOR
				ELSE ISNULL((SELECT top 1 LEFT(DOGOVOR,20) FROM dbo.BANKS WHERE LINK = PE.BANK_LINK),'')
			END,
		[DATE_DOG] = ISNULL(PE.DATE_DOG,(SELECT DATE_DOG FROM dbo.BANKS WHERE LINK = PE.BANK_LINK)),
		PE.CARD_LINK, 
		[CARD_NAME] = (SELECT NAME FROM dbo.CARDS WHERE LINK = PE.CARD_LINK),
		[CARD_CODE] = (SELECT CODE FROM dbo.CARDS WHERE LINK = PE.CARD_LINK),
		[POSTFIX] = (SELECT POSTFIX FROM dbo.CARDS WHERE LINK = PE.CARD_LINK),
		'Внештатный сотрудник',
/*+*/	replace(LEFT(ISNULL(P.DOC_NUM, ''),20),' ',''),
/*+*/	case when @isxml = 1 then replace(LEFT(@ORGNAME,254),'"','&quot;') else LEFT(@ORGNAME,254) end, case when @isxml = 1 then replace(@ORGFULLNAME,'"','&quot;') else @ORGFULLNAME end,
		dbo.PrintSalaryGetPassportString(P.DOC_NUM, P.DOC_WHOM, P.DOC_DATE),
		dbo.GetAddressByFace(P.LINK, 0),
		'',
		ISNULL(P.PHONE_OFIC, ''),
		[FD_CODE] = (CASE WHEN COALESCE(FD.CODE,'') = '21' THEN '8' 
				  WHEN COALESCE(FD.CODE,'') = '01' THEN '1'
					ELSE COALESCE(FD.CODE,'') END), 
		[FD_DATE] = CONVERT(VARCHAR,P.DOC_DATE,3),
		[FD_ROVD] = P.DOC_WHOM,
		[SUBDIV_CODE]  = '',
		[SUBDIV]  = 'Внештатники',
		[BIRTHDAY] = CONVERT(VARCHAR,P.BIRTHDATE,3),
		[ADDR]   = dbo.GetAddressByKladr2(P.ADR_OFIC_LINK)+ ' '	+ ltrim(rtrim(house_ofic))+'-'+ltrim(rtrim(flat_ofic)),
		REGION = RTRIM(LTRIM(Left(dbo.SA_GET_WORD_NUM(ADDRESS2,3,','),len(dbo.SA_GET_WORD_NUM(ADDRESS2,3,','))-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,3,',')),1,' '))) ) )), 
		ABR_REGION = RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,3,',')),1,' ')) )), 
		RAION = RTRIM(LTRIM(Left(dbo.SA_GET_WORD_NUM(ADDRESS2,4,','),len(dbo.SA_GET_WORD_NUM(ADDRESS2,4,','))-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,4,',')),1,' '))) ) )), 
		ABR_RAION = RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,4,',')),1,' ')) )), 
		GOROD = RTRIM(LTRIM(Left(dbo.SA_GET_WORD_NUM(ADDRESS2,5,','),len(dbo.SA_GET_WORD_NUM(ADDRESS2,5,','))-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,5,',')),1,' '))) ) )),
		ABR_GOROD = RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,5,',')),1,' ')) )), 
		NAS_PUNKT = RTRIM(LTRIM(Left(dbo.SA_GET_WORD_NUM(ADDRESS2,6,','),len(dbo.SA_GET_WORD_NUM(ADDRESS2,6,','))-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,6,',')),1,' '))) ) )), 
		ABR_NAS_PUNKT = RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,6,',')),1,' ')) )),
		ULICA = RTRIM(LTRIM(Left(dbo.SA_GET_WORD_NUM(ADDRESS2,7,','),len(dbo.SA_GET_WORD_NUM(ADDRESS2,7,','))-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,7,',')),1,' '))) ) )),
		ABR_ULICA = RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(dbo.SA_GET_WORD_NUM(ADDRESS2,7,',')),1,' ')) )), 
		DOM = dbo.SA_GET_WORD_NUM(ADDRESS2,8,','), 
		KORPUS = dbo.SA_GET_WORD_NUM(ADDRESS2,9,','), 
		KVARTIRA = dbo.SA_GET_WORD_NUM(ADDRESS2,10,','),
		@DEP_INN, @DEP_KPP, @DEP_OKPO, @DEP_OGRN,
		EXRT = COALESCE(F.LastFileNumber,1),
		EXRT_D = COALESCE(FE.NUM_EXPORT,1),
		DOC.LINK_DEP,
		C.FRMT_LINK,
		DD = RIGHT('0' + CONVERT(VARCHAR(2),DAY(GETDATE())),2),
		MM = RIGHT('0' + CONVERT(VARCHAR(2),MONTH(GETDATE())),2),
		YYYY = CONVERT(VARCHAR(4),YEAR(GETDATE())),
		CODE_EKR = COALESCE(SGU.CODE,''), EKR.LINK_EKR,  -- Для вывода итого в по ЭКР
		EKR_ANALIT = D.CODE_EKR,
		D.CODE_KBK,
		D.CODE_DT ,
		D.CODE_KT,
		REPLACE(D.NOTE,';',' '),
/*+*/	RND = convert(varchar(16), left(replace(cast(CONVERT(binary(8), RAND(), 0) as uniqueidentifier),'-',''), 16)),
/*+*/	[DATE] = convert(varchar(8),getdATE(),112), --YYYYMMDD
/*+*/	[TIME] = replace(convert(varchar(8),getdATE(),108),':',''), --HHMMSS
/*+*/	rko_num = @rko_n,
/*+*/	rko_date = @rko_d	
    FROM 
		dbo.SDOC DOC 
		INNER JOIN #DOCUMENTS_DED_PR_TABLE_DGH1 D ON DOC.LINK = D.LINK
		INNER JOIN (Select *, dbo.GET_ADDRESS9PARTS(dbo.PERSON.LINK, 0) ADDRESS2  from dbo.PERSON) P ON D.PERS_LINK = P.LINK
		LEFT JOIN dbo.FACE_DOCUMENT FD ON P.DOC_LINK = FD.LINK	
		LEFT OUTER JOIN dbo.SA_PERSON_ECARD_ACTUAL PE ON (PE.PERS_LINK = P.LINK AND PE.CARD_LINK = @CARD_LINK)
		LEFT JOIN dbo.cards C ON PE.CARD_LINK = C.LINK
		LEFT JOIN dbo.S_BANK_FORMATS F ON F.LINK = C.FRMT_LINK
		LEFT JOIN dbo.S_BANK_FORMAT_EXPORT FE ON F.LINK = FE.LINK_UP AND FE.LINK_DEP = DOC.LINK_DEP
		LEFT JOIN #SUM_EKR EKR ON EKR.PERS_LINK = D.PERS_LINK AND DOC.link = EKR.LINK_DOC AND EXISTS (SELECT * FROM DBO.S_BANK_FORMAT_FILES F WHERE GRP_EKR = 1 AND F.LINK_FMT = C.FRMT_LINK)
		LEFT JOIN DBO.KOSGU SGU ON SGU.LINK = EKR.LINK_EKR
	WHERE 
		(D.LINK = @nLink AND @nLink IS NOT NULL
		OR
		D.LINK IN (SELECT LINK FROM DBO.BUFFER WHERE ID = @BUFFER_ID))
		AND
		ISNULL(D.DISBURS, 0) > 0 
	ORDER BY D.FIO


	UPDATE @res SET 
		PINDEX = LTRIM(RTRIM(LEFT(ADDRESS, 7))),
		ADDRESS= LTRIM(RTRIM(RIGHT(ADDRESS, LEN(ADDRESS)-7)))
	WHERE LEFT(ADDRESS, 1) IN (	'0', '1', '2', '3', '4', '5', '6', '7', '8', '9')

	UPDATE @res SET SUM_ALL = (SELECT SUM(SUMMA) FROM @res)
	UPDATE @res SET COUNT_OP = (SELECT COUNT(*)  FROM @res)

	CREATE TABLE #SUM_EKR1 (LINK_EKR INT, SUMMA NUMERIC(20,2), CNT INT )
	INSERT INTO #SUM_EKR1 (LINK_EKR, SUMMA, CNT)
	SELECT LINK_EKR, SUM(SUMM) AS SUMM, COUNT(LINK_EKR) as CNT_EKR FROM #SUM_EKR
	GROUP BY LINK_EKR

	SELECT 
		R.*, NPP_G = NPP,
		GRP_EKR = CASE WHEN EK.SUMMA IS NULL THEN 0 ELSE 1 END,
		ITOG_EKR = COALESCE(EK.SUMMA,0),
		KOL_ST_EKR = COALESCE(EK.CNT,0) 
	FROM 
		@res R  LEFT JOIN #SUM_EKR1 EK ON R.LINK_EKR = EK.LINK_EKR
	ORDER BY 
		NPP

	SELECT NDOG_SB, NOSB, NFSB, COUNT(*) AS COUNT_OP, SUM(SUMMA) AS SUMMA_ALL 
	INTO #RES1
	FROM @res
	GROUP BY NDOG_SB, NOSB, NFSB
	ORDER BY 1, 2, 3
	
	SELECT @ORGNAME AS ORGNAME, * FROM #RES1
	ORDER BY 1, 2, 3, 4

END








GO


GRANT EXECUTE ON dbo.[SD_REP_VEDOM_DGH_PREPARE_DATA] TO PUBLIC

GO



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

GO

/*
    © Кейсистемс (Keysystems), 2007
    Процедура формирования строк и значений формы 0503125
*/

CREATE PROCEDURE dbo.RB_CALC_0503125G_15_NEW
@iLSF int,
@table int
AS

declare @dBeginDate datetime,
		@dEndDate datetime,
		@dEndDate_pl datetime,
		@dCALC_DATE datetime,
		@iThisDep int,
		@nPeriod_Type tinyint,
		@cStrSql varchar(8000)
----------		
DECLARE @LF	int, 
		@LT	int,
		@LC	int,
		@orderCol int,
		@iLinkCalcForm int,
		@iLinkColDt int,
		@bid varchar(100),
		@nabor_filter varchar(1000)
---------------
				
declare @tTempRes table(DEP_NAME varchar(254),
						INN VARCHAR(12),
						PPP varchar(3), 
						OKTMO varchar(11), 
						EL_BUDG varchar(2), 
						KBK varchar(30), 
						ACC_CODE varchar(9), 
						summa_db numeric(20,4), 
						summa_kr numeric(20,4), 
						korr_acc varchar(9), 
						DEP_K_NAME varchar(254),
						INN_K VARCHAR(12),
						PPP_K varchar(3), 
						OKTMO_K varchar(11), 
						D_ND tinyint) 

declare @tTempRes2 table(DEP_NAME varchar(254),
						 INN VARCHAR(12),
						 PPP varchar(3), 
						 OKTMO varchar(11), 
						 EL_BUDG varchar(2), 
						 KBK varchar(30), 
						 ACC_CODE varchar(9), 
						 summa_db numeric(20,4), 
						 summa_kr numeric(20,4), 
						 korr_acc varchar(9),
						 DEP_K_NAME varchar(254),
						 INN_K VARCHAR(12),
						 PPP_K varchar(3), 
						 OKTMO_K varchar(11),  
						 D_ND tinyint,
						 NUM_PP int IDENTITY(1,1)) 
declare @filter_kbk table (kbk varchar(30))

-- определяем период (если в январе формируем, то берём весь предыдущий год не включая 31 декабря)
select @dEndDate = Begin_Date, @nPeriod_Type = period_type from dbo.report_saved_forms where link_saved_form = @iLSF

select @dBeginDate = dbo.DateBeginOfYear(@dEndDate)

-- set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then (@dBeginDate - (datepart(dd,@dBeginDate))) - 1 else @dBeginDate /*- (datepart(dd,@dBeginDate))*/ end
-- set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')


--if @nPeriod_Type <> 1 
--	set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then @dBeginDate - 1 else @dBeginDate end
--else
--	set @dEndDate = @dBeginDate
--
--	set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')

select @nabor_filter = REPLACE(dbo.rn_get_atr_value(@iLSF,'REPORTS_FILTER_KBK'), 'Не отобрано', '')

insert @filter_kbk (kbk)   
Select RTRIM(code) FROM rn_get_filter(@iLSF,'REPORTS_FILTER_KBK')


---------------------------------------****************************
declare @temp_nastr table (link int, [Link_Col] int NOT NULL, 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL, link_dt int, link_kt int, dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint)
declare @temp_nastr_xor table (	link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_dt int, link_kt int, dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, dt_kt tinyint)
declare @temp_nastr_rest table (	link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000),
	[type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint)
declare @temp_nastr_rest_xor table (link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000),
	[type] tinyint, type_kbk tinyint, dt_kt tinyint)


-------- ЧИТАЕМ ДАННЫЕ ОТЧЕТА
select @LF = RSF.Link_Form, 
		@iThisDep 	= Link_Organization, 
		@dEndDate	= Begin_Date + 1,
		@dCALC_DATE	= Begin_Date, 
		@dBeginDate	= dbo.DateBeginOfYear(Begin_Date),
		@nPeriod_Type = period_type
from report_saved_forms RSF  where RSF.link_saved_form = @iLSF

SET @iLinkCalcForm = dbo.RK_GET_NASTR_CALC_REPORT (@iLSF, 1)
print @iLinkCalcForm

if @iLinkCalcForm is null 
BEGIN
	exec RT_CALC_0503125G_15 @iLSF, @table
	RETURN 0
END

set @iLinkColDt = (select top 1 RC.LINK_COL
					from dbo.REPORT_COLOUMNS RC
					inner join dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.Link_Form = @LF and RT.orders = @table and RT.orders = @table
					where @table = 2 and RC.Orders = 10 or @table <> 2 and RC.Orders =8)
---------------------------------------------------------------------
----- ПОЛУЧАЕМ ВЫБОРКУ ИЗ ТАБЛИЦЫ НАСТРОЕК ----
insert @temp_nastr 
select C.link, C.Link_Col, Calc_Order, [Sign], DT.link , KT.link, dt_ekr, kt_ekr, [type], type_kbk, mask_kbk, dt_kt
from dbo.REPORT_CALC C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = @table and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE C.LINK_UP = @iLinkCalcForm
	AND [sign] in (1,2) and CR.[type] = 1 
	AND (rtrim (CR.DT_Mask) = '' OR CR.DT_Mask = '%' OR rtrim (CR.DT_Mask) <> '' AND DT.LINK IS NOT NULL)
	AND (rtrim (CR.KT_Mask) = '' OR CR.KT_Mask = '%' OR rtrim (CR.KT_Mask) <> '' AND KT.LINK IS NOT NULL)

-- проводки, которые мы исключаем --
insert @temp_nastr_xor 
select C.link, C.Link_Col, Calc_Order, [Sign], DT.link , KT.link, dt_ekr, kt_ekr, [type], type_kbk, dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = @table and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
where C.LINK_UP = @iLinkCalcForm
	AND [sign] = 3 and CR.[type] = 1 


--- Выборка счетов для расчета остатков ---
insert @temp_nastr_rest 
select C.link, C.Link_Col, Calc_Order, [Sign],
	case
		when DT.link is NULL then KT.link
		else DT.link
	end,
	case
		when DT.link is NULL then kt_ekr
		else dt_ekr
	end, [type],
	type_kbk,
	mask_kbk,
	dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = @table and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE C.LINK_UP = @iLinkCalcForm 
	AND CR.[type] in (2,3) and [sign] in (1,2) 
	AND (rtrim (CR.DT_Mask) = '' OR rtrim (CR.DT_Mask) <> '' AND DT.LINK IS NOT NULL)
	AND (rtrim (CR.KT_Mask) = '' OR rtrim (CR.KT_Mask) <> '' AND KT.LINK IS NOT NULL)

/*
select S1.CODE, * from @temp_nastr_rest T, S_ACCOUNTS S1 
WHERE S1.LINK = T.LINK_account
*/
--- Счета, которые исключаем для расчета остатков ---
insert @temp_nastr_rest_xor
select C.link, C.Link_Col, Calc_Order, [Sign],
	case
		when DT.link is NULL then KT.link
		else DT.link
	end,
	case
		when DT.link is NULL then kt_ekr
		else dt_ekr
	end,
	[type],
	type_kbk,
	dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = @table and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE  C.LINK_UP = @iLinkCalcForm 
	AND CR.[type] in (2,3) and [sign] = 3 
	AND (DT.LINK IS NOT NULL
		OR KT.LINK IS NOT NULL)
---------------------------------------****************
---- Обороты

	insert into @tTempRes
	select	DEP_NAME = isnull(D.FULL_NAME, 'корреспондент_не_указан'), -- Наименование контрагента
			INN = isnull(D.INN, ''),
			PPP = case when TMP.Mask_KBK like '%АДМ%' then isnull(VED.CODE, '') else '' end, -- ППП
			--OKATO = case when TMP.Mask_KBK like '%ОКАТО%' then isnull(replace(D.OKATO,' ',''), '') else '' end, -- ОКАТО
			OKTMO = case when TMP.Mask_KBK like '%ОКТМО%' then isnull(replace(D.OKTMO,' ',''), '') else '' end, -- ОКАТО
			EL_BUDG = case when TMP.Mask_KBK like '%ЭЛЕМЕНТ%' then isnull(BUDG.CODE_EL, '') else '' end, -- Элемент бюджета
			KBK = isnull(replace(KBK.CODE,'.',''),''), --KBK
			ACC_CODE = case TMP.dt_kt when 0 then isnull(left(replace(SAD.CODE,'.',''),6),'') + isnull(DTS.CODE,'') else isnull(left(replace(SAK.CODE,'.',''),6),'') + isnull(KTS.CODE,'')  end,
			SUMMA_DB = case TMP.LINK_COL when @iLinkColDt then isnull(G2.SUMMA,'') else 0 end, -- сумма дебет
			SUMMA_KR = case TMP.LINK_COL when @iLinkColDt then 0 else isnull(G2.SUMMA,'') end, -- сумма кредит
			korr_acc = case TMP.dt_kt when 0 then isnull(left(replace(SAK.CODE,'.',''),6),'')  + isnull(KTS.CODE,'') else isnull(left(replace(SAD.CODE,'.',''),6),'') + isnull(DTS.CODE,'')  end, -- корреспондирующий счет
			DEP_K_NAME = isnull((select top 1 NAME from DICTIONARY_DEPARTMENT where link = @iThisDep),''),
			INN_K = isnull((select top 1 INN from DICTIONARY_DEPARTMENT where link = @iThisDep),''),
			PPP_K = isnull((select top 1 VED from DICTIONARY_DEPARTMENT where link = @iThisDep),''),
			OKTMO_K = isnull((select top 1 OKTMO from DICTIONARY_DEPARTMENT where link = @iThisDep),''), 
			D_ND = case when TMP.Mask_KBK like '%ДЕН%' then 1 else 0 end-- Признак платежа

	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)


	LEFT JOIN dbo.G_PROV_AP DT ON (DT.LINK_UP = G2.LINK AND DT.DB_KR = 0)
	LEFT JOIN dbo.G_PROV_AP KT ON (KT.LINK_UP = G2.LINK AND KT.DB_KR = 1)

	LEFT JOIN dbo.KOSGU DTS ON (DTS.Link = DT.SGU)
	LEFT JOIN dbo.KOSGU KTS ON (KTS.Link = KT.SGU)
	
	INNER JOIN @TEMP_NASTR TMP ON (TMP.LINK_DT = DT.ACCOUNT OR TMP.LINK_DT IS NULL)
			AND (TMP.LINK_KT = KT.ACCOUNT OR TMP.LINK_KT IS NULL)
		AND (dbo.RO_LIKE_LIST(DTS.Code, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '')
		AND (dbo.RO_LIKE_LIST(KTS.Code, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '')

	LEFT JOIN dbo.S_ACCOUNTS SAD ON SAD.LINK = DT.ACCOUNT

	LEFT JOIN dbo.S_ACCOUNTS SAK ON SAK.LINK = KT.ACCOUNT 

	LEFT JOIN dbo.KL_KBK KBK ON (TMP.dt_kt = 0 AND KBK.LINK = DT.KBK OR TMP.DT_KT = 1 AND KBK.LINK = KT.KBK)
	left join dbo.G_PROV_OS1 OS on OS.LINK_OS1 = G.LINK
	LEFT JOIN dbo.DEPARTMENTS D ON D.LINK = (case	when DT.Dep is not NULL and DT.Dep <> G.Dep then DT.Dep
										when KT.Dep is not NULL and KT.Dep <> G.Dep then KT.Dep
										when OS.Dep_pass is not NULL and OS.Dep_pass <> G.Dep then OS.Dep_pass
										when OS.Dep_receive is not NULL and OS.Dep_receive <> G.Dep then OS.Dep_receive
										else isnull((SELECT top 1 GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA, dbo.S_OBJECTS SO WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT = SO.LINK and (SO.CODE = 'NOTICE_LINK_DEP_RECEIVER' or SO.CODE = 'NOTICE_LINK_DEP_SENDER') AND GPDA.DEPARTMENT <> G.Dep), NULL) end)
	left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
	left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
	LEFT JOIN @filter_kbk F on KBK.Code = F.kbk
	WHERE G.DATE_PROV BETWEEN @dBeginDate AND @dCALC_DATE
		AND G.DEP = @iThisDep
		AND (F.kbk IS NOT NULL OR isnull(@nabor_filter, '') = '')
		AND (TMP.TYPE_KBK = 0 OR (TMP.TYPE_KBK & KBK.[TYPE]) / KBK.[TYPE] = 1)
		AND not exists(select top 1 *
				from @temp_nastr_xor xor
				where xor.link = tmp.link
					and xor.link_dt = dt.account and xor.link_kt = kt.account
					and (CHARINDEX(RTRIM(DTS.Code), xor.dt_ekr) > 0
						or RTRIM(isnull(DTS.Code,'')) like RTRIM(xor.dt_ekr) + '%') 
					and (RTRIM(isnull(KTS.Code,'
			')) like RTRIM(xor.kt_ekr) + '%' or CHARINDEX(RTRIM(KTS.Code),xor.kt_ekr) > 0)) -- исключаем



			
----------------- остатки ------------------------------
while exists(select top 1 * from @temp_nastr_rest)
begin
	select top 1 @LC = Link_Col from @temp_nastr_rest

	set @bid = 'calc_col_' + LTRIM(RTRIM(STR(@LC)))

	insert dbo.buffer(ID, Link)
	select @bid, link_account
	from @temp_nastr_rest
	where link_col = @LC

	-- остаток на конец периода
	insert into @tTempRes
	select	DEP_NAME = isnull(D.FULL_NAME, 'корреспондент_не_указан'), -- Наименование контрагента
			INN = isnull(D.INN, ''),
			PPP = case when R.Mask_KBK like '%АДМ%' then isnull(VED.CODE, '') else '' end, -- ППП
			OKTMO = case when R.Mask_KBK like '%ОКТМО%' then isnull(replace(D.OKTMO,' ',''), '') else '' end, -- ОКАТО
			EL_BUDG = case when R.Mask_KBK like '%ЭЛЕМЕНТ%' then isnull(BUDG.CODE_EL, '') else '' end, -- Элемент бюджета
			KBK = isnull(replace(K.CODE,'.',''),''), --KBK
			ACC_CODE = isnull(left(replace(SA.CODE,'.',''),6),'') + '000',
			SUMMA_DB = case when R.LINK_COL = @iLinkColDt and (SA.S_PASSIVE = 1 and [sign] = 1 OR SA.S_ACTIVE = 1 and [sign] = 2) then isnull(k_summa - d_summa,'') 
							when R.LINK_COL = @iLinkColDt and (SA.S_PASSIVE = 2 and [sign] = 2 OR SA.S_ACTIVE = 1 and [sign] = 1) then isnull(d_summa - k_summa,'') 
							else 0 end, -- сумма дебет
			
			SUMMA_KR = case when R.LINK_COL <> @iLinkColDt and (SA.S_PASSIVE = 1 and [sign] = 1 OR SA.S_ACTIVE = 1 and [sign] = 2) then isnull(d_summa - k_summa,'') 
							when R.LINK_COL <> @iLinkColDt and (SA.S_PASSIVE = 2 and [sign] = 2 OR SA.S_ACTIVE = 1 and [sign] = 1) then isnull(k_summa - d_summa,'') 
							else 0 end, -- сумма кредит
			korr_acc = '000000000',
			DEP_K_NAME = isnull((select top 1 NAME from DICTIONARY_DEPARTMENT where link = @iThisDep),''),
			INN_K = isnull((select top 1 INN from DICTIONARY_DEPARTMENT where link = @iThisDep),''),
			PPP_K = isnull((select top 1 VED from DICTIONARY_DEPARTMENT where link = @iThisDep),''),
			OKTMO_K = isnull((select top 1 OKTMO from DICTIONARY_DEPARTMENT where link = @iThisDep),''), 
			D_ND = case when R.Mask_KBK like '%ДЕН%' then 1 else 0 end-- Признак платежа ,
			--R.Calc_Order
	from dbo.ARestTableByDateAccounts(@dEndDate, @bid) A
	INNER JOIN @temp_nastr_rest R on R.link_account = account and R.Link_Col = @LC and R.[Type] = 3
	LEFT JOIN dbo.KL_KBK K on K.Link = A.KBK and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end) > 0)
	left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	LEFT JOIN dbo.DEPARTMENTS D ON D.LINK = A.DEP
	left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
	left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
	LEFT JOIN @filter_kbk F on K.Code = F.kbk
	where dep_link = @iThisDep
			and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and r1.link = r.link)
		AND (F.kbk IS NOT NULL OR isnull(@nabor_filter, '') = '')
		AND (R.TYPE_KBK = 0 OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		



-- select * from #tTemp
	
	delete @temp_nastr_rest where Link_Col = @LC

	exec dbo.BufferClear @bid	
end


insert into @tTempRes2 (DEP_NAME,INN, PPP, OKTMO, EL_BUDG, ACC_CODE, KBK, summa_db, summa_kr, KORR_ACC,DEP_K_NAME,INN_K,PPP_K,OKTMO_K, D_ND)
select DEP_NAME,INN, PPP, OKTMO, EL_BUDG, ACC_CODE, KBK, SUM(summa_db), SUM(summa_kr), KORR_ACC,DEP_K_NAME,INN_K,PPP_K,OKTMO_K, D_ND
from @tTempRes 
where DEP_NAME <> 'корреспондент_не_указан'
group by DEP_NAME,INN, PPP, OKTMO, EL_BUDG, ACC_CODE, KBK, KORR_ACC,DEP_K_NAME,INN_K,PPP_K,OKTMO_K, D_ND
union
select DEP_NAME,INN, PPP, OKTMO, EL_BUDG, ACC_CODE, KBK, SUM(summa_db), SUM(summa_kr), KORR_ACC,DEP_K_NAME,INN_K,PPP_K,OKTMO_K, D_ND
from @tTempRes 
where DEP_NAME = 'корреспондент_не_указан'
group by DEP_NAME,INN, PPP, OKTMO, EL_BUDG, ACC_CODE, KBK, KORR_ACC,DEP_K_NAME,INN_K,PPP_K,OKTMO_K, D_ND

if @table in (1,3) 
	SELECT 
--	[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'00000000000',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
--	[CODE] = LEFT(RTRIM(PPP)+'   ',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '  ',2) + LEFT(rtrim(KBK) + '                 ',17) + LEFT(RTRIM(KORR_ACC) + '         ',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKTMO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL1] = DEP_NAME, -- Наименование контрагента
	[COL2] = INN,
	[COL3] = PPP, -- ППП
	[COL4] = OKTMO, -- ОКАТО
	[COL5] = EL_BUDG, -- Элемент бюджета
	[COL6] = substring(rtrim(KBK),1,3), -- АДМ
	[COL7] = substring(rtrim(KBK),4,14), -- КБК
	[COL8] = SUMMA_DB, -- сумма дебет
	[COL9] = SUMMA_KR, -- сумма кредит
	[COL10] = KORR_ACC, -- Код корреспондирующего счёта бюджетного учета
	[COL11] = DEP_K_NAME,
	[COL12] = INN_K,
	[COL13] = PPP_K,
	[COL14] = OKTMO_K,
	[COL15] = cast (isnull(d_nd,'') as varchar), -- Признак платежа
	[COL16]= LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKTMO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL17]= RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8)
	FROM @tTempRes2
	where  summa_db <> 0 or summa_kr <> 0
	ORDER BY NUM_PP

else 
	SELECT 
	--[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'00000000000',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	--[CODE] = LEFT(RTRIM(PPP)+'   ',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '  ',2) + LEFT(rtrim(KBK) + '                 ',17) + LEFT(RTRIM(KORR_ACC) + '         ',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKTMO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL1] = DEP_NAME, -- Наименование контрагента
	[COL2] = INN,
	[COL3] = PPP, -- ППП
	[COL4] = OKTMO, -- ОКАТО
	[COL5] = EL_BUDG, -- Элемент бюджета
	[COL6] = substring(rtrim(KBK),1,3), -- АДМ
	[COL7] = substring(rtrim(KBK),4,4), -- РзПр
	[COL8] = substring(rtrim(KBK),8,7), -- ЦСР
	[COL9] = substring(rtrim(KBK),15,3),-- ВР
	[COL10] = SUMMA_DB, -- сумма дебет
	[COL11] = SUMMA_KR, -- сумма кредит
	[COL12] = KORR_ACC, -- Код корреспондирующего счёта бюджетного учета
	[COL13] = DEP_K_NAME,
	[COL14] = INN_K,
	[COL15] = PPP_K,
	[COL16] = OKTMO_K,
	[COL17] = cast (isnull(d_nd,'') as varchar), -- Признак платежа
	[COL18] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKTMO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL19] = RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8)
	FROM @tTempRes2
	where  summa_db <> 0 or summa_kr <> 0
	ORDER BY NUM_PP





GO


GRANT EXECUTE ON dbo.[RB_CALC_0503125G_15_NEW] TO PUBLIC

GO



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

GO

CREATE PROCEDURE [dbo].SD_N_TABEL_FILL_EMPLS_BUFFER
	@BUFFER_CODE VARCHAR(20) = NULL,	
	@DATE DATETIME = NULL,
	@FLAG_PERIOD TINYINT = NULL,
	@LINK_KBK INT = NULL,
	@DEP_LINK INT	= NULL,
	@TIME INT = NULL
AS

/*
ИСПОЛЬЗУЕТСЯ ДЛЯ РАСЧЕТА ПРЕМИИ
*/
IF ISNULL(@TIME,0) = 1
	SET @TIME = -1

SET @LINK_KBK = COALESCE(@LINK_KBK,0)

SET NOCOUNT ON

DECLARE 
	@DAT  DATETIME, 
	@DAT1 DATETIME,
	@DAT2 DATETIME,
	@EM DATETIME

IF ISNULL(@FLAG_PERIOD,0) <=2
	SET @EM = DBO.DATEENDOFMONTH(@DATE)
ELSE
	SET @EM = @DATE
	
SET @DAT = CONVERT(DATETIME,ISNULL(@DATE,GETDATE()),104)
SET	@DAT1 = DATEADD(DAY,1-DAY(@DAT),@DAT)
SET	@DAT2 = DATEADD(DAY,-1,DATEADD(MONTH,1,@DAT1))

CREATE TABLE #VARKSTMP
([LINK]				[INT],
 [ORDERS]			[INT],
 [TAB_NUMER]		[VARCHAR] (6),
 [NAME_EMPL]		[VARCHAR] (30),
 [REF_EMPL]			[INT],
 [LINK_SOVM]		[INT],
 [DATE1]			[DATETIME],		
 [DATE2]			[DATETIME],		
 [DAY]				[NUMERIC] (5,2),
 [HOUR]				[NUMERIC] (18,2),
 [DAY_NORM]			[NUMERIC] (10,4),
 [HOUR_NORM]		[NUMERIC] (10,2),
 [GRAPH_NAME]		[VARCHAR] (30),
 [GRAPH_LINK]		[INT],
 [SUMMA_BASE]		[NUMERIC] (18,2),
 [SUMMA] 			[NUMERIC] (18,2),
 [SUMMA_VIPL]		[NUMERIC] (18,2),
 [SUMMA_ALL]		[NUMERIC] (18,2),
 [PERCENT]			[NUMERIC] (18,2),
 [RATE]				[NUMERIC] (5,2),
 [REF_PAY]			[INT],
 [CODE_PAY]			[VARCHAR] (10),
 [NAME_PAY]			[VARCHAR] (60),
 [WAY_CALC]			[TINYINT],
 [DATE1_PAY]		[DATETIME],  
 [DATE2_PAY]		[DATETIME],
 WDAYS				NUMERIC(18,2), 
 NDAYS				NUMERIC(18,2),  
 SYST_PAY			TINYINT,
 LINK_KBK			INT,
 CODE_KBK			VARCHAR(30)	
)

----------------
CREATE TABLE #BASIS_SUM 
	(LINK_EMPL INT, LINK_SOVM INT, LINK_PAY INT, SUMMA_BASE NUMERIC(18,2), PERC NUMERIC(18,2), SUMMA NUMERIC(18,2), LINK_KBK INT, WAY_CALC TINYINT, 
		DATE_BEGIN DATETIME, DATE_END DATETIME, WDAYS NUMERIC(18,2), NDAYS NUMERIC(18,2), [DAYS] NUMERIC(5,2), [HOURS] NUMERIC(18,2) )

---------------
IF (DBO.SA_GET_OPTION_BY_CODE('DOC_ADD_PREMIUM_OPT3') = 2 AND ISNULL(@FLAG_PERIOD,0) = 1) OR ISNULL(@FLAG_PERIOD,0) = 3

	INSERT INTO #BASIS_SUM (LINK_EMPL, LINK_SOVM, LINK_PAY, SUMMA_BASE, PERC, SUMMA, LINK_KBK, WAY_CALC, DATE_BEGIN, DATE_END, WDAYS, NDAYS, [DAYS], [HOURS])
	SELECT LINK_EMPL, LINK_SOVM, LINK_PAY, SUMMA_BASE, PERC, SUMMA, LINK_KBK, 1, @DATE, @EM, NDAYS, NDAYS, 0, 0 FROM DBO.SA_ALL_PAYS_ALL_DATE0(DEFAULT,@EM, @BUFFER_CODE, @DEP_LINK)  WHERE LINK_SOVM = 0

ELSE

	INSERT INTO #BASIS_SUM (LINK_EMPL, LINK_SOVM, LINK_PAY, SUMMA_BASE, PERC, SUMMA, LINK_KBK, WAY_CALC, DATE_BEGIN, DATE_END, WDAYS, NDAYS, [DAYS], [HOURS])
	SELECT LINK_EMPL, LINK_SOVM, LINK_PAYS, SUMMA_BASE, PERC, SUMMA, LINK_KBK, WAY_CALC, DATE_BEGIN, DATE_END, WDAYS, NDAYS, [DAYS], [HOURS] FROM DBO.SA_ALL_PAYS_ALL(DEFAULT, @EM,@BUFFER_CODE, @DEP_LINK, @TIME) WHERE LINK_SOVM = 0

-----------------
INSERT INTO #VARKSTMP ([LINK],[ORDERS],[TAB_NUMER],[NAME_EMPL],[REF_EMPL],[LINK_SOVM], [DATE1],[DATE2],		
						[DAY],[HOUR],[DAY_NORM],[HOUR_NORM],[GRAPH_NAME],[GRAPH_LINK],[SUMMA_BASE],[SUMMA],
						[SUMMA_VIPL],[SUMMA_ALL],[PERCENT],[RATE],[REF_PAY],[CODE_PAY],[NAME_PAY],[WAY_CALC],
						[DATE1_PAY],[DATE2_PAY], WDAYS, NDAYS, SYST_PAY, LINK_KBK, CODE_KBK)
SELECT 
	[LINK]			= 0,
	[ORDERS]		= 0,
	[TAB_NUMER]		= SUBSTRING(RTRIM(LTRIM(EM.TAB)),1,6),
	[NAME_EMPL]		= SUBSTRING(LTRIM(RTRIM(COALESCE(P.FM,''))) + ' ' + LEFT(LTRIM(RTRIM(COALESCE(P.IM,''))),1) + '.' + LEFT(LTRIM(RTRIM(COALESCE(P.OT,''))),1) + '.',1,30),
	[LINK_EMPL] 	= E.LINK,
	[LINK_SOVM]		= 0,
	[DATE1]			= @DAT1,
	[DATE2]			= @DAT2,
	[DAY]			= [DAYS], --РАССЧИТЫВАЕТСЯ В ПРГ-ФАЙЛЕ
	[HOUR]			= [HOURS], --РАССЧИТЫВАЕТСЯ В ПРГ-ФАЙЛЕ
	[DAY_NORM]		= 0, --РАССЧИТЫВАЕТСЯ В ПРГ-ФАЙЛЕ
	[HOUR_NORM] 	= 0, --РАССЧИТЫВАЕТСЯ В ПРГ-ФАЙЛЕ
	[GRAPH_NAME]	= SUBSTRING(RTRIM(LTRIM(G.NAME)),1,30),
	[GRAPH_LINK]	= E.GRAPH_LINK,
	[SUMMA_BASE]	= CONVERT(NUMERIC(18,2),COALESCE( DPE.SUMMA_BASE ,0)),
	[SUMMA]		    = ISNULL(CONVERT(NUMERIC(18,2), DPE.SUMMA ),0),
	[SUMMA_VIPL]	= 0,
	[SUMMA_ALL]		= ISNULL(CONVERT(NUMERIC(18,2), DPE.SUMMA ),0),
	[PERCENT] 		= PERC,
	[RATE]			= COALESCE(num_stake,0),
	[REF_PAY]		= DPE.LINK_PAY,
	[CODE_PAY]		= SUBSTRING(RTRIM(LTRIM(PS.CODE)),1,10),
	[NAME_PAY]		= SUBSTRING(RTRIM(LTRIM(PS.NAME)),1,60),
	[WAY_CALC]		= DPE.WAY_CALC,
	[DATE1_PAY]		= DPE.DATE_BEGIN,
	[DATE2_PAY]		= ISNULL(DPE.DATE_END,CONVERT(DATETIME,'01.01.3000',104)),
	WDAYS,
	NDAYS,
	E.SYST_PAY,
	DPE.LINK_KBK, LEFT(SFIN.CODE,20)
FROM 
	dbo.EMPL E 
	INNER JOIN #BASIS_SUM DPE ON DPE.LINK_EMPL = E.LINK
	INNER JOIN DBO.PAYS PS ON PS.LINK = DPE.LINK_PAY
	INNER JOIN DBO.GRAPH G ON E.GRAPH_LINK = G.LINK
	INNER JOIN DBO.EMPL EM ON EM.LINK = E.LINK
	INNER JOIN DBO.PERSON P ON EM.PERS_LINK = P.LINK
	LEFT JOIN DBO.SA_EMPLS_INFO(@EM, DEFAULT) D ON E.LINK = D.EMPL_LINK
	LEFT JOIN DBO.SAL_SFIN SFIN ON SFIN.LINK = DPE.LINK_KBK
WHERE 
	DPE.SUMMA  > 0
    AND 
	(@LINK_KBK = 0 OR DPE.LINK_KBK = @LINK_KBK)	

ORDER BY 3

----------
IF ISNULL(@TIME,0) = -1 AND DBO.SA_GET_OPTION_BY_CODE('DOC_ADD_PREMIUM_OPT3') = 0
	UPDATE #VARKSTMP 
	SET WDAYS = dbo.SA_GET_EMPL_WD (REF_EMPL, 0, DEFAULT, @DAT1, @DAT2, DEFAULT, 0)
	WHERE SYST_PAY = 1

----------
IF ISNULL(@TIME,0) = -1 AND DBO.SA_GET_OPTION_BY_CODE('DOC_ADD_PREMIUM_OPT3') = 0
	UPDATE #VARKSTMP 
	SET WDAYS = dbo.SA_GET_EMPL_WH (REF_EMPL, 0, DEFAULT, @DAT1, @DAT2, DEFAULT, 0)
	WHERE SYST_PAY = 2	

----------
IF ISNULL(@TIME,0) = -1
	UPDATE #VARKSTMP SET WDAYS = CASE WHEN SYST_PAY = 1 THEN [DAY] ELSE [HOUR] END

----------
SELECT [LINK],[ORDERS],[TAB_NUMER],[NAME_EMPL],[REF_EMPL],[DATE1],[DATE2],		
 		 CONVERT(INT,[DAY]) AS [DAY],[HOUR],CONVERT(INT,[DAY_NORM]) AS [DAY_NORM],
       [HOUR_NORM],[GRAPH_NAME],[GRAPH_LINK],[SUMMA_BASE],[SUMMA],
		 [SUMMA_VIPL],[SUMMA_ALL],[PERCENT],[RATE],[REF_PAY],[CODE_PAY],[NAME_PAY],[WAY_CALC],
		 [DATE1_PAY],[DATE2_PAY], WDAYS, NDAYS, DAY, HOUR, SYST_PAY, LINK_KBK, CODE_KBK
FROM #VARKSTMP

SET NOCOUNT OFF



GO


GRANT EXECUTE ON dbo.[SD_N_TABEL_FILL_EMPLS_BUFFER] TO PUBLIC

GO



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

GO

CREATE PROCEDURE dbo.SD_N_TABEL_MES_FILL
/*Начисление по табелю за месяц в целом*/
@varKSnLink	 int = 0, @mode tinyint =0, @varKSdDate datetime = null, @BufferCode varchar(15) = '', @link_r int = 0
/*Если @mode = 0, то @varKSnLink - ссылка на табель, 
если @mode= 1, то @varKSnLink - ссылка на сотрудника
Результат сразу сохранить в расчете с линком @link_r
*/

AS

/*
© Кейсистемс (Keysystems), 2005
Игнатьев А.Н. 23/06/2005 Расчет по табелям за месяц
*/

SET NOCOUNT ON

DECLARE 	@varKSdat [datetime], 
	  	@varKSDat1 [datetime],
		@varKSDat2 [datetime] --,

IF @mode = 0
	SET 	@varKSdat = CONVERT(DATETIME,ISNULL((SELECT TOP 1 TAB.PERIOD FROM dbo.TABELS TAB WHERE TAB.LINK_DOC = @varKSnLink),GETDATE()),104)
else
	SET 	@varKSdat = @varKSdDate

SET @varKSdat = dbo.DateEndOfMonth(@varKSdat)

declare @p int
Set @p = (case @mode when 0 then 0 when 1 then @varKSnLink when 2 then 0 end)

declare @t3 int
Set @t3 = (Select LINK from s_objects where code = 'U_TABELS_MES')

SET	@varKSDat1 	= DATEADD(DAY,1-DAY(@varKSdat),@varKSdat)
SET	@varKSDat2 	= DATEADD(DAY,-1,DATEADD(MONTH,1,@varKSDat1))

CREATE TABLE #varKSTMP 
([LINK] 				[int],
 [ORDERS]				[int] IDENTITY(1,1),
 [TAB_NUMER]			[varchar] (6),
 [NAME_EMPL]			[varchar] (30),
 [REF_EMPL]				[int],
 [DATE1]				[datetime],		
 [DATE2]				[datetime],		
 [DAY]					[numeric] (4,0),
 [HOUR]					[numeric] (10,2),
 [DAY_NORM]				[numeric] (4,0),
 [HOUR_NORM]			[numeric] (10,2),
 [GRAPH_NAME]			[varchar] (30),
 [GRAPH_LINK]			[int],
 [SUMMA_BASE]			[numeric] (18,2),
 [SUMMA] 				[numeric] (18,2),
 [SUMMA_VIPL]			[numeric] (18,2),
 [SUMMA_ALL]			[numeric] (18,2),
 [PERCENT]				[numeric] (18,2),
 [RATE]					[numeric] (5,2),
 [REF_PAY]				[int],
 [CODE_PAY]				[varchar] (10),
 [NAME_PAY]				[varchar] (60),
 [WAY_CALC]				[tinyint],
 [DATE1_PAY]			[datetime],  
 [DATE2_PAY]			[datetime],
---- Игнатьев А.Н. Чтобы узнать отработанное время по явке из дополнительного табеля
 [TYP_DOP_TAB]	[Int],   -- Код явки по дополнительному табелю (Тип дополнительного табеля),
---- Игнатьев А.Н. Чтобы расчитать вид оплаты по явке из дополнительного табеля
 [Chas]					[numeric] (19,2),	-- За первые [] часов
 [PERCENT1]				[numeric] (19,2), 	-- оплата по [] процентов
 [PERCENT2]				[numeric] (19,2),	-- за остальное время - по [] процентов
 LINK_KBK				INT,
 CODE_KBK				VARCHAR(30),
 K					NUMERIC(18,4) default(1)	-- Для учета изменения начислений в течении месяца	
)

---------------------
IF NOT EXISTS (Select *
	FROM dbo.SDOC DOC,dbo.TABELS T,dbo.EMPL E
	WHERE 	((DOC.LINK = @varKSnLink and @mode = 0) or (@mode in (1,2) AND YEAR(t.PERIOD) = Year(@varKSdDate) AND month(t.PERIOD) = month(@varKSdDate)))
		AND DOC.OBJECT = @t3
		 AND DOC.LINK = T.LINK_DOC AND T.LINK_EMPL = E.LINK 
	)
Begin
	SELECT 	[LINK],[ORDERS],[TAB_NUMER],[NAME_EMPL],[REF_EMPL],[DATE1],[DATE2], CONVERT(int,[DAY]) AS [DAY],[HOUR],CONVERT(int,[DAY_NORM]) AS [DAY_NORM],
	      	[HOUR_NORM],[GRAPH_NAME],[GRAPH_LINK],[SUMMA_BASE],[SUMMA], [SUMMA_VIPL],[SUMMA_ALL],[PERCENT],[RATE],[REF_PAY],[CODE_PAY],[NAME_PAY],[WAY_CALC],
		[DATE1_PAY],[DATE2_PAY],LINK_KBK,CODE_KBK
	FROM #varKSTMP

	RETURN 0
End

--Для кого считать
declare @buf_id varchar(20)
if @mode < 2 begin
	exec dbo.GetRandStr 20, @buf_id out
	
	insert into dbo.buffer (id, link)
	Select distinct @buf_id, T.LINK_EMPL
	from
		dbo.SDOC DOC inner join dbo.TABELS T on DOC.LINK = T.LINK_DOC
	WHERE 	
		(DOC.LINK = @varKSnLink and @mode = 0) 

	insert into dbo.buffer (id, link)
	select @buf_id, @varKSnLink where @mode= 1
end
else
	Set @buf_id = @BufferCode

---------------------
SELECT * INTO #DPEE FROM dbo.sa_all_pays_all(@p,@varKSdat,@buf_id,default,default) 

delete from dbo.buffer where id = @buf_id

-------------  Информация на базе табеля по явкам ---------------
INSERT INTO #varKSTMP ([LINK],[TAB_NUMER],[NAME_EMPL],[REF_EMPL],[DATE1],[DATE2],		
						[DAY],[HOUR],[DAY_NORM],[HOUR_NORM],[GRAPH_NAME],[GRAPH_LINK],[SUMMA_BASE],[SUMMA],
						[SUMMA_VIPL],[SUMMA_ALL],[PERCENT],[RATE],[REF_PAY],[CODE_PAY],[NAME_PAY],[WAY_CALC],
						[DATE1_PAY],[DATE2_PAY],LINK_KBK,CODE_KBK,K)

SELECT 
	[LINK]			= DOC.LINK,
	[TAB_NUMER]		= LEFT(E.TAB,6),
	[NAME_EMPL]		= LEFT(dbo.sd_GetEmplName(E.LINK),30),
	[REF_EMPL] 		= E.LINK,
	[DATE1]			= @varKSDat1,
	[DATE2]			= @varKSDat2,
	[DAY]			= 0,
	[HOUR]			= 0,
	[DAY_NORM]		= ISNULL(CONVERT(NUMERIC(4,0),dbo.NORM_DAYS(E.LINK,MONTH(@varKSDat1),YEAR(@varKSDat1))),0),
	[HOUR_NORM] 		= ISNULL(CONVERT(NUMERIC(10,2), dbo.NORM_HOURS(E.LINK,MONTH(@varKSDat1),YEAR(@varKSDat1))),0),
	[GRAPH_NAME]		= LEFT(G.NAME,30),
	[GRAPH_LINK]		= E.GRAPH_LINK,
	[SUMMA_BASE]		= CONVERT(NUMERIC(18,2),Coalesce( dpe.summa_base ,0)),
	[SUMMA]		    	= 0.00,
	[SUMMA_VIPL]		= (case when @mode = 0 then CONVERT(NUMERIC(18,2),ISNULL(OLD.SUMMA,0)) else CONVERT(NUMERIC(18,2),ISNULL(OLDA.SUMMA,0)) end),
	[SUMMA_ALL]		= CONVERT(NUMERIC(18,2),Coalesce( dpe.summa,0)),
	[PERCENT] 		= CONVERT(NUMERIC(18,2),Coalesce( dpe.perc ,0)),
	[RATE]			= COALESCE(NS.num_stake,0),
	[REF_PAY]		= DPE.LINK_PAYS,
	[CODE_PAY]		= LEFT(DPE.CODE_PAYS,10),
	[NAME_PAY]		= LEFT(DPE.NAME_PAYS,60),
	[WAY_CALC]		= DPE.WAY_CALC,
	[DATE1_PAY]		= DPE.DATE_BEGIN,
	[DATE2_PAY]		= ISNULL(DPE.DATE_END,CONVERT(DATETIME,'01.01.3000',104)),
	DPE.LINK_KBK, LEFT(DPE.CODE_KBK,30), DPE.WDAYS / DPE.NDAYS 
FROM 
	dbo.SDOC DOC INNER JOIN dbo.TABELS T ON DOC.LINK = T.LINK_DOC
	INNER JOIN dbo.EMPL E ON T.LINK_EMPL = E.LINK
	INNER JOIN #DPEE DPE ON (DPE.LINK_EMPL = T.LINK_EMPL AND DPE.SUMMA  > 0)
	INNER JOIN dbo.GRAPH G ON E.GRAPH_LINK = G.LINK 
	left join dbo.sa_EmplsNumStake(0,DEFAULT) NS on NS.empl_link = e.link
	LEFT join ( SELECT LINK_EMPL, LINK_PAYS, SUMMA = SUM(SUMMA) FROM dbo.CALCULATE_JURNAL SJC INNER JOIN dbo.SDOC_TABEL ST ON (SJC.LINK_DOC = ST.LINK_UP)
		WHERE ST.REF_DOC = @varKSnLink GROUP BY LINK_EMPL, LINK_PAYS) OLD on OLD.LINK_EMPL = E.LINK AND OLD.LINK_PAYS = DPE.link_pays
	LEFT join ( SELECT LINK_EMPL, LINK_PAYS, SUMMA = SUM(SUMMA) FROM dbo.CALCULATE_JURNAL SJC INNER JOIN dbo.SDOC_TABEL ST ON (SJC.LINK_DOC = ST.LINK_UP)
		WHERE MONTH(DATE_BEGIN) = MONTH(@varKSdat) AND YEAR(DATE_BEGIN) = YEAR(@varKSdat) GROUP BY LINK_EMPL, LINK_PAYS) OLDA on OLDA.LINK_EMPL = E.LINK AND OLDA.LINK_PAYS = DPE.link_pays
WHERE 	
	((DOC.LINK = @varKSnLink and @mode = 0) or (@mode in (1,2) AND YEAR(t.PERIOD) = Year(@varKSdDate) AND month(t.PERIOD) = month(@varKSdDate)))
	AND 
	DOC.OBJECT = @t3
ORDER BY 3

-----Игнатьев А.Н. -----------------------------------------------------
-------------  Информация на базе дополнительного табеля ---------------

INSERT INTO #varKSTMP ([LINK],[TAB_NUMER],[NAME_EMPL],[REF_EMPL],[DATE1],[DATE2],		
						[DAY],[HOUR],[DAY_NORM],[HOUR_NORM],[GRAPH_NAME],[GRAPH_LINK],[SUMMA_BASE],[SUMMA],
						[SUMMA_VIPL],[SUMMA_ALL],[PERCENT],[RATE],[REF_PAY],[CODE_PAY],[NAME_PAY],[WAY_CALC],
						[DATE1_PAY],[DATE2_PAY], 
						[TYP_DOP_TAB], [Chas], [PERCENT1], [PERCENT2],LINK_KBK,CODE_KBK,K)

SELECT 
	[LINK]			= DOC.LINK,
	[TAB_NUMER]		= LEFT(E.TAB,6),
	[NAME_EMPL]		= LEFT(dbo.sd_GetEmplName(E.LINK),30),
	[REF_EMPL] 		= E.LINK,
	[DATE1]			= @varKSDat1,
	[DATE2]			= @varKSDat2,
	[DAY]			= 0,
	[HOUR]			= 0,
	[DAY_NORM]		= 0, 
	[HOUR_NORM] 		= ISNULL(CONVERT(NUMERIC(10,2),dbo.NORM_HOURS(E.LINK,MONTH(@varKSDat1),YEAR(@varKSDat1))),0),
	[GRAPH_NAME]		= LEFT(G.NAME,30),
	[GRAPH_LINK]		= E.GRAPH_LINK,
	[SUMMA_BASE]		= CONVERT(NUMERIC(18,2),Coalesce( #DPEE.summa_base ,0)),
	[SUMMA]		    	= CONVERT(NUMERIC(18,2),0),
	[SUMMA_VIPL]		= (case when @mode = 0 then CONVERT(NUMERIC(18,2),ISNULL(dbo.SA_SUMMA_VIPL_TABEL(E.LINK, #DPEE.link_pays, @varKSnLink),0)) 
			else CONVERT(NUMERIC(18,2),ISNULL(dbo.SA_SUMMA_VIPL(E.LINK, #DPEE.link_pays, @varKSdat),0)) end),
	[SUMMA_ALL]		= CONVERT(NUMERIC(18,2),0),
	[PERCENT] 		= CONVERT(NUMERIC(18,2), (Case when ISNULL(DKD.[Chas],0) = 0 then  ISNULL(DKD.[PERCENT],0) else 0 end) ),
	[RATE]			= COALESCE(NS.num_stake,0),
	[REF_PAY]		= DKD.LINK_PAYS,
	[CODE_PAY]		= LEFT(P.CODE,10),
	[NAME_PAY]		= LEFT(P.[NAME],60),
	[WAY_CALC]		= P.WAY_CALC,
	[DATE1_PAY]		= DKD.DATE,
	[DATE2_PAY]		= ISNULL(
			((select top 1 l1.[DATE] from dictionary_koef_dopl as l1 where l1.TAB_TYP = dkd.TAB_TYP and l1.[DATE] > T.[PERIOD] order by l1.[DATE] desc) -1)
					, CONVERT(DATETIME,'01.01.3000',104)),  
	[TYP_DOP_TAB]		= TAB_TYP,   -- Код явки по дополнительному табелю (Тип дополнительного табеля)
	[Chas]			= DKD.[Chas], -- За первые [] часов
	[PERCENT1]		= DKD.[PERCENT], -- оплата по [] процентов
	[PERCENT2]		= DKD.[PERCENT2], -- за остальное время - по [] процентов
	#DPEE.LINK_KBK, left(#DPEE.CODE_KBK,30),#DPEE.WDAYS / #DPEE.NDAYS
FROM 	
	dbo.SDOC DOC INNER JOIN dbo.TABELS T ON DOC.LINK = T.LINK_DOC 
	INNER JOIN dbo.EMPL E ON T.LINK_EMPL = E.LINK	
	INNER JOIN #DPEE ON T.LINK_EMPL = #DPEE.link_empl 
	INNER JOIN dbo.DICTIONARY_KOEF_DOPL as DKD ON  dkd.LINK_PAYS = #DPEE.link_pays--Чтобы узнать виды оплат
	INNER JOIN dbo.PAYS as P ON DKD.LINK_PAYS = P.LINK
	INNER JOIN dbo.GRAPH G ON E.GRAPH_LINK = G.LINK
	left join dbo.sa_EmplsNumStake(0,DEFAULT) NS on NS.empl_link = e.link
	LEFT join ( SELECT LINK_EMPL, LINK_PAYS, SUMMA = SUM(SUMMA) FROM dbo.CALCULATE_JURNAL SJC INNER JOIN dbo.SDOC_TABEL ST ON (SJC.LINK_DOC = ST.LINK_UP)
		WHERE ST.REF_DOC = @varKSnLink GROUP BY LINK_EMPL, LINK_PAYS) OLD on OLD.LINK_EMPL = E.LINK AND OLD.LINK_PAYS = #DPEE.link_pays
	LEFT join ( SELECT LINK_EMPL, LINK_PAYS, SUMMA = SUM(SUMMA) FROM dbo.CALCULATE_JURNAL SJC INNER JOIN dbo.SDOC_TABEL ST ON (SJC.LINK_DOC = ST.LINK_UP)
		WHERE MONTH(DATE_BEGIN) = MONTH(@varKSdat) AND YEAR(DATE_BEGIN) = YEAR(@varKSdat) GROUP BY LINK_EMPL, LINK_PAYS) OLDA on OLDA.LINK_EMPL = E.LINK AND OLDA.LINK_PAYS = #DPEE.link_pays
WHERE 
	((DOC.LINK = @varKSnLink and @mode = 0) or (@mode in (1,2) AND YEAR(t.PERIOD) = Year(@varKSdDate) AND month(t.PERIOD) = month(@varKSdDate)))
	AND 
	DOC.OBJECT = @t3
	AND	-- Определение списка видов оплат и номер графика по каждому работнику
	dkd.[DATE]= ( select top 1 l1.[DATE] from dictionary_koef_dopl as l1 where l1.TAB_TYP = dkd.TAB_TYP and l1.[DATE] <= T.[PERIOD] order by l1.[DATE] desc) 

--------- Расчет времени по норме за каждый отрезочек времени
SELECT 
	T1.ORDERS, count(distinct (YEAR(N.PERIOD) *100 +MONTH(N.PERIOD)) *100 +N.[DAY]) as NORM_DAY, SUM(N.HOURS * T1.RATE) as NORM_HOUR
INTO
	#N
FROM 
	#varKSTMP T1 LEFT join 
	(  SELECT LINK_EMPL = E.LINK, G.PERIOD, [DAY], GD.HOURS FROM  dbo.EMPL E INNER JOIN GRAPHICS G ON G.GRAPH_LINK = E.GRAPH_LINK INNER JOIN dbo.GRAPHIC_DAYS GD ON GD.LINK_UP=G.LINK WHERE GD.HOURS<>0 
	) N ON N.LINK_EMPL = T1.REF_EMPL AND DATEADD(d,N.[DAY],N.PERIOD)-1 BETWEEN DATE1_PAY AND DATE2_PAY
GROUP BY 
	T1.REF_EMPL,T1.ORDERS

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

DELETE FROM #varKSTMP 
WHERE NOT(DATE1_PAY-1 < DATE2 AND DATE2_PAY+1 > DATE1 AND (WAY_CALC IN (select CODE from WAY_CALC where type = 1 and (const_pay_empl = 1 or CODE in (17,18,19))) )) 

------------
UPDATE #varKSTMP SET DATE1 = DATE1_PAY WHERE DATE1_PAY > DATE1
UPDATE #varKSTMP SET DATE2 = DATE2_PAY WHERE DATE2_PAY < DATE2

-----------
UPDATE #varKSTMP  
SET 
	[DAY] 		=  ISNULL(CONVERT(NUMERIC(4,0), ROUND(dbo.WORKHOURS_TABMES(T1.REF_EMPL,YEAR(T1.DATE1)*100+MONTH(T1.DATE1),T1.LINK,Default)/(8 * T1.RATE ),0) * COALESCE(T1.K,1) ),0),
	[HOUR] 		=  ISNULL(CONVERT(NUMERIC(10,2),dbo.WORKHOURS_TABMES(T1.REF_EMPL,YEAR(T1.DATE1)*100+MONTH(T1.DATE1),T1.LINK,Default) * COALESCE(T1.K,1)),0),
	[SUMMA_ALL]	=  SUMMA_ALL
FROM 	
	#varKSTMP T1
WHERE
	WAY_CALC <> 16 --Для всех видов оплат, кроме тех, которые расчитываются по дополнительному табелю

----------  Для видов оплат по дополнительному табелю ---------
UPDATE #varKSTMP  
SET     [HOUR] 		=  ISNULL(CONVERT(NUMERIC(10,2), dbo.WORKHOURS_TABMES(T1.REF_EMPL,YEAR(T1.DATE1)*100+MONTH(T1.DATE1),T1.LINK,TYP_DOP_TAB) ),0)
FROM 	#varKSTMP T1
WHERE	WAY_CALC = 16

--------------------------
Delete from #varKSTMP where WAY_CALC = 16 and COALESCE([HOUR],0) = 0

--------------------------
UPDATE #varKSTMP  
SET    	[SUMMA_ALL] = 	ISNULL(CONVERT(NUMERIC(10,2), 
		(CASE WHEN (COALESCE([Chas],0) = 0 AND COALESCE([HOUR_NORM],0) > 0) THEN /*Расчет по простой схеме*/
			[SUMMA_BASE] / [HOUR_NORM] * [HOUR] * [PERCENT1] / 100 
		ELSE
			dbo.SUM_MES_TAB(T1.REF_EMPL, YEAR(T1.DATE1)*100+MONTH(T1.DATE1), [LINK], [TYP_DOP_TAB], [SUMMA_BASE], [Chas], [PERCENT1], [PERCENT2], [HOUR_NORM], [HOUR])
		END)
 ),0)

FROM 	#varKSTMP T1
WHERE	WAY_CALC = 16

--------------------------
UPDATE #varKSTMP  
SET [SUMMA_ALL] = CASE WHEN WAY_CALC = 22 THEN
				SUMMA_ALL /*Сумма не зависит от табеля*/
		  ELSE
			(case when WAY_CALC <> 16 then /*Игнатьев А.Н. Для всех видов оплат, кроме тех, которые расчитываются по дополнительному табелю*/
				[SUMMA_ALL]*(CASE WHEN dbo.kd_GetEmplSystPay(REF_EMPL) = 1 
						THEN (CASE WHEN DAY_NORM=0  THEN 0 ELSE [DAY]/ ISNULL(CONVERT(NUMERIC(4,0),N.NORM_DAY),999999999999)  END)
					   ELSE (CASE WHEN HOUR_NORM=0  THEN 0 ELSE [HOUR]/ ISNULL(CONVERT(NUMERIC(10,2),N.NORM_HOUR),9999999999999) END) END)
				else [SUMMA_ALL]
			end)
		  END
FROM #varKSTMP T1 left join #N N on N.ORDERS = T1.ORDERS

-----------
select Link_EMPL = REF_EMPL, Link_PAY = REF_PAY, SUMMA = SUM(SUMMA_ALL) into #tmp from #varKSTMP group by REF_EMPL, REF_PAY

-----------
UPDATE #varKSTMP  
SET SUMMA_VIPL = SUMMA_VIPL * SUMMA_ALL / (Select (Case when coalesce(SUMMA,0) <> 0 then coalesce(SUMMA,0) else 1 end) from #tmp where Link_EMPL = REF_EMPL and Link_PAY = REF_PAY)
FROM 	#varKSTMP T1
/*Игнатьев А.Н. Для всех видов оплат, кроме тех, которые расчитываются по дополнительному табелю*/
WHERE	WAY_CALC <> 16 

-----------
--UPDATE #varKSTMP SET [SUMMA] = (CASE WHEN  [SUMMA_ALL]-[SUMMA_VIPL] > 0 THEN [SUMMA_ALL]-[SUMMA_VIPL] ELSE 0 END)	
--FROM #varKSTMP T1
UPDATE #varKSTMP SET [SUMMA] = COALESCE([SUMMA_ALL],0)-COALESCE([SUMMA_VIPL],0)
FROM #varKSTMP T1

-----------
if coalesce(@link_r,0) <> 0 begin
	declare @PrevOrd int
	set @PrevOrd = coalesce((select max(ORDERS) from dbo.SDOC_TABEL_TABLE where LINK_UP  = @link_r),0)

	insert into dbo.SDOC_TABEL_TABLE (
		LINK_UP,ORDERS,LINK_EMPL,LINK_PAY,SUMMA_ALL,SUMMA_VIPL,SUMMA,SUMMA_BASE,DATE1,DATE2,DAYS,HOURS,DAY_NORM,HOUR_NORM,PERC,RATE,LINK_KBK
	)
	SELECT @link_r, ORDERS + @PrevOrd, [REF_EMPL],[REF_PAY],[SUMMA_ALL],[SUMMA_VIPL],[SUMMA],[SUMMA_BASE],[DATE1],[DATE2],
			CONVERT(int,[DAY]) AS [DAY],[HOUR],CONVERT(int,[DAY_NORM]) AS [DAY_NORM],[HOUR_NORM],[PERCENT],[RATE], LINK_KBK
	FROM #varKSTMP
	ORDER BY [NAME_EMPL], convert(int,[CODE_PAY]), [DATE1_PAY]
end else
	SELECT 	[LINK],[ORDERS],[TAB_NUMER],[NAME_EMPL],[REF_EMPL],[DATE1],[DATE2], CONVERT(int,[DAY]) AS [DAY],[HOUR],CONVERT(int,[DAY_NORM]) AS [DAY_NORM],
      		[HOUR_NORM],[GRAPH_NAME],[GRAPH_LINK],[SUMMA_BASE],[SUMMA], [SUMMA_VIPL],[SUMMA_ALL],[PERCENT],[RATE],[REF_PAY],[CODE_PAY],[NAME_PAY],[WAY_CALC],
		[DATE1_PAY],[DATE2_PAY],LINK_KBK,CODE_KBK
	FROM #varKSTMP
	order by [NAME_EMPL], convert(int,[CODE_PAY]), [DATE1_PAY]

SET NOCOUNT OFF

RETURN 0








GO


GRANT EXECUTE ON dbo.[SD_N_TABEL_MES_FILL] TO PUBLIC

GO




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

GO

/*
    © Кейсистемс (Keysystems), 2007
    Процедура формирования строк и значений формы 0503125
*/

CREATE PROCEDURE dbo.RB_CALC_0503125G_NEW
@iLSF int,
@table int
AS

declare @dBeginDate datetime,
		@dEndDate datetime,
		@dEndDate_pl datetime,
		@dCALC_DATE datetime,
		@iThisDep int,
		@nPeriod_Type tinyint,
		@cStrSql varchar(8000)
----------		
DECLARE @LF	int, 
		@LT	int,
		@LC	int,
		@orderCol int,
		@iLinkCalcForm int,
		@iLinkColDt int,
		@bid varchar(100),
		@nabor_filter varchar(1000)
---------------
				
declare @tTempRes table(DEP_NAME varchar(254),
						PPP varchar(3), 
						OKATO varchar(11), 
						EL_BUDG varchar(2), 
						KBK varchar(30), 
						ACC_CODE varchar(9), 
						summa_db numeric(20,4), 
						summa_kr numeric(20,4), 
						korr_acc varchar(9), 
						D_ND tinyint) 

declare @tTempRes2 table(DEP_NAME varchar(254),
						 PPP varchar(3), 
						 OKATO varchar(11), 
						 EL_BUDG varchar(2), 
						 KBK varchar(30), 
						 ACC_CODE varchar(9), 
						 summa_db numeric(20,4), 
						 summa_kr numeric(20,4), 
						 korr_acc varchar(9), 
						 D_ND tinyint,
						 NUM_PP int IDENTITY(1,1)) 
declare @filter_kbk table (kbk varchar(30))

-- определяем период (если в январе формируем, то берём весь предыдущий год не включая 31 декабря)
select @dEndDate = Begin_Date, @nPeriod_Type = period_type from dbo.report_saved_forms where link_saved_form = @iLSF

select @dBeginDate = dbo.DateBeginOfYear(@dEndDate)

-- set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then (@dBeginDate - (datepart(dd,@dBeginDate))) - 1 else @dBeginDate /*- (datepart(dd,@dBeginDate))*/ end
-- set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')


--if @nPeriod_Type <> 1 
--	set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then @dBeginDate - 1 else @dBeginDate end
--else
--	set @dEndDate = @dBeginDate
--
--	set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')

select @nabor_filter = REPLACE(dbo.rn_get_atr_value(@iLSF,'REPORTS_FILTER_KBK'), 'Не отобрано', '')

insert @filter_kbk (kbk)   
Select RTRIM(code) FROM rn_get_filter(@iLSF,'REPORTS_FILTER_KBK')


---------------------------------------****************************
declare @temp_nastr table (link int, [Link_Col] int NOT NULL, 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL, link_dt int, link_kt int, dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint)
declare @temp_nastr_xor table (	link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_dt int, link_kt int, dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, dt_kt tinyint)
declare @temp_nastr_rest table (	link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000),
	[type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint)
declare @temp_nastr_rest_xor table (link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000),
	[type] tinyint, type_kbk tinyint, dt_kt tinyint)


-------- ЧИТАЕМ ДАННЫЕ ОТЧЕТА
select @LF = RSF.Link_Form, 
		@iThisDep 	= Link_Organization, 
		@dEndDate	= Begin_Date + 1,
		@dCALC_DATE	= Begin_Date, 
		@dBeginDate	= dbo.DateBeginOfYear(Begin_Date),
		@nPeriod_Type = period_type
from report_saved_forms RSF  where RSF.link_saved_form = @iLSF

SET @iLinkCalcForm = dbo.RK_GET_NASTR_CALC_REPORT (@iLSF, 1)
print @iLinkCalcForm
if @iLinkCalcForm is null 
BEGIN
	exec RT_CALC_0503125G @iLSF, @table
	RETURN 0
END

set @iLinkColDt = (select top 1 RC.LINK_COL
					from dbo.REPORT_COLOUMNS RC
					inner join dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.Link_Form = @LF and RT.orders = @table and RT.orders = @table
					where @table = 2 and RC.Export_Order = 9 or @table <> 2 and RC.Export_Order = 7)
---------------------------------------------------------------------
----- ПОЛУЧАЕМ ВЫБОРКУ ИЗ ТАБЛИЦЫ НАСТРОЕК ----
insert @temp_nastr 
select C.link, C.Link_Col, Calc_Order, [Sign], DT.link , KT.link, dt_ekr, kt_ekr, [type], type_kbk, mask_kbk, dt_kt
from dbo.REPORT_CALC C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = @table and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE C.LINK_UP = @iLinkCalcForm
	AND [sign] in (1,2) and CR.[type] = 1 
	AND (rtrim (CR.DT_Mask) = '' OR CR.DT_Mask = '%' OR rtrim (CR.DT_Mask) <> '' AND DT.LINK IS NOT NULL)
	AND (rtrim (CR.KT_Mask) = '' OR CR.KT_Mask = '%' OR rtrim (CR.KT_Mask) <> '' AND KT.LINK IS NOT NULL)


-- проводки, которые мы исключаем --
insert @temp_nastr_xor 
select C.link, C.Link_Col, Calc_Order, [Sign], DT.link , KT.link, dt_ekr, kt_ekr, [type], type_kbk, dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = @table and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
where C.LINK_UP = @iLinkCalcForm
	AND [sign] = 3 and CR.[type] = 1 


--- Выборка счетов для расчета остатков ---
insert @temp_nastr_rest 
select C.link, C.Link_Col, Calc_Order, [Sign],
	case
		when DT.link is NULL then KT.link
		else DT.link
	end,
	case
		when DT.link is NULL then kt_ekr
		else dt_ekr
	end, [type],
	type_kbk,
	mask_kbk,
	dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = @table and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE C.LINK_UP = @iLinkCalcForm 
	AND CR.[type] in (2,3) and [sign] in (1,2) 
	AND (rtrim (CR.DT_Mask) = '' OR rtrim (CR.DT_Mask) <> '' AND DT.LINK IS NOT NULL)
	AND (rtrim (CR.KT_Mask) = '' OR rtrim (CR.KT_Mask) <> '' AND KT.LINK IS NOT NULL)

/*
select S1.CODE, * from @temp_nastr_rest T, S_ACCOUNTS S1 
WHERE S1.LINK = T.LINK_account
*/
--- Счета, которые исключаем для расчета остатков ---
insert @temp_nastr_rest_xor
select C.link, C.Link_Col, Calc_Order, [Sign],
	case
		when DT.link is NULL then KT.link
		else DT.link
	end,
	case
		when DT.link is NULL then kt_ekr
		else dt_ekr
	end,
	[type],
	type_kbk,
	dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = @table and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE  C.LINK_UP = @iLinkCalcForm 
	AND CR.[type] in (2,3) and [sign] = 3 
	AND (DT.LINK IS NOT NULL
		OR KT.LINK IS NOT NULL)
---------------------------------------****************
---- Обороты

	insert into @tTempRes
	select	DEP_NAME = left(isnull(D.FULL_NAME, 'корреспондент_не_указан'), 254), -- Наименование контрагента
			PPP = case when TMP.Mask_KBK like '%АДМ%' then isnull(VED.CODE, '') else '' end, -- ППП
			--OKATO = case when TMP.Mask_KBK like '%ОКАТО%' then isnull(replace(D.OKATO,' ',''), '') else '' end, -- ОКАТО
			OKATO = case when TMP.Mask_KBK like '%ОКТМО%' then isnull(replace(D.OKTMO,' ',''), '') else '' end, -- ОКАТО
			EL_BUDG = case when TMP.Mask_KBK like '%ЭЛЕМЕНТ%' then isnull(BUDG.CODE_EL, '') else '' end, -- Элемент бюджета
			KBK = isnull(replace(KBK.CODE,'.',''),''), --KBK
			ACC_CODE = case TMP.dt_kt when 0 then isnull(left(replace(SAD.CODE,'.',''),6),'') + isnull(DTS.CODE,'') else isnull(left(replace(SAK.CODE,'.',''),6),'') + isnull(KTS.CODE,'')  end,
			SUMMA_DB = case TMP.LINK_COL when @iLinkColDt then isnull(G2.SUMMA,'') else 0 end, -- сумма дебет
			SUMMA_KR = case TMP.LINK_COL when @iLinkColDt then 0 else isnull(G2.SUMMA,'') end, -- сумма кредит
			korr_acc = case TMP.dt_kt when 0 then isnull(left(replace(SAK.CODE,'.',''),6),'')  + isnull(KTS.CODE,'') else isnull(left(replace(SAD.CODE,'.',''),6),'') + isnull(DTS.CODE,'')  end, -- корреспондирующий счет
			D_ND = case when TMP.Mask_KBK like '%ДЕН%' then 1 else 0 end-- Признак платежа

	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)


	LEFT JOIN dbo.G_PROV_AP DT ON (DT.LINK_UP = G2.LINK AND DT.DB_KR = 0)
	LEFT JOIN dbo.G_PROV_AP KT ON (KT.LINK_UP = G2.LINK AND KT.DB_KR = 1)

	LEFT JOIN dbo.KOSGU DTS ON (DTS.Link = DT.SGU)
	LEFT JOIN dbo.KOSGU KTS ON (KTS.Link = KT.SGU)
	
	INNER JOIN @TEMP_NASTR TMP ON (TMP.LINK_DT = DT.ACCOUNT OR TMP.LINK_DT IS NULL)
			AND (TMP.LINK_KT = KT.ACCOUNT OR TMP.LINK_KT IS NULL)
		AND (dbo.RO_LIKE_LIST(DTS.Code, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '')
		AND (dbo.RO_LIKE_LIST(KTS.Code, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '')

	LEFT JOIN dbo.S_ACCOUNTS SAD ON SAD.LINK = DT.ACCOUNT

	LEFT JOIN dbo.S_ACCOUNTS SAK ON SAK.LINK = KT.ACCOUNT 

	LEFT JOIN dbo.KL_KBK KBK ON (TMP.dt_kt = 0 AND KBK.LINK = DT.KBK OR TMP.DT_KT = 1 AND KBK.LINK = KT.KBK)
	left join dbo.G_PROV_OS1 OS on OS.LINK_OS1 = G.LINK
	LEFT JOIN dbo.DEPARTMENTS D ON D.LINK = (case	when DT.Dep is not NULL and DT.Dep <> G.Dep then DT.Dep
										when KT.Dep is not NULL and KT.Dep <> G.Dep then KT.Dep
										when OS.Dep_pass is not NULL and OS.Dep_pass <> G.Dep then OS.Dep_pass
										when OS.Dep_receive is not NULL and OS.Dep_receive <> G.Dep then OS.Dep_receive
										else isnull((SELECT top 1 GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA, dbo.S_OBJECTS SO WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT = SO.LINK and (SO.CODE = 'NOTICE_LINK_DEP_RECEIVER' or SO.CODE = 'NOTICE_LINK_DEP_SENDER') AND GPDA.DEPARTMENT <> G.Dep), NULL) end)
	left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
	left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
	LEFT JOIN @filter_kbk F on KBK.Code = F.kbk
	WHERE G.DATE_PROV BETWEEN @dBeginDate AND @dCALC_DATE
		AND G.DEP = @iThisDep
		AND (F.kbk IS NOT NULL OR isnull(@nabor_filter, '') = '')
		AND (TMP.TYPE_KBK = 0 OR (TMP.TYPE_KBK & KBK.[TYPE]) / KBK.[TYPE] = 1)
		AND not exists(select top 1 *
				from @temp_nastr_xor xor
				where xor.link = tmp.link
					and xor.link_dt = dt.account and xor.link_kt = kt.account
					and (CHARINDEX(RTRIM(DTS.Code), xor.dt_ekr) > 0
						or RTRIM(isnull(DTS.Code,'')) like RTRIM(xor.dt_ekr) + '%') 
					and (RTRIM(isnull(KTS.Code,'
			')) like RTRIM(xor.kt_ekr) + '%' or CHARINDEX(RTRIM(KTS.Code),xor.kt_ekr) > 0)) -- исключаем
			
----------------- остатки ------------------------------
while exists(select top 1 * from @temp_nastr_rest)
begin
	select top 1 @LC = Link_Col from @temp_nastr_rest

	set @bid = 'calc_col_' + LTRIM(RTRIM(STR(@LC)))

	insert dbo.buffer(ID, Link)
	select @bid, link_account
	from @temp_nastr_rest
	where link_col = @LC

	-- остаток на конец периода
	insert into @tTempRes
	select	DEP_NAME = isnull(D.FULL_NAME, 'корреспондент_не_указан'), -- Наименование контрагента
			PPP = case when R.Mask_KBK like '%АДМ%' then isnull(VED.CODE, '') else '' end, -- ППП
			--OKATO = case when R.Mask_KBK like '%ОКТМО%' then isnull(replace(D.OKATO,' ',''), '') else '' end, -- ОКАТО
			OKATO = case when R.Mask_KBK like '%ОКТМО%' then isnull(replace(D.OKTMO,' ',''), '') else '' end, -- ОКАТО
			EL_BUDG = case when R.Mask_KBK like '%ЭЛЕМЕНТ%' then isnull(BUDG.CODE_EL, '') else '' end, -- Элемент бюджета
			KBK = isnull(replace(K.CODE,'.',''),''), --KBK
			ACC_CODE = isnull(left(replace(SA.CODE,'.',''),6),'') + '000',
			SUMMA_DB = case when R.LINK_COL = @iLinkColDt and (SA.S_PASSIVE = 1 and [sign] = 1 OR SA.S_ACTIVE = 1 and [sign] = 2) then isnull(k_summa - d_summa,'') 
							when R.LINK_COL = @iLinkColDt and (SA.S_PASSIVE = 2 and [sign] = 2 OR SA.S_ACTIVE = 1 and [sign] = 1) then isnull(d_summa - k_summa,'') 
							else 0 end, -- сумма дебет
			
			SUMMA_KR = case when R.LINK_COL <> @iLinkColDt and (SA.S_PASSIVE = 1 and [sign] = 1 OR SA.S_ACTIVE = 1 and [sign] = 2) then isnull(d_summa - k_summa,'') 
							when R.LINK_COL <> @iLinkColDt and (SA.S_PASSIVE = 2 and [sign] = 2 OR SA.S_ACTIVE = 1 and [sign] = 1) then isnull(k_summa - d_summa,'') 
							else 0 end, -- сумма кредит
			korr_acc = '000000000',
			D_ND = case when R.Mask_KBK like '%ДЕН%' then 1 else 0 end-- Признак платежа ,
			--R.Calc_Order
	from dbo.ARestTableByDateAccounts(@dEndDate, @bid) A
	INNER JOIN @temp_nastr_rest R on R.link_account = account and R.Link_Col = @LC and R.[Type] = 3
	LEFT JOIN dbo.KL_KBK K on K.Link = A.KBK and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end) > 0)
	left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	LEFT JOIN dbo.DEPARTMENTS D ON D.LINK = A.DEP
	left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
	left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
	LEFT JOIN @filter_kbk F on K.Code = F.kbk
	where dep_link = @iThisDep
			and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and r1.link = r.link)
		AND (F.kbk IS NOT NULL OR isnull(@nabor_filter, '') = '')
		AND (R.TYPE_KBK = 0 OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		



-- select * from #tTemp
	
	delete @temp_nastr_rest where Link_Col = @LC

	exec dbo.BufferClear @bid	
end


insert into @tTempRes2 (DEP_NAME, PPP, OKATO, EL_BUDG, ACC_CODE, KBK, summa_db, summa_kr, KORR_ACC, D_ND)
select DEP_NAME, PPP, OKATO, EL_BUDG, ACC_CODE, KBK, SUM(summa_db), SUM(summa_kr), KORR_ACC, D_ND
from @tTempRes 
where DEP_NAME <> 'корреспондент_не_указан'
group by DEP_NAME, PPP, OKATO, EL_BUDG, ACC_CODE, KBK, KORR_ACC, D_ND
union
select DEP_NAME, PPP, OKATO, EL_BUDG, ACC_CODE, KBK, SUM(summa_db), SUM(summa_kr), KORR_ACC, D_ND
from @tTempRes 
where DEP_NAME = 'корреспондент_не_указан'
group by DEP_NAME, PPP, OKATO, EL_BUDG, ACC_CODE, KBK, KORR_ACC, D_ND



if @table in (1,3) 
	SELECT 
--	[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'00000000000',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
--	[CODE] = LEFT(RTRIM(PPP)+'   ',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '  ',2) + LEFT(rtrim(KBK) + '                 ',17) + LEFT(RTRIM(KORR_ACC) + '         ',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL1] = DEP_NAME, -- Наименование контрагента
	[COL2] = PPP, -- ППП
	[COL3] = OKATO, -- ОКАТО
	[COL4] = EL_BUDG, -- Элемент бюджета
	[COL5] = substring(rtrim(KBK),1,3), -- АДМ
	[COL6] = substring(rtrim(KBK),4,14), -- КБК
	[COL7] = SUMMA_DB, -- сумма дебет
	[COL8] = SUMMA_KR, -- сумма кредит
	[COL9] = KORR_ACC, -- Код корреспондирующего счёта бюджетного учета
	[COL10] = cast (isnull(d_nd,'') as varchar), -- Признак платежа
	[COL11]= LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL12]= RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8)
	FROM @tTempRes2
	where  summa_db <> 0 or summa_kr <> 0
	ORDER BY NUM_PP

else 
	SELECT 
	--[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'00000000000',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	--[CODE] = LEFT(RTRIM(PPP)+'   ',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '  ',2) + LEFT(rtrim(KBK) + '                 ',17) + LEFT(RTRIM(KORR_ACC) + '         ',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL1] = DEP_NAME, -- Наименование контрагента
	[COL2] = PPP, -- ППП
	[COL3] = OKATO, -- ОКАТО
	[COL4] = EL_BUDG, -- Элемент бюджета
	[COL5] = substring(rtrim(KBK),1,3), -- АДМ
	[COL6] = substring(rtrim(KBK),4,4), -- РзПр
	[COL7] = substring(rtrim(KBK),8,7), -- ЦСР
	[COL8] = substring(rtrim(KBK),15,3),-- ВР
	[COL9] = SUMMA_DB, -- сумма дебет
	[COL10] = SUMMA_KR, -- сумма кредит
	[COL11] = KORR_ACC, -- Код корреспондирующего счёта бюджетного учета
	[COL12] = cast (isnull(d_nd,'') as varchar), -- Признак платежа
	[COL13] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL14] = RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8)
	FROM @tTempRes2
	where  summa_db <> 0 or summa_kr <> 0
	ORDER BY NUM_PP




GO


GRANT EXECUTE ON dbo.[RB_CALC_0503125G_NEW] TO PUBLIC

GO



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

GO


CREATE  PROCEDURE dbo.SD_VAC_CHILD_FILL
/*Расчет по уходу за ребенком*/
@varKSnMonth int,
@varKSnYear int
AS

DECLARE @varKSDateS DATETIME
SET @varKSDateS = dbo.ConvertDMY2Date(1,@varKSnMonth,@varKSnYear)

declare @DEP_LINK int
exec dbo.xd_whats_zb @DEP_LINK output

DECLARE @DATE_BEG DATETIME, @DATE_END DATETIME
SET @DATE_BEG = dbo.DateBeginOfMonth(@varKSDateS)
SET @DATE_END = dbo.DateEndOfMonth(@varKSDateS)

CREATE TABLE #EMPL (LINK INT, LINK_EMPL INT, SYST_PAY TINYINT, SUBDIV_NAME VARCHAR(254), POST_NAME VARCHAR(254), LINK_SFIN INT)	
INSERT INTO #EMPL (LINK, LINK_EMPL, SYST_PAY, SUBDIV_NAME, POST_NAME, LINK_SFIN)	
SELECT C.LINK, C.LINK_EMPL, E.SYST_PAY, SUBDIV_NAME, POST_NAME, E.LINK_KBK
FROM 
	dbo.VAC_CHILD C
	INNER JOIN dbo.KU_EMPL_PLACING E ON C.LINK_EMPL = E.LINK
WHERE	
	C.DATE1<=@DATE_END 
	and C.DATE2>=@DATE_BEG
	AND E.DEP_LINK = @DEP_LINK	


CREATE TABLE #OLD (LINK INT, LINK_EMPL INT, LINK_SFIN INT, LINK_PAYS INT, SUMMA_OLD NUMERIC(18,2))	
INSERT INTO #OLD (LINK, LINK_EMPL, LINK_SFIN, LINK_PAYS, SUMMA_OLD)	
SELECT 
C.LINK, C.LINK_EMPL, SD.LINK_SFIN, C.LINK_PAYS, SUM(SD.SUMMA)
FROM 
	dbo.VAC_CHILD C
	INNER JOIN dbo.SDOC_ACHILD_TABLE SD ON C.LINK = SD.LINK_VAC_CHILD	
	INNER JOIN dbo.SDOC D ON D.LINK = SD.LINK_UP
	INNER JOIN #EMPL E ON C.LINK = E.LINK
WHERE
	D.[DATE] BETWEEN @DATE_BEG AND @DATE_END
	AND 
	D.LINK_DEP = @DEP_LINK
	AND
	D.FLAG_JC = 1
GROUP BY
	C.LINK, C.LINK_EMPL, SD.LINK_SFIN, C.LINK_PAYS

CREATE TABLE #RES (
	[LINK] int,
	[LINK_EMPL] int,
	[TAB_NUM] varchar(10),
	[NAME_EMPL] varchar(100),
	[COMMENT] varchar(254),
	[DATE_R] datetime,
	[DATE1] datetime,
	[DATE2] datetime,
	[SUMMA] numeric(18, 2),
	[LINK_PAYS] int,
	[CODE_PAYS] varchar(10),
	[NAME_PAYS] varchar(60),
	[TYP_CALC] int,
	[DEP_LINK] int,
	[name_dep] varchar(254),
	[CNT] int,
	[LINK_R] int,
	[LINK_KBK] int,
	[CODE_KBK] varchar(30),
	[INSTRUCT] tinyint,
	[date1_m] datetime,
	[date2_m] datetime,
	[SYST_PAY] tinyint,
	[SUMMA_OLD] numeric(18, 2),
	SUBDIV_NAME VARCHAR(254), 
	POST_NAME VARCHAR(254))

INSERT INTO #RES (LINK,LINK_EMPL,TAB_NUM,NAME_EMPL,COMMENT,DATE_R,DATE1,DATE2,SUMMA,LINK_PAYS,CODE_PAYS,NAME_PAYS,TYP_CALC,DEP_LINK,
	name_dep,CNT,LINK_R,LINK_KBK,CODE_KBK,INSTRUCT,date1_m,date2_m,SYST_PAY,SUMMA_OLD,SUBDIV_NAME,POST_NAME)
SELECT 
	DV.LINK,DV.LINK_EMPL,DV.TAB_NUM,DV.NAME_EMPL,DV.COMMENT,DV.DATE_R,DV.DATE1,DV.DATE2,DV.SUMMA,DV.LINK_PAYS,DV.CODE_PAYS,DV.NAME_PAYS,
	DV.TYP_CALC,DV.DEP_LINK,DV.name_dep,DV.CNT,DV.LINK_R,
	ISNULL(DV.LINK_KBK,E.LINK_SFIN),ISNULL(DV.CODE_KBK,F.CODE),
	DV.INSTRUCT,
	[date1_m] = (case when DV.DATE1<=@DATE_BEG then @DATE_BEG else  DV.DATE1 end),
	[date2_m] = (case when DV.DATE2>=@DATE_END then @DATE_END else  DV.DATE2 end),
	E.SYST_PAY, 
	ISNULL(O.SUMMA_OLD,0),
	SUBDIV_NAME,
	POST_NAME
FROM 
	dbo.DICTIONARY_VAC_CHILD DV
	INNER JOIN #EMPL E ON E.LINK = DV.LINK
	INNER JOIN dbo.SAL_SFIN F ON F.LINK = E.LINK_SFIN
	LEFT JOIN #OLD O ON O.LINK = DV.LINK
WHERE 
	DV.DATE1<=@DATE_END
	and DV.DATE2>=@DATE_BEG 
	AND DV.DEP_LINK = @DEP_LINK

SELECT *,

		CASE TYP_CALC 
			WHEN 1 THEN 0
			WHEN 2 THEN (CASE WHEN SYST_PAY = 1 THEN dbo.NORM_DAY_DH(t1.link_empl,t1.date1_m, t1.Date2_m) ELSE 0 END)
			WHEN 3 THEN DAY(date2_m)
		END as DAYS, 
		 
		CASE TYP_CALC 
			WHEN 1 THEN 0
			WHEN 2 THEN (CASE WHEN SYST_PAY = 2 THEN dbo.NORM_HOUR_DH(t1.link_empl,t1.date1_m, t1.Date2_m) ELSE 0 END)
			WHEN 3 THEN 0
		END as HOURS,

		CASE TYP_CALC 
			WHEN 1 THEN 0
			WHEN 2 THEN (CASE WHEN SYST_PAY = 1 THEN dbo.norm_days(t1.link_empl,@varKSnMonth,@varKSnYear) ELSE 0 END)
			WHEN 3 THEN DAY(dbo.DateEndOfMonth(date2_m))
		END as NORM_DAYS,

		CASE TYP_CALC 
			WHEN 1 THEN 0
			WHEN 2 THEN (CASE WHEN SYST_PAY = 2 THEN dbo.norm_hours(t1.link_empl,@varKSnMonth,@varKSnYear) ELSE 0 END)
			WHEN 3 THEN 0
		END as NORM_HOURS,

		NAME_CALC = CASE TYP_CALC WHEN 1 THEN 'без учёта дней' WHEN 2 THEN 'пропорц.раб.вр.' ELSE 'пропорц.календ.дн.' END
FROM
	#RES T1

DROP TABLE #EMPL
DROP TABLE #RES






GO


GRANT EXECUTE ON dbo.[SD_VAC_CHILD_FILL] TO PUBLIC

GO



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

GO

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

CREATE      PROCEDURE [dbo].SALARY_SAVE_DICTIONARY_MROT
	@varKSparLINK		int	OUTPUT,
	@varKSparPERIOD		datetime,
	@varKSparMROT1		numeric(15,2) = 0,
	@varKSparMROT2		numeric(15,2) = 0,
	@varKSparTARIF		numeric(15,2) = 0,
	@varKSparKOEF		numeric(4,2) = 1,
	@varKSparKOEF_BL	numeric(4,2) = 1,	
	@varKSparREF_DEP INT,
	@varKSparRESERV TINYINT = 0
AS
DECLARE @varKSERROR	tinyint,
		@varKStrancount	int

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


	IF @varKSparPERIOD IS NULL 
	BEGIN
		ROLLBACK
		RETURN 5
	END

	Set @varKSparKOEF_BL = (case when coalesce(@varKSparKOEF_BL,1) = 1 then @varKSparKOEF else @varKSparKOEF_BL end)

	
	EXECUTE @varKSERROR = X_UPDATE_MINROT @varKSparLINK OUTPUT,@varKSparPERIOD,@varKSparMROT1,@varKSparMROT2,
								@varKSparTARIF,@varKSparKOEF, @varKSparKOEF_BL,@varKSparRESERV

	IF @varKSERROR <> 0
	BEGIN
		ROLLBACK
		RETURN @varKSERROR
	END
	
	update MINROT
	set REF_DEP = @varKSparREF_DEP where LINK = @varKSparLINK

	
	DELETE FROM MINROT_DICTION WHERE LINK_MINROT = @varKSparLINK
	DELETE FROM MINROT_PAYS  WHERE LINK_MINROT = @varKSparLINK

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0



GO


GRANT EXECUTE ON dbo.[SALARY_SAVE_DICTIONARY_MROT] TO PUBLIC

GO



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

GO

/*
    © Кейсистемс (Keysystems), 2007
    Процедура формирования строк и значений формы 0503125
*/

CREATE PROCEDURE dbo.RB_CALC_0503725G_NEW @iLSF int
AS

declare @dBeginDate datetime,
		@dEndDate datetime,
		@dEndDate_pl datetime,
		@dCALC_DATE datetime,
		@iThisDep int,
		@nPeriod_Type tinyint,
		@cStrSql varchar(8000)
----------		
DECLARE @LF	int, 
		@LT	int,
		@LC	int,
		@orderCol int,
		@iLinkCalcForm int,
		@iLinkColDt int,
		@bid varchar(100),
		@nabor_filter varchar(1000)
---------------
				
declare @tTempRes table(DEP_NAME varchar(254),
						DEP_CODE varchar(10), 
						ACC_CODE varchar(9), 
						summa_db numeric(20,4), 
						summa_kr numeric(20,4), 
						korr_acc varchar(9), 
						D_ND tinyint) 

declare @tTempRes2 table(DEP_NAME varchar(254),
						 DEP_CODE varchar(10), 
						 ACC_CODE varchar(9), 
						 summa_db numeric(20,4), 
						 summa_kr numeric(20,4), 
						 korr_acc varchar(9), 
						 D_ND tinyint,
						 NUM_PP int IDENTITY(1,1)) 
declare @filter_kbk table (kbk varchar(30))

-- определяем период (если в январе формируем, то берём весь предыдущий год не включая 31 декабря)
select @dEndDate = Begin_Date, @nPeriod_Type = period_type from dbo.report_saved_forms where link_saved_form = @iLSF

select @dBeginDate = dbo.DateBeginOfYear(@dEndDate)


select @nabor_filter = REPLACE(dbo.rn_get_atr_value(@iLSF,'REPORTS_FILTER_KBK'), 'Не отобрано', '')

insert @filter_kbk (kbk)   
Select RTRIM(code) FROM rn_get_filter(@iLSF,'REPORTS_FILTER_KBK')


---------------------------------------****************************
declare @temp_nastr table (link int, [Link_Col] int NOT NULL, 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL, link_dt int, link_kt int, dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint)
declare @temp_nastr_xor table (	link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_dt int, link_kt int, dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, dt_kt tinyint)
declare @temp_nastr_rest table (	link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000),
	[type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint)
declare @temp_nastr_rest_xor table (link int, [Link_Col] int NOT NULL , 
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000),
	[type] tinyint, type_kbk tinyint, dt_kt tinyint)


-------- ЧИТАЕМ ДАННЫЕ ОТЧЕТА
select @LF = RSF.Link_Form, 
		@iThisDep 	= Link_Organization, 
		@dEndDate	= Begin_Date + 1,
		@dCALC_DATE	= Begin_Date, 
		@dBeginDate	= dbo.DateBeginOfYear(Begin_Date),
		@nPeriod_Type = period_type
from report_saved_forms RSF  where RSF.link_saved_form = @iLSF

SET @iLinkCalcForm = dbo.RK_GET_NASTR_CALC_REPORT (@iLSF, 1)
--select  @iLinkCalcForm
if @iLinkCalcForm is null 
	RETURN 0

set @iLinkColDt = (select RC.LINK_COL
					from dbo.REPORT_COLOUMNS RC
					inner join dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.Link_Form = @LF and RT.orders = 1 and RC.Export_Order = 3)
---------------------------------------------------------------------
----- ПОЛУЧАЕМ ВЫБОРКУ ИЗ ТАБЛИЦЫ НАСТРОЕК ----
insert @temp_nastr 
select C.link, C.Link_Col, Calc_Order, [Sign], DT.link , KT.link, dt_ekr, kt_ekr, [type], type_kbk, mask_kbk, dt_kt
from dbo.REPORT_CALC C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = 1 and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE C.LINK_UP = @iLinkCalcForm
	AND [sign] in (1,2) and CR.[type] = 1 
	AND (rtrim (CR.DT_Mask) = '' OR CR.DT_Mask = '%' OR rtrim (CR.DT_Mask) <> '' AND DT.LINK IS NOT NULL)
	AND (rtrim (CR.KT_Mask) = '' OR CR.KT_Mask = '%' OR rtrim (CR.KT_Mask) <> '' AND KT.LINK IS NOT NULL)


-- проводки, которые мы исключаем --
insert @temp_nastr_xor 
select C.link, C.Link_Col, Calc_Order, [Sign], DT.link , KT.link, dt_ekr, kt_ekr, [type], type_kbk, dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = 1 and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
where C.LINK_UP = @iLinkCalcForm
	AND [sign] = 3 and CR.[type] = 1 


--- Выборка счетов для расчета остатков ---
insert @temp_nastr_rest 
select C.link, C.Link_Col, Calc_Order, [Sign],
	case
		when DT.link is NULL then KT.link
		else DT.link
	end,
	case
		when DT.link is NULL then kt_ekr
		else dt_ekr
	end, [type],
	type_kbk,
	mask_kbk,
	dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = 1 and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE C.LINK_UP = @iLinkCalcForm 
	AND CR.[type] in (2,3) and [sign] in (1,2) 
	AND (rtrim (CR.DT_Mask) = '' OR rtrim (CR.DT_Mask) <> '' AND DT.LINK IS NOT NULL)
	AND (rtrim (CR.KT_Mask) = '' OR rtrim (CR.KT_Mask) <> '' AND KT.LINK IS NOT NULL)

/*
select S1.CODE, * from @temp_nastr_rest T, S_ACCOUNTS S1 
WHERE S1.LINK = T.LINK_account
*/

--- Счета, которые исключаем для расчета остатков ---
insert @temp_nastr_rest_xor
select C.link, C.Link_Col, Calc_Order, [Sign],
	case
		when DT.link is NULL then KT.link
		else DT.link
	end,
	case
		when DT.link is NULL then kt_ekr
		else dt_ekr
	end,
	[type],
	type_kbk,
	dt_kt
from dbo.report_calc C 
INNER JOIN  dbo.REPORT_COLOUMNS RC on C.Link_Col = RC.Link_Col
INNER JOIN  dbo.REPORT_TABLES RT on RC.Link_Table = RT.Link_Table and RT.orders = 1 and RT.Link_Form = @LF
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE  C.LINK_UP = @iLinkCalcForm 
	AND CR.[type] in (2,3) and [sign] = 3 
	AND (DT.LINK IS NOT NULL
		OR KT.LINK IS NOT NULL)

---------------------------------------****************
---- Обороты

	insert into @tTempRes
	select	DEP_NAME = isnull(D.FULL_NAME, 'корреспондент_не_указан'), -- Наименование контрагента
			DEP_CODE = isnull(D.CODE, ''), 
			ACC_CODE = case TMP.dt_kt when 0 then isnull(left(replace(SAD.CODE,'.',''),6),'') + isnull(DTS.CODE,'') else isnull(left(replace(SAK.CODE,'.',''),6),'') + isnull(KTS.CODE,'')  end,
			SUMMA_DB = case TMP.LINK_COL when @iLinkColDt then isnull(G2.SUMMA,'') else 0 end, -- сумма дебет
			SUMMA_KR = case TMP.LINK_COL when @iLinkColDt then 0 else isnull(G2.SUMMA,'') end, -- сумма кредит
			korr_acc = case TMP.dt_kt when 0 then isnull(left(replace(SAK.CODE,'.',''),6),'')  + isnull(KTS.CODE,'') else isnull(left(replace(SAD.CODE,'.',''),6),'') + isnull(DTS.CODE,'')  end, -- корреспондирующий счет
			D_ND = case when TMP.Mask_KBK like '%ДЕН%' then 1 else 0 end-- Признак платежа

	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)


	LEFT JOIN dbo.G_PROV_AP DT ON (DT.LINK_UP = G2.LINK AND DT.DB_KR = 0)
	LEFT JOIN dbo.G_PROV_AP KT ON (KT.LINK_UP = G2.LINK AND KT.DB_KR = 1)

	LEFT JOIN dbo.KOSGU DTS ON (DTS.Link = DT.SGU)
	LEFT JOIN dbo.KOSGU KTS ON (KTS.Link = KT.SGU)
	
	INNER JOIN @TEMP_NASTR TMP ON (TMP.LINK_DT = DT.ACCOUNT OR TMP.LINK_DT IS NULL)
			AND (TMP.LINK_KT = KT.ACCOUNT OR TMP.LINK_KT IS NULL)
		AND (dbo.RO_LIKE_LIST(DTS.Code, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '')
		AND (dbo.RO_LIKE_LIST(KTS.Code, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '')

	LEFT JOIN dbo.S_ACCOUNTS SAD ON SAD.LINK = DT.ACCOUNT

	LEFT JOIN dbo.S_ACCOUNTS SAK ON SAK.LINK = KT.ACCOUNT 

	LEFT JOIN dbo.KL_KBK KBK ON (TMP.dt_kt = 0 AND KBK.LINK = DT.KBK OR TMP.DT_KT = 1 AND KBK.LINK = KT.KBK)
	left join dbo.G_PROV_OS1 OS on OS.LINK_OS1 = G.LINK
	LEFT JOIN dbo.DEPARTMENTS D ON D.LINK = (case	when DT.Dep is not NULL and DT.Dep <> G.Dep then DT.Dep
										when KT.Dep is not NULL and KT.Dep <> G.Dep then KT.Dep
										when OS.Dep_pass is not NULL and OS.Dep_pass <> G.Dep then OS.Dep_pass
										when OS.Dep_receive is not NULL and OS.Dep_receive <> G.Dep then OS.Dep_receive
										else isnull((SELECT GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA, dbo.S_OBJECTS SO WHERE GPDA.DOC_LINK = G.LINK AND GPDA.OBJECT = SO.LINK and SO.CODE = 'NOTICE_LINK_DEP_RECEIVER'), NULL) end)
	left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
	left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
	LEFT JOIN @filter_kbk F on KBK.Code = F.kbk
	WHERE G.DATE_PROV BETWEEN @dBeginDate AND @dCALC_DATE
		AND G.DEP = @iThisDep
		AND (F.kbk IS NOT NULL OR isnull(@nabor_filter, '') = '')
		AND (TMP.TYPE_KBK = 0 OR (TMP.TYPE_KBK & KBK.[TYPE]) / KBK.[TYPE] = 1)
		AND not exists(select top 1 *
				from @temp_nastr_xor xor
				where xor.link = tmp.link
					and xor.link_dt = dt.account and xor.link_kt = kt.account
					and (CHARINDEX(RTRIM(DTS.Code), xor.dt_ekr) > 0
						or RTRIM(isnull(DTS.Code,'')) like RTRIM(xor.dt_ekr) + '%') 
					and (RTRIM(isnull(KTS.Code,'
			')) like RTRIM(xor.kt_ekr) + '%' or CHARINDEX(RTRIM(KTS.Code),xor.kt_ekr) > 0)) -- исключаем
			
			
----------------- остатки ------------------------------
while exists(select top 1 * from @temp_nastr_rest)
begin
	select top 1 @LC = Link_Col from @temp_nastr_rest

	set @bid = 'calc_col_' + LTRIM(RTRIM(STR(@LC)))

	insert dbo.buffer(ID, Link)
	select @bid, link_account
	from @temp_nastr_rest
	where link_col = @LC

	-- остаток на конец периода
	insert into @tTempRes
	select	DEP_NAME = isnull(D.FULL_NAME, 'корреспондент_не_указан'), -- Наименование контрагента
			DEP_CODE = isnull(D.CODE, ''), 
			ACC_CODE = isnull(left(replace(SA.CODE,'.',''),6),'') + '000',
			SUMMA_DB = case when R.LINK_COL = @iLinkColDt and (SA.S_PASSIVE = 1 and [sign] = 1 OR SA.S_ACTIVE = 1 and [sign] = 2) then isnull(k_summa - d_summa,'') 
							when R.LINK_COL = @iLinkColDt and (SA.S_PASSIVE = 2 and [sign] = 2 OR SA.S_ACTIVE = 1 and [sign] = 1) then isnull(d_summa - k_summa,'') 
							else 0 end, -- сумма дебет
			
			SUMMA_KR = case when R.LINK_COL <> @iLinkColDt and (SA.S_PASSIVE = 1 and [sign] = 1 OR SA.S_ACTIVE = 1 and [sign] = 2) then isnull(d_summa - k_summa,'') 
							when R.LINK_COL <> @iLinkColDt and (SA.S_PASSIVE = 2 and [sign] = 2 OR SA.S_ACTIVE = 1 and [sign] = 1) then isnull(k_summa - d_summa,'') 
							else 0 end, -- сумма кредит
			korr_acc = '000000000',
			D_ND = case when R.Mask_KBK like '%ДЕН%' then 1 else 0 end-- Признак платежа ,
			--R.Calc_Order
	from dbo.ARestTableByDateAccounts(@dEndDate, @bid) A
	INNER JOIN @temp_nastr_rest R on R.link_account = account and R.Link_Col = @LC and R.[Type] = 3
	LEFT JOIN dbo.KL_KBK K on K.Link = A.KBK and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end) > 0)
	left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	LEFT JOIN dbo.DEPARTMENTS D ON D.LINK = A.DEP
	left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
	left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
	LEFT JOIN @filter_kbk F on K.Code = F.kbk
	where dep_link = @iThisDep
			and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and r1.link = r.link)
		AND (F.kbk IS NOT NULL OR isnull(@nabor_filter, '') = '')
		AND (R.TYPE_KBK = 0 OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		



-- select * from #tTemp
	
	delete @temp_nastr_rest where Link_Col = @LC

	exec dbo.BufferClear @bid	
end


insert into @tTempRes2 (DEP_NAME, DEP_CODE, ACC_CODE, summa_db, summa_kr, KORR_ACC, D_ND)
select DEP_NAME, DEP_CODE, ACC_CODE, SUM(summa_db), SUM(summa_kr), KORR_ACC, D_ND
from @tTempRes 
where DEP_NAME <> 'корреспондент_не_указан'
group by DEP_NAME, DEP_CODE, ACC_CODE, KORR_ACC, D_ND
union
select DEP_NAME,DEP_CODE, ACC_CODE, SUM(summa_db), SUM(summa_kr), KORR_ACC, D_ND
from @tTempRes 
where DEP_NAME = 'корреспондент_не_указан'
group by DEP_NAME, DEP_CODE, ACC_CODE, KORR_ACC, D_ND



	SELECT 
	--[CODE] = LEFT(RTRIM(PPP)+'000',3) + LEFT(RTRIM(OKATO)+'00000000000',11) + LEFT(RTRIM(EL_BUDG) + '00',2) + LEFT(rtrim(KBK) + '00000000000000000',17) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	--[CODE] = LEFT(RTRIM(PPP)+'   ',3) + LEFT(RTRIM(OKATO)+'           ',11) + LEFT(RTRIM(EL_BUDG) + '  ',2) + LEFT(rtrim(KBK) + '                 ',17) + LEFT(RTRIM(KORR_ACC) + '         ',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[CODE] = LEFT(RTRIM(DEP_CODE)+'000000000',8) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8), -- Код строки.
	[COL1] = DEP_NAME, -- Наименование контрагента
	[COL2] = DEP_CODE, -- 
	[COL3] = SUMMA_DB, -- сумма дебет
	[COL4] = SUMMA_KR, -- сумма кредит
	[COL11] = KORR_ACC, -- Код корреспондирующего счёта бюджетного учета
	[COL12] = cast (isnull(d_nd,'') as varchar), -- Признак платежа
	[COL13] = LEFT(RTRIM(DEP_CODE)+'00000000',8) + LEFT(RTRIM(KORR_ACC) + '000000000',9) + RIGHT('00000000' + LTRIM(CAST(ISNULL(NUM_PP,0) as VARCHAR(8))),8) -- Код строки.
	FROM @tTempRes2
	where  summa_db <> 0 or summa_kr <> 0
	ORDER BY NUM_PP




GO


GRANT EXECUTE ON dbo.[RB_CALC_0503725G_NEW] TO PUBLIC

GO


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

GO



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


CREATE     PROCEDURE [dbo].X_UPDATE_MINROT
	@varKSintLINK	int	OUTPUT,
	@varKSdatPeriod	datetime,
	@varKSnumMROT1 numeric(15,2) = 0,
	@varKSnumMROT2 numeric(15,2) = 0,
	@varKSnumTarif numeric(15,2) = 0,
	@varKSnumKoef numeric(4,2) = 1,
	@varKSnumKoef_bl numeric(4,2) = 1,
	@varKSReserv tinyint = 0
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 MINROT WITH (ROWLOCK) (PERIOD,MROT1,MROT2,TARIF,KOEF, KOEF_BL,RESERV)
		VALUES (@varKSdatPeriod,@varKSnumMROT1,@varKSnumMROT2,@varKSnumTarif, @varKSnumKoef, @varKSnumKoef_bl, @varKSReserv)
		SELECT @varKSSQLError = @@ERROR, @varKSintLINK = @@IDENTITY
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	ELSE
	BEGIN
		UPDATE MINROT WITH (ROWLOCK) 
		SET PERIOD =@varKSdatPeriod, MROT1 = @varKSnumMROT1, MROT2 = @varKSnumMROT2, TARIF = @varKSnumTarif, KOEF = @varKSnumKoef, KOEF_BL = @varKSnumKoef_bl, RESERV = @varKSReserv
		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_MINROT] TO PUBLIC

GO


GO

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


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

CREATE PROCEDURE BB_EXPORT_SPR 
		@cBuffId	varchar(30) = '',
		@cObjCode	varchar(30) = ''

AS 
declare @iSum int
set @iSum = 0
-- Таблица 1
-- Код справочника
select  LINK = 0,
	LINK_UP = 0,
	KOD_SPR = case @cObjCode when 'BI_DICTION_INCOME'  	then 'DICTIONARY_INCOME'
				 when 'BI_DICTION_EXP' 	   	then 'DICTIONARY_EXPEND'
				 when 'BI_DICTION_IVF'	   	then 'DICTIONARY_SOURCE'
				 when 'BI_DICTION_KBK2'		then 'DICTIONARY_KBK_INC'
				 when 'BI_DICTION_KBK1'   	then 'DICTIONARY_KBK_EXP'
				 when 'BI_DICTION_KBK4'   	then 'DICTIONARY_KBK_SOURCE'
				 when 'BD_DOP_CLASSIF' 	   	then 'DICTIONARY_ADD_BK'
				 when 'BI_DICTION_DIV' 	   	then 'DICTIONARY_DIVISION'
				 when 'DICTIONARY_TARGET_PROG' 	then 'DICTIONARY_PROGRAM'
				 when 'BI_DICTION_CSR' 	  	then 'DICTIONARY_TARGET_ITEM'
				 when 'DICTIONARY_ITEM'   	then 'DICTIONARY_ITEM'
				 when 'DICTIONARY_KOSGU'   	then 'DICTIONARY_ITEM'
				 when 'DICTIONARY_BANK'   	then 'DICTIONARY_BANK'
				 when 'DICTIONARY_DEPARTMENT'	then 'DICTIONARY_CORR'
				 when 'DICTIONARY_TREASURY'	then 'DICTIONARY_CORR'
				 when 'DICTIONARY_ACCOUNTS'	then 'DICTIONARY_ACCOUNT'
				 when 'DICTIONARY_K_ACCOUNTS'	then 'DICTIONARY_ACCOUNT'
				 when 'BB_DICTION_PROG'	then 'DICTIONARY_PROGRAM'
				 
		 end


-- Таблица 2
-- в зависимости от справочника
IF @cObjCode = 'BI_DICTION_INCOME'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME] = LNAME,
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = '',
		VID    = '',
		[CONTROL]    = '',
		PAYCINCOME    = '',
		INC_RCP    = '',
		EXP_PAY    = '',
		EXP_RCP    = ''
	from dbo.KL_KD
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BI_DICTION_EXP'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME] = [LNAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = '',
		VID    = '',
		[CONTROL]    = '',
		PAYCINCOME    = '',
		INC_RCP    = '',
		EXP_PAY    = '',
		EXP_RCP    = ''  
	from dbo.KL_EXPEND
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BI_DICTION_IVNESHF'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = '',
		VID    = '',
		[CONTROL]    = '',
		PAYCINCOME    = '',
		INC_RCP    = '',
		EXP_PAY    = '',
		EXP_RCP    = ''  
	from dbo.BI_DICTION_IVNESHF
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BI_DICTION_IVF'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = '',
		VID    = '',
		[CONTROL]    = '',
		PAYCINCOME    = '',
		INC_RCP    = '',
		EXP_PAY    = '',
		EXP_RCP    = ''  
	from dbo.BI_DICTION_IVF
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BB_DICTION_PROG'
begin
	select 	LINK,
			LINK_UP = LINK,
			CODE, 
			[SNAME] = cast([NAME] as varchar(45)),
			[NAME] = [LNAME],
			DATE_BEGIN = cast(null as datetime),  
			DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = '' ,
		VID    = '',
		[CONTROL]    = '',
		PAYCINCOME    = '',
		INC_RCP    = '',
		EXP_PAY    = '',
		EXP_RCP    = ''
	from dbo.KL_PROG
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end IF @cObjCode = 'BD_DOP_CLASSIF'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime) ,
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = '' ,
		VID    = '',
		[CONTROL]    = '',
		PAYCINCOME    = '',
		INC_RCP    = '',
		EXP_PAY    = '',
		EXP_RCP    = ''
	from dbo.DOP_CLASSIF
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BI_DICTION_DIV'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME] = [LNAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = '' ,
		VID    = '',
		[CONTROL]    = '',
		PAYCINCOME    = '',
		INC_RCP    = '',
		EXP_PAY    = '',
		EXP_RCP    = ''  
	from dbo.KL_DIVISION
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'DICTIONARY_TARGET_PROG'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = '' ,
		VID    = '',
		[CONTROL]    = '',
		PAYCINCOME    = '',
		INC_RCP    = '',
		EXP_PAY    = '',
		EXP_RCP    = ''  
	from dbo.DICTIONARY_TARGET_PROG
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'BI_DICTION_CSR'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME]  = cast([NAME] as varchar(512)),
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = '' ,
		VID    = '',
		[CONTROL]    = '',
		PAYCINCOME    = '',
		INC_RCP    = '',
		EXP_PAY    = '',
		EXP_RCP    = ''
	from dbo.BI_DICTION_CSR
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'DICTIONARY_ITEM' or @cObjCode = 'DICTIONARY_KOSGU'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE, 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME],
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = '' ,
		VID    = '',
		[CONTROL]    = '',
		PAYCINCOME    = '',
		INC_RCP    = '',
		EXP_PAY    = '',
		EXP_RCP    = ''  
	from dbo.DICTIONARY_ITEM               
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 

IF left(@cObjCode,14) = 'BI_DICTION_KBK'
begin
	select 	LINK,
		LINK_UP = LINK,
		CODE = cast(replace(CODE,'.','') as varchar(20)), 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME] ,
		DATE_BEGIN = cast(null as datetime),  
		DATE_END = cast(null as datetime),
		[LEVEL] = 0,
		BUDGET = '',
		[ORDER] = '',
		PARENT = '',
		VID    = '',
		[CONTROL]    = '',
		PAYCINCOME    = '',
		INC_RCP    = '',
		EXP_PAY    = '',
		EXP_RCP    = ''  
	from dbo.KL_KBK               
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by code
	set @iSum = @@rowcount 
end 

IF @cObjCode = 'DICTIONARY_BANK'
begin
	select 	LINK,
		LINK_UP = LINK,
		BIC = cast(replace(BIK,'.','') as varchar(20)), 
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME] = FNAME,
		KS,
		CITY,
		STATE = 1  
	from dbo.DICTIONARY_BANK                
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by BIK
	set @iSum = @@rowcount 
end 

IF @cObjCode = 'DICTIONARY_DEPARTMENT'
begin
	select 	LINK,
		LINK_UP = LINK,
		INN     = cast(INN_LONG as char(12)),
		CODE_BP = cast(BUDG as char(5)),
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME]  = [FULL_NAME],
		CPPU	= KPP,	
		OKATO	= cast(replace(OKATO,' ','') as char(11)),
		ADRESS  = isnull(rtrim(cast(dbo.GetAddressByKladr(REF_LINK_A) + CASE when HOUSE is null or HOUSE = '' then '' else ' ,' + HOUSE end   as varchar(100))),'')
	from dbo.DICTIONARY_DEPARTMENT D                
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by INN
	set @iSum = @@rowcount 
end 

IF @cObjCode = 'DICTIONARY_TREASURY'
begin
	select 	LINK,
		LINK_UP = LINK,
		INN,
		CODE_BP = '',
		[SNAME] = cast([NAME] as varchar(45)),
		[NAME]  = [FULL_NAME],
		CPPU	= KPP,	
		OKATO	= '',
		ADRESS  = isnull(rtrim(cast(dbo.GetAddressByKladr(REF_LINK_A) + CASE when HOUSE is null or HOUSE = '' then '' else ' ,' + HOUSE end   as varchar(100))),'')
	from dbo.DICTIONARY_TREASURY                
	where LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))
	order by INN
	set @iSum = @@rowcount 
end 

IF @cObjCode = 'DICTIONARY_ACCOUNTS'
begin
	select 	DA.LINK,
		LINK_UP    = DA.LINK,
		CACCOUNT   = DA.CODE,
		ACC_TYPE   = '',
		ACC_VID    = '',
		STATE      = 1,
		CCORR      = D.INN_LONG,
		CORR_BP    = cast(D.BUDG as char(5)),
		CORR_SNAME = cast(D.[NAME] as varchar(20)),
		BANK_BIC   = isnull(B.BIK,''),
		BANK_KS	   = isnull(B.KS,''),	
		BANK_SNAME = isnull(cast(B.[NAME] as varchar(100)),''),
		TOP_ACC    = isnull(TA.CODE,'')
	from dbo.DEPARTMENT_ACCOUNTS DA
	inner join dbo.DICTIONARY_DEPARTMENT D on DA.LINK_UP = D.LINK and D.LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))               
	left join dbo.BANKS B on B.LINK = DA.BANK_LINK and DA.BANK_LINK is not null
	left join dbo.TREASURY_ACCOUNTS TA on DA.TA_LINK = TA.LINK  and DA.TA_LINK is not null
	order by DA.CODE
	set @iSum = @@rowcount 
end 
IF @cObjCode = 'DICTIONARY_K_ACCOUNTS'
begin
	select 	TA.LINK,
		LINK_UP    = TA.LINK,
		CACCOUNT   = TA.CODE,
		ACC_TYPE   = '',
		ACC_VID    = '',
		STATE      = 1,
		CCORR      = T.INN,
		CORR_BP    = '',
		CORR_SNAME = cast(T.[NAME] as varchar(20)),
		BANK_BIC   = isnull(B.BIK,''),
		BANK_KS	   = isnull(B.KS,''),	
		BANK_SNAME = isnull(cast(B.[NAME] as varchar(100)),''),
		TOP_ACC    = ''
	from dbo.TREASURY_ACCOUNTS TA
	inner join dbo.TREASURY T on TA.LINK_UP = T.LINK and T.LINK IN (select LINK from dbo.BufferGetTableByID(@cBuffId))               
	left join dbo.BANKS B on B.LINK = TA.BANK_LINK               
	order by TA.CODE
	set @iSum = @@rowcount 
end 


-- Таблица 3
-- Колличество записей
select  LINK = 0,
	LINK_UP = 0,
	[SUM] = @iSum



GO


GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[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 isnull(GPA1.EKR,GPA1.SGU) = 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 ,30),
				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 isnull(GPA1.EKR,GPA1.SGU) = 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.[SS_SPR_SZP_REP]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SS_SPR_SZP_REP]

GO
CREATE PROC dbo.SS_SPR_SZP_REP 
	@varKSdDate1 DATETIME, /*Начало периода*/
	@varKSdDate2 DATETIME, /*Окончание периода*/
	@Date1 datetime,
	@LINK_EMPL int = NULL, /*Сотрудник*/
	@cNum_SPR varchar(20),	/*Номер справки*/
	@Link_GR_PAY int = null	/*Номер справки*/

	
AS
BEGIN
declare @DEP_LINK int,
		@Date_3mAGO datetime,
		/*@LINK_EMPL INT ,  /*Сотрудник*/ */
		/*@LINK_PERSON INT , /*Физ лицо*/*/
		@varKSnYear INT
exec dbo.xd_whats_zb @DEP_LINK output		
CREATE TABLE #EMPLS(LINK_EMPL INT, PERS_LINK INT, SYST_PAY TINYINT)

if @Date1 = dbo.DateEndOfMonth(@Date1)  
begin
	set @Date_3mAGO = dbo.DateBeginOfMonth(dateadd(MONTH, - 2, @Date1))	
end
else 
begin
	set @Date_3mAGO = dbo.DateBeginOfMonth(dateadd(MONTH, - 3, @Date1))	
end

if isnull(@LINK_EMPL,0) > 0
BEGIN
	INSERT INTO #EMPLS (PERS_LINK, LINK_EMPL, SYST_PAY)
	SELECT PERS_LINK, LINK, SYST_PAY FROM dbo.EMPL A
	WHERE 
		DEP_LINK = @DEP_LINK
		AND EXISTS ( SELECT * FROM dbo.EMPL E WHERE E.LINK = @LINK_EMPL AND E.PERS_LINK = A.PERS_LINK)
	
END

SELECT DISTINCT E.PERS_LINK INTO #PERS FROM #EMPLS E1 INNER JOIN dbo.EMPL E ON E1.LINK_EMPL = E.LINK
	

DECLARE @DEP_NAME VARCHAR(254), @DEP_FN VARCHAR(254), @INN VARCHAR(20), @KPP VARCHAR(20), @OKPO VARCHAR(40),@NOM_PF VARCHAR(20)	
SELECT TOP 1 @DEP_NAME = NAME, @DEP_FN = FULL_NAME, @INN = INN, @KPP = KPP , @OKPO = OKPO, @NOM_PF = PFNUMBER FROM dbo.DEPARTMENTS WHERE LINK = @DEP_LINK

--==========================================================
CREATE TABLE #RES(
	ORD TINYINT,
	LINK_FACE INT,
	[YEAR] int, 
	[MONTH] int,
	MONTH_NAME VARCHAR(20), 
	WORK int,
	NORM int,
	COMMENT varchar(1000), 
	SUMMA NUMERIC(20, 2),
	qprem numeric(20,2)
)

DECLARE @months_ex table (y int, m int, mname varchar(15))

DECLARE @y int
set @y =year(@varKSdDate1)

insert into @months_ex (y,m,mname)
select y,m,mname from DBO.months_ex(@varKSdDate1,@varKSdDate2)

--Список суммы последних квартальных премий
declare @qprem_sum numeric(18,2)

CREATE TABLE #QPREM (month_end int,year_end int, date1 datetime,date2 datetime, summa numeric(18,2) )
insert into #QPREM 
select j.month_end, j.year_end, j.date1, j.date2, sum(j.summa)
from
	#PERS as E
	inner join dbo.empl em  on EM.PERS_LINK = E.PERS_LINK
	inner join 	dbo.S_J_C_Short j on (J.LINK_EMPL = EM.LINK OR EM.PERS_LINK = J.LINK_FACE)
	inner join dbo.PAYS_REF PR on PR.LINK_PAYS = j.LINK_PAYS
where
	em.link = @LINK_EMPL
	and 
	PR.LINK_GROUPS = @Link_GR_PAY
	AND
	(year(j.date1) * 100 + month(j.date1)) between (year(@varKSdDate1) *100 +month(@varKSdDate1)) AND (year(@varKSdDate2) *100 + month(@varKSdDate2))
	AND
	(year(j.date2) * 100 + month(j.date2)) between (year(@varKSdDate1) *100 +month(@varKSdDate1)) AND (year(@varKSdDate2) *100 + month(@varKSdDate2))
	AND
	j.date2 = (select max(date2) from dbo.S_J_C_Short j 
									where e.PERS_LINK = J.LINK_FACE 
									and PR.LINK_PAYS = j.LINK_PAYS
									AND
										(year(j.date1) * 100 + month(j.date1)) between (year(@varKSdDate1) *100 +month(@varKSdDate1)) AND (year(@varKSdDate2) *100 + month(@varKSdDate2))
									AND
										(year(j.date2) * 100 + month(j.date2)) between (year(@varKSdDate1) *100 +month(@varKSdDate1)) AND (year(@varKSdDate2) *100 + month(@varKSdDate2))
									AND
										J.TYP_OPER = 1
									AND
										J.LINK_DEP = @DEP_LINK
									and J.WAY_CALC in (6,7)
									)
	AND
	J.TYP_OPER = 1
	AND
	J.LINK_DEP = @DEP_LINK
	and J.WAY_CALC in (6,7)
group by
	j.month_end,j.year_end, j.date1, j.date2


INSERT INTO #RES
SELECT
	ORD = ROW_NUMBER() OVER (PARTITION BY E.PERS_LINK ORDER BY MM.y, MM.m),
	E.PERS_LINK,
	MM.y, MM.m, MM.mname,
	work = 	MAX(
				(CASE WHEN e.SYST_PAY = 1 THEN 
				dbo.SA_GET_EMPL_WD (e.LINK_EMPL, 0, DEFAULT, dbo.ConvertDMY2Date(1,MM.m,MM.y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MM.m,MM.y)), DEFAULT, 0)
				ELSE 
				dbo.SA_GET_EMPL_WH (e.LINK_EMPL, 0, DEFAULT,  dbo.ConvertDMY2Date(1,MM.m,MM.y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MM.m,MM.y)), DEFAULT, 0)
				END)
				),
	NORM =	MAX(
				(CASE WHEN e.SYST_PAY = 1 THEN 
				dbo.NORM_DAY_DH (e.LINK_EMPL,  dbo.ConvertDMY2Date(1,MM.m,MM.y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MM.m,MM.y)))
				ELSE 
				dbo.NORM_HOUR_DH (e.LINK_EMPL,  dbo.ConvertDMY2Date(1,MM.m,MM.y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MM.m,MM.y)))
				END)
				),
	COMMENT   =  MAX(
					dbo.SA_GET_EMPL_NWD_COMMENT (e.LINK_EMPL,  DEFAULT,  dbo.ConvertDMY2Date(1,MM.m,MM.y), dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,MM.m,MM.y)))
					),
	MAX(ISNULL(SUMMA,0)),
	qprem = CAST( 0 AS numeric(18,2))
	
from 	
	@months_ex MM
	INNER JOIN #EMPLS E ON 1=1
	LEFT JOIN 
		(SELECT 
			PERS_LINK = ISNULL(EM.PERS_LINK,JC.PERS_LINK),
			y, m,
			SUMMA = SUM(JC.SUMMA)
		FROM
			@months_ex M
			INNER JOIN dbo.CALCULATE_JURNAL JC ON M.y = YEAR(JC.PERIOD_BEGIN) AND M.m = MONTH(JC.PERIOD_BEGIN) 
			INNER JOIN dbo.PAYS P ON P.LINK = JC.LINK_PAYS
			INNER JOIN #EMPLS EM ON (EM.LINK_EMPL = JC.LINK_EMPL OR EM.PERS_LINK = JC.PERS_LINK)
		WHERE
			JC.LINK_DEP = @DEP_LINK
			AND EXISTS (SELECT * FROM dbo.PAYS_REF PR WHERE PR.LINK_GROUPS = @Link_GR_PAY AND PR.LINK_PAYS = JC.LINK_PAYS)			
			AND P.[OBJECT] = 1
			AND P.WAY_CALC not in (13, 14, 15, 6, 7) 
		group by
			ISNULL(EM.PERS_LINK,JC.PERS_LINK), y, m
		) T ON MM.y = T.y AND MM.m = T.M AND E.PERS_LINK = T.PERS_LINK
GROUP BY
	E.PERS_LINK, MM.y, MM.m, MM.mname

-- подсчитаем среднюю зп за последних 3 месяца
declare @Count_rows3 int,
		@Count_rows2 int,
		@Count_rows1 int,
		@SUMMA1 NUMERIC(20, 2),
		@SUMMA2 NUMERIC(20, 2),
		@SUMMA3 NUMERIC(20, 2),
		@DF1 int,
		@DF2 int,
		@dF3 int,
		@DR1 int,
		@DR2 int,
		@dR3 int,
		@SR_SUM_3MONTH NUMERIC(20, 2),
		@QPREM_SUMM NUMERIC(20,2),
		@QPREM_MON1 INT,
		@QPREM_MON2 INT,
		@QPREM_MON3 INT,
		@QPREM_S1 NUMERIC(20, 3), 
		@QPREM_S2 NUMERIC(20, 3),
		@QPREM_S3 NUMERIC(20, 3)

if @Date1 = dbo.DateEndOfMonth(@Date1)  
	begin	
		set @Count_rows3 = (select count(*) from #RES)
		set @Count_rows2 = (@Count_rows3 - 1)
		SET @Count_rows1 = (@Count_rows3 - 2)
	end
else 
	begin
		set @Count_rows3 = ((select count(*) from #RES)-1)
 		set @Count_rows2 = (@Count_rows3 - 1)
		SET @Count_rows1 = (@Count_rows3 - 2)
 	end



--1. Количество фактически отработанных дней за 3 месяца 
SET @DF1 = (SELECT WORK FROM #RES WHERE ORD = @Count_rows1)
SET @DF2 = (SELECT WORK FROM #RES WHERE ORD = @Count_rows2)
SET @DF3 = (SELECT WORK FROM #RES WHERE ORD = @Count_rows3)

--2. Количество дней по графику за 3 месяца
SET @DR1 = (SELECT NORM FROM #RES WHERE ORD = @Count_rows1)
SET @DR2 = (SELECT NORM FROM #RES WHERE ORD = @Count_rows2)
SET @DR3 = (SELECT NORM FROM #RES WHERE ORD = @Count_rows3)

-- 3. подсчет последней Квартальной премии с разбивкой по трем последним месяцам 
if @Date1 = dbo.DateEndOfMonth(@Date1)  
	begin	
	   set @QPREM_SUMM = isnull((select Sum(summa) from #QPREM where month(date2) = convert( int ,(select  max([month]) from #RES  where [year] = year(@Date1)and [month] = (select  month(max(date2)) from #QPREM  )))),0)
	   set @QPREM_MON3 = convert( int ,(select  max([month]) from #RES  where [year] = year(@Date1) and [month] = (select  month(max(date2)) from #QPREM  )))
	   set @QPREM_MON2 = @QPREM_MON3 - 1 
	   set @QPREM_MON1 = @QPREM_MON3 - 2 	
	end
else 
	begin
	   set @QPREM_SUMM = isnull((select sum(summa) from #QPREM where month(date2) = convert( int ,(select  max([month]-1) from #RES  where [year] = year(@Date1) and [month] = (select  month(max(date2)) from #QPREM  )))),0)
	   set @QPREM_MON3 = convert( int ,(select  max([month]-1) from #RES  where [year] = year(@Date1) and [month] = (select  month(max(date2)) from #QPREM  )))	
 	   set @QPREM_MON2 = @QPREM_MON3 - 1 
 	   set @QPREM_MON1 = @QPREM_MON3 - 2 
 	end

-- сумма премии на первый месяц
SET @QPREM_S1  = isnull(((@QPREM_SUMM / (@dR1 + @dR2 + @dR3)) * @dR1),0)	
-- сумма премии на второй месяц
SET @QPREM_S2  = isnull(((@QPREM_SUMM / (@dR1 + @dR2 + @dR3)) * @dR2),0)	
-- сумма премии на третий месяц
SET @QPREM_S3  = isnull(((@QPREM_SUMM / (@dR1 + @dR2 + @dR3)) * @dR3),0)	

-- обновление таблицы - к суммам по последним трем месяцам, прибавляется разбитая квартальная премия 
update #RES 
	set SUMMA =  case when SUMMA = 0 then 0 else (SUMMA + @QPREM_S1) end
from #RES where [month] = @QPREM_MON1 and [year] = year(@Date1)
update #RES 
	set SUMMA =  case when SUMMA = 0 then 0 else (SUMMA + @QPREM_S2) end
from #RES where [month] = @QPREM_MON2 and [year] = year(@Date1)
update #RES 
	set SUMMA =  case when SUMMA = 0 then 0 else  (SUMMA + @QPREM_S3) end 
from #RES where [month] = @QPREM_MON3 and [year] = year(@Date1)
---

--4. Сумма за 3 последних месяца		
SET @SUMMA1 = (SELECT SUMMA FROM #RES WHERE ORD = @Count_rows1)
SET @SUMMA2 = (SELECT SUMMA FROM #RES WHERE ORD = @Count_rows2)
SET @SUMMA3 = (SELECT SUMMA FROM #RES WHERE ORD = @Count_rows3)

--  Подсчет средней заработной платы за 3 последних месяца с учетом последней квартальной премии

if  isnull ((@dF1 + @dF2 + @dF3) , 0  ) > 0
	begin
		SET @SR_SUM_3MONTH  = (((@SUMMA1 + @SUMMA2 + @SUMMA3)/ (@dF1 + @dF2 + @dF3)) * (@dR1 + @dR2 + @dR3)) /3	
	end
else 
	begin
		set @SR_SUM_3MONTH = (@SUMMA1 + @SUMMA2 + @SUMMA3) / 3 
	end
---

declare @work_date datetime
set @work_date = (select workdate from user_info)
------------------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------------------
SELECT	RR.*,
	[NUM_SPR]	= @cNum_SPR,
	[fio] 		= KU_EM.FIO,
	[date_beg] 	= KU_EM.DATE_BEGIN,
	[PERS_INN]	= KU_EM.INN,
	[subdiv] 	= KU_EM.SUBDIV_NAME,
	[link] 		= D.LINK,
	[dep_name] 	= D.FULL_NAME,
	[dep_inn] 	= case
				WHEN D.INN IS NOT NULL THEN D.INN
				ELSE NULL
			  end,
	[dep_buhph]	= (SELECT TOP 1 PHONE FROM DEPARTMENT_FACES WHERE LINK_UP = D.LINK AND NAME LIKE '%Главный бухгалтер%'),
	[dep_kadph]	= (SELECT TOP 1 PHONE FROM DEPARTMENT_FACES WHERE LINK_UP = D.LINK AND NAME LIKE '%Рук.кадровой службы%'),
	[DATE_FROM] = @varKSdDate1 ,
	[DATE_THRU] = @Date1,
	[DATE_DOC] = Getdate()		  
	FROM	(
	SELECT	@LINK_EMPL as empl_link,
		R.LINK_FACE,
		R.MONTH_NAME,
		R.[YEAR],
		R.SUMMA AS NACH,
		@SR_SUM_3MONTH as SR_SUMM,
		r.work ,
		r.norm,
		r.COMMENT
	FROM	#RES R 
	) RR  left join dbo.ku_empl_placing_fn(@work_date) KU_EM
	ON RR.empl_link = KU_EM.LINK left join DEPARTMENTS D
	ON D.LINK = KU_EM.DEP_LINK left join department_accounts DA
	ON D.MAIN_LINK = DA.LINK
--=====================================================================

END

RETURN 0

GO


GRANT EXECUTE ON dbo.[SS_SPR_SZP_REP] TO PUBLIC

GO

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

GO

/* --- ФОРМИРОАНИЕ ПРОВОДОК ПО ЗАКРЫТИЮ ГОДА --- */
CREATE PROCEDURE dbo.BK_CHANGE_ANALIT_CREATE_PROV
	@intLINK_DOC	INT,
	@intDEL_PROV	INT
AS
BEGIN
	DECLARE @intDEP_LINK	INT,
		@dDOC_DATE	DATETIME,
		@dDATE_PROV	DATETIME,
		@intROWCOUNT	INT,
		@intOLD_ANALIT	INT,
		@intNEW_ANALIT	INT,

		@strCOMMENT_G1	VARCHAR (254),
		@strCOMMENT_G2	VARCHAR (254),

		@dDATE_REST	DATETIME,
		@varKSERROR	INT,

	/* --- !!!ЗАПОЛНЕНИЕ ПРОВОДОК!!! --- */
		@varKSLinkG1	INT,
		@varKSLinkG2	INT,
		@varKSAccount	INT,
		@varKSKBK		INT,
		@varKSEKR		INT,
		@varKSDEP		INT,
		@varKSSUB		INT,
		@varKSEMP		INT,
		@varKSNOMEN	INT,
		@varKSINV		INT,
		@varKSKAU		INT,
		@varKSDEP_ACC	INT,
		@varKSTMC 		INT,
		@varKSINDATE	DATETIME,
		@varKSAP1		INT,
		@varKSAP2		INT,
		@varKSAP3		INT,
		@varKSSGU		INT,
		@D_SUMMA		NUMERIC (28,4),
		@K_SUMMA		NUMERIC (28,4),
		@SUMMA			NUMERIC (28,4),
		@D_QTY			NUMERIC (28,4),
		@K_QTY			NUMERIC (28,4),
		@QTY			NUMERIC (28,4),
		@intS_ACTIVE		INT,
		@intORDERS_G1		INT,
		@intLINK_ECONOM_OPER	INT,
		@intDBKR1		TINYINT,
		@intDBKR2		TINYINT,
		@intZABALANS		TINYINT

	/* --- НАСТРОЙКИ ДОКУМЕНТА --- */
	SELECT
		@intLINK_DOC = LINK,		
		@intDEP_LINK	=	DEP_LINK,
		@intOLD_ANALIT	=	LN_KBK_OLD,
		@intNEW_ANALIT	=	LN_KBK_NEW,
		@dDOC_DATE	=	[DATE],
		@dDATE_PROV	=	DATE_PROV
	FROM	dbo.BK_CHANGE_ANALIT
	WHERE	LINK = @intLINK_DOC
	
	SET @intROWCOUNT = @@ROWCOUNT
	IF @intROWCOUNT <> 1
	BEGIN
		RAISERROR ('Проводки не сформированы! Сохраните документ. ', 11, 1)
		RETURN 1
	END

	/* -- Удаление старых проводок в документе -- */
	IF @intDEL_PROV = 1
	BEGIN
		DELETE FROM G_PROV1 WHERE LINK_UP = @intLINK_DOC
		IF @dDATE_PROV IS NOT NULL
			exec X_Saldo_CommitChanges
	END

	/* !!!!!!! BEGIN SCRIPT !!!!!!!!!! */
	SET @dDATE_REST = DATEADD (DAY, 1, @dDOC_DATE) /* --- --- */
	SET @strCOMMENT_G1 = 'Смена КБК'

	DECLARE #REST	CURSOR STATIC LOCAL 
		FOR SELECT SUM (REST.D_SUMMA), SUM (REST.K_SUMMA), 
				SUM (REST.D_QUANTITY), SUM (REST.K_QUANTITY),
				REST.ACCOUNT, REST.KBK, REST.EKR, REST.DEP, REST.SUB, REST.EMP, REST.NOMEN,
				REST.INV, REST.KAU, REST.DEP_ACC, REST.TMC, REST.SGU, REST.INDATE,
				REST.AP1, REST.AP2, REST.AP3, SA.S_ACTIVE, SA.ZABALANS
			FROM dbo.ARestTableByDate (@dDATE_REST, DEFAULT) REST
			INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = REST.ACCOUNT)
			WHERE REST.DEP_LINK =  @intDEP_LINK
				AND REST.KBK = @intOLD_ANALIT
			GROUP BY REST.ACCOUNT, REST.KBK, REST.EKR, REST.DEP, REST.SUB, REST.EMP, REST.NOMEN,
				REST.INV, REST.KAU, REST.DEP_ACC, REST.TMC, REST.SGU, REST.INDATE,
				REST.AP1, REST.AP2, REST.AP3, SA.S_ACTIVE, SA.ZABALANS

	OPEN #REST
	FETCH NEXT FROM #REST
		INTO @D_SUMMA, @K_SUMMA, 
			@D_QTY, @K_QTY,
			@varKSAccount, @varKSKBK, @varKSEKR, @varKSDEP, @varKSSUB,
			@varKSEMP, @varKSNOMEN, @varKSINV, @varKSKAU, @varKSDEP_ACC,
			@varKSTMC, @varKSSGU, @varKSINDATE,
			@varKSAP1, @varKSAP2, @varKSAP3, @intS_ACTIVE, @intZABALANS

	WHILE @@FETCH_STATUS = 0
	BEGIN

		SET @varKSLinkG1 = NULL
		SET @varKSLinkG2 = NULL

		/* --- Разносим по счетам!!! --- */
		IF @intS_ACTIVE = 1	-- ДЛЯ ЗАКРЫТИЯ АКТИВНЫХ СЧЕТОВ
		BEGIN
			SET @SUMMA = @D_SUMMA
			SET @QTY = @D_QTY
			SET @intDBKR1 = 1
			SET @intDBKR2 = 0
		END
		ELSE			-- ДЛЯ ЗАКРЫТИЯ ПАССИВНЫХ СЧЕТОВ
		BEGIN	
			SET @SUMMA = @K_SUMMA
			SET @QTY = @K_QTY
			SET @intDBKR1 = 0
			SET @intDBKR2 = 1
		END

		/* -- Определяем КОСГУ: ставим в Дб и Кт увлечение -- */
		IF @varKSSGU IS NULL
		BEGIN
			SET @varKSSGU = (SELECT TOP 1 S.LINK_SGU
						FROM dbo.S_ACCOUNTS_SGU S
						INNER JOIN dbo.KOSGU K ON (K.LINK = S.LINK_SGU
								AND K.DB_KR = @intDBKR2)
						WHERE S.ACCOUNT = @varKSAccount)

			IF @varKSSGU IS NULL
				SELECT @varKSSGU = LINK FROM dbo.KOSGU WHERE CODE = '000'
		END		

		-- Вычисялем текущее структурное подразделение --
		SELECT TOP 1
			@varKSSUB = SUBDIV_LINK
		FROM dbo.SUBDIVISION (@dDOC_DATE)
		WHERE LINK = @varKSSUB

		/* --- G_PROV1 --- */
		SET @intORDERS_G1 = COALESCE ((SELECT MAX (ORDERS) FROM G_PROV1 WHERE LINK_UP = @intLINK_DOC), 0) + 1
		EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV1 @varKSLinkG1 OUTPUT, @intLINK_DOC, NULL,
						  @strCOMMENT_G1, @intORDERS_G1
		IF @varKSERROR <> 0
			RETURN @varKSERROR	

		SET @strCOMMENT_G2 = ISNULL ((SELECT RTRIM (CONVERT (VARCHAR (254), NAME))
						FROM dbo.XOZ_OPER WHERE LINK = @intLINK_ECONOM_OPER), @strCOMMENT_G1)

		/* --- G_PROV2 --- */
		EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV2 @varKSLinkG2 OUTPUT, @varKSLinkG1, NULL,
					 @SUMMA, @QTY, 0, @strCOMMENT_G2, @intLINK_ECONOM_OPER, 1

		IF @varKSERROR <> 0
			RETURN @varKSERROR	

		/* -- Часть1 списание -- */
		EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV_AP @varKSLinkG2, @intDBKR1, @varKSAccount, 
					@intOLD_ANALIT, @varKSEKR, @varKSDEP, @varKSSUB,
					@varKSEMP, @varKSNOMEN, @varKSINV, @varKSKAU, @varKSDEP_ACC,
					@varKSTMC, @varKSINDATE, @varKSAP1, @varKSAP2, @varKSAP3, @varKSSGU 
		IF @varKSERROR <> 0
			RETURN @varKSERROR	

		/* -- Часть2 восстановление -- */
		IF @intZABALANS = 1	-- для забалансовых счетов
		BEGIN
			SET @varKSLinkG2 = NULL
			EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV2 @varKSLinkG2 OUTPUT, @varKSLinkG1, NULL,
						 @SUMMA, @QTY, 0, @strCOMMENT_G2, @intLINK_ECONOM_OPER, 2
	
			IF @varKSERROR <> 0
				RETURN @varKSERROR	

		END
		
		EXECUTE @varKSERROR = dbo.X_UPDATE_G_PROV_AP @varKSLinkG2, @intDBKR2, @varKSAccount, 
					@intNEW_ANALIT, @varKSEKR, @varKSDEP, @varKSSUB,
					@varKSEMP, @varKSNOMEN, @varKSINV, @varKSKAU, @varKSDEP_ACC,
					@varKSTMC, @varKSINDATE, @varKSAP1, @varKSAP2, @varKSAP3, @varKSSGU 
		IF @varKSERROR <> 0
			RETURN @varKSERROR	

		FETCH NEXT FROM #REST
			INTO @D_SUMMA, @K_SUMMA, 
				@D_QTY, @K_QTY,
				@varKSAccount, @varKSKBK, @varKSEKR, @varKSDEP, @varKSSUB,
				@varKSEMP, @varKSNOMEN, @varKSINV, @varKSKAU, @varKSDEP_ACC,
				@varKSTMC, @varKSSGU, @varKSINDATE,
				@varKSAP1, @varKSAP2, @varKSAP3, @intS_ACTIVE, @intZABALANS
	END

	CLOSE #REST
	DEALLOCATE #REST
END


GO


GRANT EXECUTE ON dbo.[BK_CHANGE_ANALIT_CREATE_PROV] TO PUBLIC

GO


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


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

GO

CREATE procedure [dbo].[RM_REPORT_SELECTION]
	@varKSnYEAR				int,
	@varKSnPERIODIC			int,
	@varKSnPeriod_Numeric	int,
	@varKSnSvod				int,
	@varKSnStatus			int,
	@varKSsrtFltKbk			varchar(8000) = null,
	@varKSsrtFltBud			varchar(1000) = null,
    @cProgressTable			varchar(254)  = null,
	@calledfrom				tinyint = 1,			-- 0 - вызов из толстого, 1 - вызов из тонкого,
	@col_an_str				varchar(1000) = '#',	-- строка содержащая список аналитических признаков в столбцах
	@row_an_str				varchar(1000) = '#'		-- строка содержащая список аналитических признаков в строках
as
-----------нижеследующие строчки нужны для нормализации наименования кбк в 317 форме-----------------
-----------------------------------------------------------------------------------------------------
declare @LF int,@LT int,@LC int
select @LF=link_form from report_forms where code='0503317M'

select @LT=link_table from report_tables where orders=1 and link_form=@LF
select @LC=Link_col from report_coloumns where orders=1 and link_table=@LT

update report_dinamics 
set str_val=(select long_name from RN_VIEW_KBK_0503317M_01 A where A.code=code_row)
where link_sf in (select link_saved_form from report_saved_forms where link_form=@LF)
and link_col=@LC 
and str_val<>(select long_name from RN_VIEW_KBK_0503317M_01 A where A.code=code_row)


select @LT=link_table from report_tables where orders=3 and link_form=@LF
select @LC=Link_col from report_coloumns where orders=1 and link_table=@LT

update report_dinamics 
set str_val=(select long_name from RN_VIEW_KBK_0503317M_03 A where A.code=code_row)
where link_sf in (select link_saved_form from report_saved_forms where link_form=@LF)
and link_col=@LC and str_val<>(select long_name from RN_VIEW_KBK_0503317M_03 A where A.code=code_row)
-----------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------
declare @strProgressExec varchar(1000)
-- если таблица #SelectedBOK не существует, то создаём её пустую
if not exists (select * from tempdb.dbo.sysobjects where id = object_id(N'[tempdb].[dbo].[#selectedBOK]'))
begin
    CREATE TABLE #selectedBOK (data varchar(254))
end
-- если таблица #SelectedKBK не существует, то создаём её пустую
if not exists (select * from tempdb.dbo.sysobjects where id = object_id(N'[tempdb].[dbo].[#selectedKBK]'))
begin
    CREATE TABLE #selectedKBK (code varchar(254),[name] varchar(254))
end;
-- если таблица #selectedAtr не существует, то создаём её пустую
if not exists (select * from tempdb.dbo.sysobjects where id = object_id(N'[tempdb].[dbo].[#selectedAtr]'))
begin
    create table #selectedAtr (atr varchar(254))
end
-- если таблица #selectedNAS не существует, то создаём её пустую
if not exists (select * from tempdb.dbo.sysobjects where id = object_id(N'[tempdb].[dbo].[#selectedNAS]'))
begin
    create table #selectedNAS (str_val varchar(254))
end
--------------------------------------------------------------------------------
declare @allow_empty tinyint, -- 0 - запрет пустых значений, !0 - пустые значения разрешены
        @inThousand tinyint,
        @fullNameOrg tinyint

set @allow_empty = 0
set @inThousand = 0
set @fullNameOrg = 0
select top 1
    @allow_empty = case when (cast(str_val as int)& 0x01) > 0 then 1 else 0 end,
    @inThousand =  case when (cast(str_val as int)& 0x02) > 0 then 1 else 0 end,
    @fullNameOrg = case when (cast(str_val as int)& 0x04) > 0 then 1 else 0 end
from
    #selectedNAS

----ограничение диапазона сохранненых форм-------------------------------------- 
if @calledfrom = 0 begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Ограничение диапазона сохранённых форм'', percents = 12'
    execute(@strProgressExec)
end
--------------------------------------------------------------------------------
declare @sid varbinary(85)
set @sid = suser_sid()
if @calledfrom = 1
	EXEC dbo.RM_SubDepAccessBySID @sid

CREATE TABLE #sf (link_sf int,link_form int,period_type tinyint,period_number tinyint,begin_date datetime,link_organization int,btype varchar (250),link_type_svod int)

insert into #sf
select distinct rsf.link_saved_form as link_sf,
	rsf.link_form, 
	rsf.period_type, 
	rsf.period_number,
	RSF.begin_date,
	rsf.link_organization,
	[btype] = (select [name] from BI_DICTION_BUDG_TYPE where link = rsf.link_type_svod),
    rsf.link_type_svod
    from   report_saved_forms RSF (nolock) 
    where  RSF.link_form in --(select link_form from @kbk_tab)
			(select rt2.link_form from
				BufferGetTableByID('REPORT_COL_LINK_CHECKED') rl2 
                                inner join report_coloumns rc2 (nolock) on rc2.link_col = rl2.link 
                                inner join report_tables rt2 (nolock) on rt2.link_table = rc2.link_table )
	 and year(RSF.begin_date)=@varKSnYEAR
	 and RSF.period_type = @varKSnPERIODIC
	 and RSF.period_number = @varKSnPeriod_Numeric
	 and RSF.version = 	(select  top 1 version
   			 	from report_saved_forms as lrsf (nolock) 
   				where lrsf.link_form = RSF.link_form
 				and lrsf.begin_date = RSF.begin_date
 				and lrsf.period_type = RSF.period_type
 				and lrsf.period_number = RSF.period_number
 				and lrsf.link_organization = RSF.link_organization
 				and isnull(lrsf.link_type_svod,-255) = isnull(RSF.link_type_svod,-255)
				and (select dbo.RN_GET_ATR_VAL(lrsf.link_saved_form,null,1)) = (select dbo.RN_GET_ATR_VAL(RSF.link_saved_form,null,1))
   				order by  version desc)
	and rsf.IsSvod in (
                case when @varKSnStatus&0x10 = 0x10 then 1 else -1 end,
			    case when @varKSnStatus&0x20 = 0x20 then 0 else -1 end) --@varKSnSvod
	and rsf.IsRO in (
                case when @varKSnStatus&0x01 = 0x01 then 0 else -1 end,
			    case when @varKSnStatus&0x02 = 0x02 then 1 else -1 end,
			    case when @varKSnStatus&0x04 = 0x04 then 2 else -1 end,
			    case when @varKSnStatus&0x08 = 0x08 then 3 else -1 end,
			    case when @varKSnStatus&0x40 = 0x40 then 4 else -1 end,
			    case when @varKSnStatus&0x80 = 0x80 then 5 else -1 end)
	and (rsf.link_organization in (select link from dbo.BufferGetTableByID('SUB_DEP_LINK')) or @calledfrom = 0)
    and (rsf.link_type_svod in (select link from dbo.BufferGetTableByID('REPORT_SEL_BUD')) OR NOT EXISTS(select link from dbo.BufferGetTableByID('REPORT_SEL_BUD')))
    and (rsf.link_organization in (select link from dbo.BufferGetTableByID('REPORT_SEL_ORG')) OR NOT EXISTS(select link from dbo.BufferGetTableByID('REPORT_SEL_ORG')))
	and ((select dbo.RN_GET_ATR_VAL(rsf.link_saved_form,null,0)) in (select atr from #selectedAtr) OR NOT EXISTS(select atr from #selectedAtr))

exec dbo.BufferClear 'SUB_DEP_LINK'
delete from Buffer where SID = suser_sid() and ID = 'REPORT_SEL_BUD'
-------------------------------------------------------------------------------------------
--- далее создаётся таблица @kbk_tab в которой будут link_col на столбцы с КБК
if @calledfrom = 0 begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Проверка наличия КБК в форме'', percents = 18'
    execute(@strProgressExec)
end

declare @kbk_tab table(code char(30),link_form int,name varchar(70),link_table int,link_col int,link_code_col int,isEdited tinyint, keyflag tinyint)
insert into @kbk_tab
select distinct rf.code, rf.link_form, rc.[name],rc.link_table, rc.link_col, rt.link_code_col, rc.isEdited, case when rc.link_col = rt.link_code_col then 1 else 0 end
from	
    report_forms rf (nolock) inner join
	report_tables rt (nolock) on rf.link_form = rt.link_form inner join 
	report_coloumns rc (nolock) on rt.link_table = rc.link_table 
  
where 
exists(
    select * 
    from
        BufferGetTableByID('REPORT_COL_LINK_CHECKED') rl2 inner join
	    report_coloumns rc2 (nolock) on rc2.link_col = rl2.link inner join
	    report_tables rt2 (nolock) on rt2.link_table = rc2.link_table 
    where 
        rt2.link_table = rt.link_table
)
and 
(
    rc.name like '%БК%' or rc.name like '%КД%' or rc.name like '%ФКР%' or (rf.Object like '%FORM14%' and rc.name = 'Код строки') or
    rc.name like '%КИВ%' or
    rc.name = 'Код расхода'
)
-- теперь таблица @kbk_tab содержит данные о столбце, который предположительно (судя по имени) является столбцом КБК
-- в одной таблице может быть один такой столбец
-------------------------------------------------------------------------------------------
if @calledfrom = 0 begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Обработка данных'', percents = 33'
    execute(@strProgressExec)
end
-------------------
exec DropTempTable '#code_row'
create table #code_row (data varchar(254),code varchar(254)) -- табличка в которую будут помещены линки кодовых строк и соответсвующих КБК
-------------------
declare @debug_start datetime, -- здесь объявлены переменные которые используются для отладки и оптимизации
        @debug_stop datetime

insert into #code_row  -- в этом кусочке в таблицу #code_row (см. выше) помещаются значения допускаемые фильтрами по КБК и Боковику. Причём из столбцов, не являющихся ключевыми
select distinct code_row,str_val
from dbo.report_dinamics_all 
where link_sf in (
    select link_sf from #sf 
)
and link_col in (select link_col from @kbk_tab where keyflag = 0)
and str_val in (select code from #selectedKBK)
and (dbo.RT_BOK14(code_row) in (select data from #selectedBOK) or not exists(select data from #selectedBOK))
-------------------
insert into #code_row  -- в этом кусочке в таблицу #code_row (см. выше) помещаются значения допускаемые фильтрами по КБК и Боковику. Причём из столбцов, ЯВЛЯЮЩИХСЯ ключевыми
select distinct code_row,dbo.RM_KBK14(code_row)
from dbo.report_dinamics_all 
where link_sf in (
    select link_sf from #sf 
)
and link_col in (select min(rc.link_col) from dbo.report_coloumns as rc where rc.Col_Type = 1 and rc.link_col <> (select rt.link_code_col from report_tables as rt where rt.link_table = rc.link_table) and rc.link_table in (select kt.link_table from @kbk_tab as kt where kt.keyflag = 1) group by rc.link_table)
and dbo.RM_KBK14(code_row) in (select code from #selectedKBK)
and (dbo.RT_BOK14(code_row) in (select data from #selectedBOK) or not exists(select data from #selectedBOK))
-------------------

if not exists(select code from #selectedKBK) begin  -- если не задан ФИЛЬТР по КБК, то выводим либо все значения из фильтра по Боковику, либо, если и он не задан, То ВСЕ значения 
    insert into #code_row
    select distinct rd.code_row,''
    from dbo.report_dinamics_all as rd 
    where rd.link_sf in (
        select link_sf from #sf 
    )
    and link_col in (
        select link from BufferGetTableByID('REPORT_COL_LINK_CHECKED')
        union
        select link_col 
        from 
            @kbk_tab 
        where link_table in (
                                select rc2.link_table 
                                from dbo.report_coloumns as rc2 (nolock)
                                where rc2.link_col in (
                                                        select link from BufferGetTableByID('REPORT_COL_LINK_CHECKED')
                                                       )
                            )
--                         select rc.link_col/*min(rc.link_col)*/
--                         from dbo.report_coloumns as rc
--                         where /*rc.Col_Type = 1 
--                         and rc.link_col <> (select rt.link_code_col from report_tables as rt where rt.link_table = rc.link_table) 
--                         and*/ rc.Link_Table in (
--                                                 select rc2.link_table 
--                                                 from dbo.report_coloumns as rc2
--                                                 where rc2.link_col in (
--        select link from BufferGetTableByID('REPORT_COL_LINK_CHECKED')
--                                                                    )
--                                               )
                     )
    and (dbo.RT_BOK14(rd.code_row) in (select data from #selectedBOK) or not exists(select data from #selectedBOK))
    
    update #code_row -- здесь в поле Code попадают значения КБК соответствующие отобранным выше строкам
    set Code = case 
                when isnull(kt.link_form,0)<>0 and isnull(kt2.link_col,0) = 0 then dbo.RM_KBK14(rd.code_row)
                when isnull(kt.link_form,0)<>0 and isnull(kt2.link_col,0)<> 0 then (case when kt2.link_col = rt.link_code_col then dbo.RM_KBK14(rd.code_row) else rd.str_val end)
                else ''
               end
--    select cr.data,rd.code_row,rd.link_sf,sf.link_sf,rd.link_col,rc.link_col,rc.link_table,rt.link_table,sf.link_form,kt.link_form,rd.link_col,kt2.link_col
    from
        #code_row as cr (nolock)
        inner join dbo.report_dinamics_all rd 
            on cr.data = rd.code_row
        inner join #sf as sf (nolock)
            on rd.link_sf = sf.link_sf
        inner join dbo.report_coloumns as rc (nolock)
            on rd.link_col = rc.link_col
        inner join dbo.report_tables as rt (nolock)
            on rc.link_table = rt.link_table
        left join @kbk_tab as kt
            on sf.link_form = kt.link_form and rt.link_table = kt.link_table
        left join @kbk_tab as kt2
            on rd.link_col = kt2.link_col
    where data = cr.data
end
---------------------------
exec DropTempTable '#report_dinamics_res'
create table #report_dinamics_res (link_SF int,Link_Col int,Code_Row varchar(250),Float_val numeric(20,4),Str_Val varchar(8000),Code varchar(250))

insert into #report_dinamics_res -- В ЭТОЙ ТАБЛИЦЕ БУДУТ ЧИСЛОВЫЕ ЗНАЧЕНИЯ с кодами строк и значениями КБК отобранными выше
select rd.link_sf,rd.link_col,rd.code_row,rd.float_val,rd.str_val,cr.code 
from 
    report_dinamics_all as rd 
    inner join #sf as sf (nolock)
        on rd.link_sf = sf.link_sf
    inner join BufferGetTableByID('REPORT_COL_LINK_CHECKED') as bu
        on rd.link_col = bu.link
    inner join #code_row as cr (nolock) 
        on rd.code_row = cr.data
where 
    (rd.float_val <> 0.0 OR rd.str_val <> '')

create nonclustered index ixx on #report_dinamics_res (link_SF,Link_Col,Code_Row)

--------------------------
delete from #code_row -- очищаем табличку для значений СТАТИЧЕСКИХ таблиц
--------------------------

insert into #code_row  -- здесь берём линки строк и значение КБК из таблицы report_formula
select distinct rf.link_row,rf.formula
from 
    dbo.report_formula as rf (nolock) 
    inner join @kbk_tab as kt
        on rf.link_col = kt.link_col
where 
    rf.formula in (select code from #selectedKBK)
and
    rf.link_row in (
        select rf2.link_row
        from
            dbo.report_formula as rf2 (nolock)
            inner join dbo.report_coloumns as rc (nolock)
                on rf2.link_col = rc.link_col
            inner join dbo.report_tables as rt (nolock)
                on rt.link_table = rc.link_table and rt.link_code_col = rc.link_col
        where
            rf2.formula in (select data from #selectedBOK) or not exists(select data from #selectedBOK)
            and
            rt.link_table in (select link_table from dbo.report_coloumns where link_col in (select link from BufferGetTableByID('REPORT_COL_LINK_CHECKED')))
    )

insert into #code_row -- здесь берём линки строк и значение КБК из таблицы report_string
select distinct rs.link_row,rs.str_val
from 
    #sf as sf (nolock)
    inner join dbo.report_string_all as rs 
        on sf.link_sf = rs.link_saved_form
    inner join @kbk_tab as kt
        on rs.link_col = kt.link_col
where 
    rs.str_val in (select code from #selectedKBK)    
and
    rs.link_row in (
        select rf2.link_row
        from
   dbo.report_formula as rf2 (nolock)
            inner join dbo.report_coloumns as rc (nolock)
                on rf2.link_col = rc.link_col
            inner join dbo.report_tables as rt (nolock)
                on rt.link_table = rc.link_table and rt.link_code_col = rc.link_col
        where
            rf2.formula in (select data from #selectedBOK) or not exists(select data from #selectedBOK)
            and
            rt.link_table in (select link_table from dbo.report_coloumns where link_col in (select link from BufferGetTableByID('REPORT_COL_LINK_CHECKED')))
    )

if not exists(select code from #selectedKBK)begin -- если фильтр по КБК не установлен, берём значения всех боковиков из фильтра или, если он не задан, ВСЕХ боковиков (параллельно находим соответствующие КБК если есть)
    insert into #code_row
    select distinct rf2.link_row,(select 
            top 1 isnull(rs.str_val,rf3.formula) as code
        from 
            dbo.report_formula as rf3 (nolock)
            inner join dbo.report_coloumns as rc2 (nolock)
                on rf3.link_col = rc2.link_col
            inner join @kbk_tab as kt
                on rc2.link_col = kt.link_col
            left join dbo.report_string_all as rs 
                on rf3.link_row = rs.link_row and rf3.link_col = rs.link_col
        where
            rf3.link_row = rf2.link_row and rc2.link_table = rt.link_table
        ) as code
    from
        dbo.report_formula as rf2 (nolock)
        inner join dbo.report_coloumns as rc (nolock)
            on rf2.link_col = rc.link_col
        inner join dbo.report_tables as rt (nolock)
            on rt.link_table = rc.link_table and rt.link_code_col = rc.link_col
        inner join #sf as sf (nolock)
            on rt.link_form = sf.link_form
    where
        rf2.formula in (select data from #selectedBOK) or not exists(select data from #selectedBOK)
        and
        rt.link_table in (select link_table from dbo.report_coloumns where link_col in (select link from BufferGetTableByID('REPORT_COL_LINK_CHECKED')))
end 
---------------------------------------------------------------------------------------------------------------------
exec DropTempTable '#report_summa'
create table #report_summa (link_saved_form int,Link_Col int,Link_Row int,Summa numeric(20,4),Code varchar(250))

--set @debug_start = GETDATE()--<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

insert into #report_summa (link_saved_form,Link_Col,Link_Row,Summa,Code)
select distinct sf.link_sf,rs.link_col,rs.link_row,rs.Summa,cr.Code
from
    #sf as sf
    inner join dbo.report_summa_all as rs 
        on sf.link_sf = rs.link_saved_form
    inner join #code_row as cr (nolock)
        on rs.link_row = cr.data
    inner join BufferGetTableByID('REPORT_COL_LINK_CHECKED') as bu
        on rs.link_col = bu.link
    inner join dbo.report_coloumns as rc (nolock)
        on rc.link_col = rs.link_col and rc.col_type = 0

--set @debug_stop = GETDATE()--<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
--print 'прошло времени (мс):' + cast(DATEDIFF (millisecond, @debug_start , @debug_stop ) as varchar(20))
-----------------------------------------------------------------------------------------------------------------------
-- если 
-----------------------------------------------------------------------------------------------------------------------
if @calledfrom = 0 begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Формирование результирующей таблицы'', percents = 50'
    execute(@strProgressExec)
end
/* for dinamic */
CREATE TABLE #restab(nn int IDENTITY, form char(20),period varchar(7),tab varchar(50),dep varchar(50),deplink int,budg varchar(10),name_dep varchar(254),key_col varchar(250),link_row varchar(50),col varchar(70),ord_col varchar(3),kbk varchar(254),razd varchar(2),podrazd varchar(2),csr varchar(7),vr varchar(3),ekr varchar(3),bud_type varchar(250),summa float(53),lsf int)
insert into #restab
select distinct	
    [form] 	= RF.code, /*код формы*/
	[period]= 'текущий', -- dbo.rm_GetPeriodName(SF.period_type,SF.period_number,SF.begin_date),
	[tab]	= RT.[name], /*код таблицы*/
	[dep]	= DEP.code, /*код источника (организации)*/
	[deplink] = DEP.link,
	[budg] = DEP.budg, /*код БП источника (организации)*/
	[name_dep] = case when @fullNameOrg <> 0 then DEP.full_name else DEP.name end,
	[key_col]= dbo.RT_BOK14(RD.code_row), /*код боковика*/
    [link_row] = case
                    when charindex('#',RD.code_row)>0 -- если в коде строки есть # считаем что имеем дело с 14-ми формами
                    then (select cast(link_row as varchar(20)) from dbo.report_formula where formula = substring(RD.code_row, charindex('#',RD.code_row) + 1,10/*от балды*/) and link_col = (select link_code_col from dbo.report_tables where link_table = RT.link_table))
                    else RD.code_row /*линк строчки*/
                end,
	[col]	= RC.[name], /*код колонки*/

	[ord_col]= right('000' + ltrim(rtrim(cast(case /*весь этот бардак - заглушка для 317 форм*/
                when RF.CODE like '%0503317M' or RF.CODE like '%0503317G'
                    then /*(case 
                            when RC.[orders] = 2 
                                then 0
                            when RC.[orders] > 2
                                then RC.[orders] - 1
                            else RC.[orders]
                          end)*/
                        RC.[export_order]
                else RC.[orders]
                end as varchar(3)))),3),

	[kbk] = rd.code, /*КБК*/
	[razd] = dbo.RT_GET_RAZD(rd.code), /*Раздел*/
	[podrazd] = dbo.RT_GET_PODRAZD(rd.code), /*Подраздел*/
	[csr] = dbo.RT_GET_CSR(rd.code), /*ЦСР*/
	[vr] = dbo.RT_GET_VR(rd.code), /*Вид расхода*/
	[ekr] = dbo.RT_GET_EKR(rd.code), /*ЭКР*/
	[bud_type] = isnull(sf.btype,'Бюджет не определен'),
	[summa] = case when @inThousand <> 0 then (RD.float_val)/1000.0 else RD.float_val end, /*номер колонки*/ 	
    [lsf] = sf.link_sf
from 	
    report_coloumns RC (nolock) inner join 
	BufferGetTableByID('REPORT_COL_LINK_CHECKED') RL on rc.link_col = rl.link inner join
	report_tables RT (nolock) on RC.link_table = RT.link_table inner join
	report_forms RF (nolock) on RT.link_form = RF.link_form inner join 
	#report_dinamics_res RD on rd.link_col = RL.link inner join
	#sf sf on sf.link_sf = RD.link_SF inner join 
	departments DEP (nolock) on DEP.link = SF.link_organization 
where 
    RD.float_val<>0.0 or (rc.Col_Type = 0 and @allow_empty <> 0)
union 
/* for static */    
select distinct
    [form] 	= RF.code, /*код формы*/
	[period] = 'текущий', -- dbo.rm_GetPeriodName(SF.period_type,SF.period_number,SF.begin_date),
	[tab]	= RT.[name], /*код таблицы*/
	[dep]	= DEP.code, /*код источника (организации)*/
	[deplink] = DEP.link,
	[budg] = DEP.budg, /*код БП источника (организации)*/
	[name_dep] = case when @fullNameOrg <> 0 then DEP.full_name else DEP.name end,
	[key_col]= RM.formula, /*код боковика*/
    [link_row] = convert(varchar(50),RM.link_row), /*линк строчки*/
	[col]	= RC.[name], /*код колонки*/
	[ord_col]= right('000' + ltrim(rtrim(cast(RC.[orders] as varchar(3)))),3), /*номер колонки*/ 
	[kbk] = rs.code, /*КБК*/	
	[razd] = dbo.RT_GET_RAZD(rs.code), /*Раздел*/
	[podrazd] = dbo.RT_GET_PODRAZD(rs.code), /*Подраздел*/
	[csr] = dbo.RT_GET_CSR(rs.code), /*ЦСР*/
	[vr] = dbo.RT_GET_VR(rs.code), /*Вид расхода*/
	[ekr] = dbo.RT_GET_EKR(rs.code), /*ЭКР*/
 	[bud_type] = isnull(sf.btype,'Бюджет не определен'),
	[summa] = case when @inThousand <> 0 then (RS.summa)/1000.0 else RS.summa end, /*номер колонки*/ 	
    [lsf] = sf.link_sf
from
 	report_coloumns RC (nolock) inner join 
	BufferGetTableByID('REPORT_COL_LINK_CHECKED') RL on rc.link_col = rl.link inner join
	report_tables RT (nolock) on RC.link_table = RT.link_table inner join
	report_forms RF (nolock) on RT.link_form = RF.link_form left join 
	#report_summa RS (nolock) on RS.link_col = RL.link inner join 
	report_formula rm (nolock) on rm.link_row = rs.link_row and rm.link_col = rt.link_code_col inner join 
	#sf sf on sf.link_sf = RS.link_Saved_Form inner join 
	departments DEP (nolock) on DEP.link = SF.link_organization
where	
    RS.summa<>0.0 or @allow_empty <> 0

if @calledfrom = 0 begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Добавление в набор текстовых столбцов'', percents = 60'
    execute(@strProgressExec)
end

declare @clone table(form char(20),period varchar(7),tab varchar(50),deplink int,key_col varchar(250),link_row varchar(50),col varchar(70),ord_col varchar(3),mark tinyint)
insert into @clone select form,period,tab,deplink,key_col,link_row,col,ord_col,mark = 0 from #restab
--------------------------------------------------
        declare @iLC int,
                @cES varchar(8000),
                @cCodeForm char(20),
                @cPeriod varchar(11),
                @cNameTab varchar(50),
                @iDeplink int,
                @cKeyCol varchar(250),
                @cCodeCol varchar(250),
                @cOrdCol char(3),
                @cStr_Val varchar(8000),
                @cNewCol varchar(254),
                @IsEdited tinyint,
                @selFields varchar(1000),        
				@res_set_num int,
                @i int,
                @j int,
                @IsCodeCol int,
                @iLink_Form int,
                @iLink_Table int,
                @iVal_Type tinyint,
                @iLink_Col int,
                @iLink_SF int,
                @cCode_Row varchar(50)

        declare @t_text_cols table (numb int IDENTITY(1,1), lc int, lt int, lf int)
        insert into @t_text_cols (lc, lt, lf) 
        select distinct rl.link, rt.link_table, rf.link_form
        from BufferGetTableByID('REPORT_COL_LINK_CHECKED') rl 
        inner join report_coloumns rc (nolock) on rl.link = rc.link_col and rc.col_type = 1
        inner join report_tables rt (nolock) on rt.link_table = rc.link_table
        inner join report_forms rf (nolock) on rf.link_form = rt.link_form
        order by rl.link

        set @i = 1 -- это, счётчик столбцов
        set @iLC = 0
        select @iLC = lc, @iLink_Table = lt, @iLink_Form = lf from @t_text_cols where numb = @i
        set @selFields = ''
        -- создаём эту таблицу с тем, чтобы помещать в неё имена текстовых колонок, чтобы избегать их дублирования в результирующей выборке
        create table #col_names (num int IDENTITY(1,1), name varchar(8000), link_col int, alias varchar(100))        
        -- здесь обьявляются переменные, участвующие в борьбе с дублированием колонок с одинаковыми именами
        declare @cur_col_name varchar(254),
                @count_col_name int,
                @cur_col_link int,
                @cur_alias_name varchar(100)

        while @iLC <> 0
        begin
                ----------------------------------------------------
                select @IsEdited = IsEdited from report_coloumns (nolock) where link_col = @iLC
                set @cur_col_name = ''
                set @cur_col_link = 0
                select @cur_alias_name = alias, @cur_col_name = name, @cur_col_link = link_col from #col_names (nolock) where name in (select name from report_coloumns (nolock) where link_col = @iLC)
--                 if @cur_col_link <>0
--                 begin -- если совпадает, то в качестве нового имени берём найденое и не добавляем новый столбец
--                         set @cNewCol = '_'+ltrim(rtrim(convert(varchar(254),@cur_col_link)))
--                 end
--                 else
--                 begin -- иначе добавляем новое имя в таблицу #col_names и новый столбец в #RESTAB
                        select @cur_col_name = name from report_coloumns (nolock) where link_col = @iLC
         EXEC X_GET_TABLE_NAME @cur_alias_name OUTPUT -- получили новый алиас
                        insert into #col_names (name,link_col,alias) values(@cur_col_name,@iLC,@cur_alias_name)
                        set @cNewCol = '_'+ltrim(rtrim(convert(varchar(254),@iLC)))
                        set @selFields = @selFields + @cNewCol + ','
                        set @cES = 'create table '+@cur_alias_name+' ( nn int, [' + @cNewCol + '] varchar(8000) )'
                        execute(@cES) -- добавили столбец
--                 end
                select @cCodeForm = code from report_forms where link_form = @iLink_Form
                select @cNameTab = name from report_tables where link_table = @iLink_Table
                select @iVal_Type = Val_Type from report_tables (nolock) where link_table = @iLink_Table
                if @iLC = (select link_code_col from report_tables where link_table = @iLink_Table)
                    set @IsCodeCol = 1
                else
                    set @IsCodeCol = 0

                ---------------------------------------------------------------
                -- работаем с блоками данных. блок определяется совокупностью фомы и таблицы
                set @cES = '
                insert into '+@cur_alias_name+' ( nn, '+@cNewCol+')
                select res.nn,(
                    case    when '+convert(varchar,@iVal_Type)+' = 0
                            then (
                                case    when '+convert(varchar,@IsEdited)+' = 1
                                        then (
                                            case    when exists(select top 1 str_val from report_string_all where link_saved_form = res.lsf and link_col = '+convert(varchar,@iLC)+' and convert(varchar(50),link_row) = res.link_row and str_val <> '''')
                                                    then (select top 1 str_val from report_string_all where link_saved_form = res.lsf and link_col = '+convert(varchar,@iLC)+' and convert(varchar(50),link_row) = res.link_row and str_val <> '''')
                                                    else (select top 1 formula from report_formula where link_col = '+convert(varchar,@iLC)+' and convert(varchar(50),link_row) = res.link_row)
                                            end
                                        )
                                        else (select top 1 formula from report_formula where link_col = '+convert(varchar,@iLC)+' and convert(varchar(50),link_row) = res.link_row)
                                end
                            )
                            else (
                                select top 1 (case when '+convert(varchar,@IsCodeCol)+' = 1 then code_row else str_val end) 
                                from #report_dinamics_res where (link_col = '+convert(varchar,@iLC)+' OR '+convert(varchar,@IsCodeCol)+' = 1) and Code_Row = res.key_col and Link_SF = res.lsf
                            )
                    end
                )
                from #restab as res
                where res.form = '''+convert(varchar,@cCodeForm)+''' and res.tab = '''+convert(varchar,@cNameTab)+''''
                execute(@cES)
   
                set @i = @i + 1
                set @iLC = 0
                select @iLC = lc, @iLink_Table = lt, @iLink_Form = lf from @t_text_cols where numb = @i
        end 
--------------------------------------------------
if @calledfrom = 0 begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Построение сводной таблицы'', percents = 65'
    execute(@strProgressExec)
end
set @cES = ''
update #col_names
set @cES = @cES + 'left join '+ alias + ' on res.nn = '+alias+'.nn '

declare @StrSel varchar(8000),
	@strWhere varchar(8000),
	@varKScKbkTable varchar(50)

    UPDATE report_selection_an
    SET @selFields = @selFields + CODE + ','
    SET @selFields = @selFields + 'summa'


SET @StrSel = 'SELECT '+@selFields+' FROM #restab as res '+@cES   --- для временной было INSERT INTO dbo.drop_me_in_february_please
if 	@calledfrom	<> 0 begin -- если вызов произошел из тонкого, возвращаем весь список
	execute(@StrSel)
end
else begin -- иначе, смотрим не пустые ли строчки с ап 
	select @res_set_num = count(*) from #restab
	if (len(left(@col_an_str,len(@col_an_str)-1))= 0 and len(left(@col_an_str,len(@row_an_str)-1))= 0) or @res_set_num = 0 begin -- в случае когда обе строчки пустые или результирующая таблица пуста, т.е. ап не заданы
		-- предупреждаем, что выдаём весь набор 
		set @j = (@res_set_num / 65534) + case when (@res_set_num % 65534) > 0 then 1 else 0 end
		select 0 as res, null as col_num, null as col_set, null as col_lists, null as row_num, null as row_set, null as row_lists, @j as [count], @j as lists
		-- и выдаём его
		set @i = 1
		while @i !> @j begin
			set @strWhere = ' where res.nn between ' + cast((((@i-1) * 65534)+1) as varchar(30)) + ' and ' + cast((@i * 65534) as varchar(30))
			execute(@StrSel + @strWhere)
			set @i = @i + 1
		end
	end
	---------------------------------------------------------------------------------------------------------
	else begin -- иначе запускаем процедуру генерации сводной таблицы
--         declare @str_my varchar(1000)
--         set @str_my = 'select * into Drop_me from ( '+@StrSel+' ) as s'
--         print @str_my
--         execute(@str_my)
--		   print '@col_an_str = '+@col_an_str 
--		   print '@row_an_str = '+@row_an_str 
--		   print '@StrSel = '+@StrSel 
		exec RT_PIVOT_TABLE @col_an_str, @row_an_str, @StrSel, null, 0, 1/*0 - новая выборка; 1 - старая выборкаии*/--, @cProgressTable
	end
end

set @cES = ''										---
update #col_names									-- --	
set @cES = @cES + alias + ','						-- ---
													--  ---
if @cES <> ''										--   ---- здесь удаляются динамически созданные временные таблицы
begin												--  ---
    set @cES = substring(@cES,1,len(@cES)-1)		-- ---
    execute('drop table ' + @cES)					-- --
end													---

exec DropTempTable '#report_dinamics_res'
exec DropTempTable '#restab'
exec DropTempTable '#col_names'
exec DropTempTable '#selectedBOK'
exec DropTempTable '#selectedKBK'
exec DropTempTable '#selectedAtr'
exec DropTempTable '#code_row'
exec DropTempTable '#report_summa'
---------------------------------------------------------------------------------------------------------------------------------------------------------
if @calledfrom = 0 begin
    set @strProgressExec = 'update '+@cProgressTable+' set msg = ''Передача данных на клиент'', percents = 100'
    execute(@strProgressExec)
end

GO


GRANT EXECUTE ON dbo.[RM_REPORT_SELECTION] TO PUBLIC

GO



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

GO


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

	c Кейсистемс (Keysystems), 2007

*******************************************************************************/
CREATE PROCEDURE [dbo].[RO_CALC_DETAIL] 
	@varKSiLSF		INT,
	@varKSiLT		INT = NULL,
	@varKSiOrderCol	INT = 0, -- внутренний порядок
	@varKScCodeRow	varchar(50) = ''
AS

DECLARE @ldEnd		  DATETIME,
		@ldBegin      DATETIME,
		@liYear       INT,
		@ADM_CODE	  CHAR(3),
		@dCALC_DATE	  DATETIME,
		@iDEP_LINK	  INT,
		@LF		int, @LT int,
		@tmpStr		varchar(8000),
		@LC			int,
		@CodeForm	varchar(30),
		@orderCol	tinyint,
		@bid		varchar(100),
		@nabor_filter varchar(100),
		@iLinkCalcForm INT,
		@iForm737 tinyint

if exists(select * from dbo.REPORT_FORMS RF 
					inner join dbo.REPORT_SAVED_FORMS RSF on RF.Link_Form = RSF.Link_Form and RSF.Link_Saved_Form = @varKSiLSF
					where left(RF.CODE,7) = '0503737')
	set @iForm737 = 1
else	
	set @iForm737 = 0

declare @temp_nastr table (	link int, [Link_Col] int NOT NULL , [Code_Row] varchar(50) NOT NULL, [Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_dt int, link_kt int, dt_ekr varchar(1000), kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint, orderCol tinyint)
declare @temp_nastr_xor table (	link int, [Link_Col] int NOT NULL , [Code_Row] varchar(50) NOT NULL, [Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_dt int, link_kt int, dt_ekr varchar(1000), kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, dt_kt tinyint, orderCol tinyint)
declare @temp_nastr_rest table (	link int, [Link_Col] int NOT NULL , [Code_Row] varchar(50) NOT NULL,[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000), [type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint, orderCol tinyint)
declare @temp_nastr_rest_xor table (link int, [Link_Col] int NOT NULL , [Code_Row] varchar(50) NOT NULL,[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000), [type] tinyint, type_kbk tinyint, dt_kt tinyint, orderCol tinyint)
declare @filter_kbk table (kbk varchar(30))
declare @t_Col table (Link_Col int, orderCol tinyint)

create table #t_PROV (signa varchar(10), orderCol varchar(10), KBK varchar(50), DT varchar(50), KT varchar(50),
	DATE_PROV varchar(10),  SUMMA varchar(100), COMMENT VARCHAR (254))
create table #t_Rest_Begin (signa varchar(10), orderCol varchar(10), KBK varchar(50), ACCOUNT varchar(50),
	DATE_REST varchar(10), SUMMA varchar(100))
create table #t_Rest_End (signa varchar(10), orderCol varchar(10), KBK varchar(50), ACCOUNT varchar(50),
	DATE_REST varchar(10), SUMMA varchar(100))

------------------------------------------------------------------------------------------
-------- ЧИТАЕМ ДАННЫЕ ОТЧЕТА

select @LF = RSF.Link_Form, 
		@iDEP_LINK 	= Link_Organization, 
		@ldEnd		= Begin_Date + 1,
		@dCALC_DATE = Begin_Date, 
		@liYear		= YEAR(Begin_Date),
		@ldBegin	= dbo.DateBeginOfYear(Begin_Date),
		@CodeForm	= RF.Code
from report_saved_forms RSF join report_forms RF on RSF.Link_Form = RF.Link_Form and RSF.link_saved_form = @varKSiLSF

SET @iLinkCalcForm = dbo.RK_GET_NASTR_CALC_REPORT (@varKSiLSF,0)

-- select @iLinkCalcForm

/*
if @iLinkCalcForm is null 
	RETURN 0
*/

SET @varKScCodeRow = LTRIM (RTRIM (@varKScCodeRow))

if @varKSiLT is NULL or isnull(@varKSiOrderCol,0) = 0
	insert @t_Col (Link_Col, orderCol)
	select Link_Col, Export_Order
	from report_coloumns RC join report_tables RT on RC.Link_Table = RT.Link_Table
	where RT.Link_Form = @LF
else
begin
	insert @t_Col (Link_Col, orderCol)
	select Link_Col, Export_Order
	from report_coloumns where link_table = @varKSiLT and (orders = @varKSiOrderCol or isnull(@varKSiOrderCol, 0) = 0)
end

SET @ADM_CODE = Null
IF @iDEP_LINK is not null
	SELECT @ADM_CODE = LEFT(LTRIM(dbo.rn_get_atr_value(@varKSiLSF, 'REPORTS_ATR_ADM')),3)

IF @ADM_CODE = '' OR @ADM_CODE = '000'
	SET @ADM_CODE = Null

select @nabor_filter = dbo.rn_get_atr_value(@varKSiLSF,'REPORTS_FILTER_KBK')

select @nabor_filter = REPLACE (@nabor_filter, 'Не отобрано', '')

insert @filter_kbk (kbk)
select code from dbo.rn_view_filter 
where link_self in (select link from dbo.rn_view_filter_nabor where '№' + LTRIM(RTRIM(STR(orders))) + ' - ' + Name = @nabor_filter)

if isnull(@nabor_filter, '') = ''
	insert @filter_kbk (kbk)
	values ('1')

--select * from @t_Col

---------------------------------------------------------------------
----- ПОЛУЧАЕМ ВЫБОРКУ ИЗ ТАБЛИЦЫ НАСТРОЕК

insert @temp_nastr 
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign],
	DT.link , KT.link, dt_ekr, kt_ekr,
	[type], type_kbk, mask_kbk, dt_kt,
	RC.orderCol
from dbo.REPORT_CALC C 
INNER JOIN @t_Col RC on RC.Link_Col = C.Link_Col
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
left join dbo.s_accounts DT on
	DT.Code like case when CR.DT_Mask = '%' or rtrim (CR.DT_Mask) = '' then 'x' else rtrim (CR.DT_Mask) + '%' end
left join dbo.s_accounts KT on
	KT.Code like case when CR.KT_Mask = '%' or rtrim (CR.KT_Mask) = ''then 'x' else rtrim (CR.KT_Mask) + '%' end
WHERE C.LINK_UP = @iLinkCalcForm
	AND [sign] in (1,2) and CR.[type] = 1 
	AND (rtrim (CR.DT_Mask) = '' OR CR.DT_Mask = '%' OR rtrim (CR.DT_Mask) <> '' AND DT.LINK IS NOT NULL)
	AND (rtrim (CR.KT_Mask) = '' OR CR.KT_Mask = '%' OR rtrim (CR.KT_Mask) <> '' AND KT.LINK IS NOT NULL)

insert @temp_nastr_xor -- проводки, которые мы исключаем 
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign], DT.link , KT.link, dt_ekr, kt_ekr, [type], type_kbk, dt_kt, orderCol
from dbo.report_calc C 
	join @t_Col RC on RC.Link_Col = C.Link_Col
	join dbo.report_calc_rows CR on CR.Link_calc = C.link
	left join dbo.s_accounts DT on DT.Code like CR.DT_Mask 
	left join dbo.s_accounts KT on KT.Code like CR.KT_Mask 
where [sign] = 3 and CR.[type] = 1 

insert @temp_nastr_rest 
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign], case when DT.link is NULL then KT.link else DT.link end, case when DT.link is NULL then kt_ekr else dt_ekr end, [type], type_kbk, mask_kbk, dt_kt, orderCol
from dbo.report_calc C 
	join @t_Col RC on RC.Link_Col = C.Link_Col
	join dbo.report_calc_rows CR on CR.Link_calc = C.link
	left join dbo.s_accounts DT on DT.Code like case when CR.DT_Mask = '%' OR CR.DT_Mask = '' then 'x' else CR.DT_Mask + '%' end
	left join dbo.s_accounts KT on KT.Code like case when CR.KT_Mask = '%' OR CR.KT_Mask = '' then 'x' else CR.KT_Mask + '%'  end
where  CR.[type] in (2,3) and [sign] in (1,2) 

insert @temp_nastr_rest_xor
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign], case when DT.link is NULL then KT.link else DT.link end, case when DT.link is NULL then kt_ekr else dt_ekr end,  [type], type_kbk , dt_kt, orderCol
from dbo.report_calc C 
	join @t_Col RC on RC.Link_Col = C.Link_Col
	join dbo.report_calc_rows CR on CR.Link_calc = C.link
	left join dbo.s_accounts DT on DT.Code like case when CR.DT_Mask = '%' OR CR.DT_Mask = '' then 'x' else CR.DT_Mask + '%' end
	left join dbo.s_accounts KT on KT.Code like case when CR.KT_Mask = '%' OR CR.KT_Mask = '' then 'x' else CR.KT_Mask + '%'  end
where  CR.[type] in (2,3) and [sign] = 3 


/*
if not exists(select top 1 * from @temp_nastr) and not exists(select top 1 * from @temp_nastr_rest)
	return
*/
----------------------------------------------------------------------
-- ПОЛУЧАЕМ ТО ИЗ ЧЕГО СЧИТАЕМ
---------------- проводки ----------------------------
insert #t_PROV (signa, orderCol, KBK, DT, KT, DATE_PROV,  SUMMA, COMMENT)
SELECT CASE [SIGN] WHEN 1 THEN '+' WHEN 2 THEN '-' ELSE '' END, 
		LTRIM(STR(TMP.orderCol)),
--		KBK.CODE,
	CASE WHEN TMP.Code_Row <> '' THEN TMP.Code_Row
		ELSE
			 dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', TMP.Mask_KBK) = 0 THEN ''
						ELSE LEFT (TMP.Mask_KBK, CHARINDEX ('#', TMP.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(KBK.CODE,'.','')),'') + '00000000000000000', 30)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6)
--			+ LEFT(ISNULL(REPLACE(CASE TMP.DT_KT when 0 THEN SAD.CODE ELSE SAK.CODE END,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(case dt_kt when 0 then DTS.CODE else KTS.CODE END, '') + '000', 3) 
			+ LEFT(ISNULL(case dt_kt when 0 then DTE.CODE else KTE.CODE END, '') + '000', 3), TMP.Mask_KBK)
		END,
	SAD.CODE,
	SAK.CODE,

	CONVERT (VARCHAR (10), G.DATE_PROV, 104),
	G2.SUMMA,
	CONVERT (VARCHAR (254), RTRIM (dbo.JurnalProvGetDocKind (G.LINK, G.OBJECT)))
		+ ISNULL (' № ' + LTRIM (RTRIM (G.NUMBER)), '')
		+ ISNULL (' от ' + CONVERT (VARCHAR (10), G.DATE, 104), '')  

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)


LEFT JOIN dbo.G_PROV_AP DT ON (DT.LINK_UP = G2.LINK
	AND DT.DB_KR = 0)
LEFT JOIN dbo.G_PROV_AP KT ON (KT.LINK_UP = G2.LINK
	AND KT.DB_KR = 1)

LEFT JOIN dbo.S_ACCOUNTS SAD ON (SAD.LINK = DT.ACCOUNT)
LEFT JOIN dbo.S_ACCOUNTS SAK ON (SAK.LINK = KT.ACCOUNT)

LEFT JOIN dbo.KOSGU DTS ON (DTS.Link = DT.SGU)
LEFT JOIN dbo.KOSGU DTE ON (DTE.Link = DT.EKR)
LEFT JOIN dbo.KOSGU KTS ON (KTS.Link = KT.SGU)
LEFT JOIN dbo.KOSGU KTE ON (KTE.Link = KT.EKR)

INNER JOIN @TEMP_NASTR TMP ON (TMP.LINK_DT = DT.ACCOUNT OR TMP.LINK_DT IS NULL)
		AND (TMP.LINK_KT = KT.ACCOUNT OR TMP.LINK_KT IS NULL)
	AND (@iForm737 = 0 and dbo.RO_LIKE_LIST(DTS.Code, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '' or @iForm737 = 1)
	AND (@iForm737 = 0 and dbo.RO_LIKE_LIST(KTS.Code, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '' or @iForm737 = 1)
	AND (@iForm737 = 1 and dbo.RO_LIKE_LIST(DTE.Code, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '' or @iForm737 = 0)
	AND (@iForm737 = 1 and dbo.RO_LIKE_LIST(KTE.Code, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '' or @iForm737 = 0)

LEFT JOIN dbo.S_ACCOUNTS SA ON (TMP.DT_KT = 0 AND SA.LINK = DT.ACCOUNT
	OR TMP.DT_KT = 1 AND SA.LINK = KT.ACCOUNT)

LEFT JOIN dbo.KL_KBK KBK ON (TMP.dt_kt = 0 AND KBK.LINK = DT.KBK
		OR TMP.DT_KT = 1 AND KBK.LINK = KT.KBK)
LEFT JOIN @filter_kbk F on F.kbk = KBK.Code 
WHERE G.DATE_PROV BETWEEN @ldBegin AND @dCALC_DATE
	AND G.DEP = @iDEP_LINK
	AND (F.kbk IS NOT NULL
		OR isnull(@nabor_filter, '') = '')
	AND (TMP.TYPE_KBK = 0 
		OR (TMP.TYPE_KBK & KBK.[TYPE]) / KBK.[TYPE] = 1)
	AND not exists(select top 1 *
			from @temp_nastr_xor xor
			where xor.link = tmp.link and 
				xor.link_dt = dt.account and xor.link_kt = kt.account
				and (CHARINDEX(RTRIM(DTS.Code), xor.dt_ekr) > 0
					or RTRIM(isnull(DTS.Code,'')) like RTRIM(xor.dt_ekr) + '%') 
				and (RTRIM(isnull(KTS.Code,'
		')) like RTRIM(xor.kt_ekr) + '%' or CHARINDEX(RTRIM(KTS.Code),xor.kt_ekr) > 0)) -- исключаем
order by G.DATE_PROV
-- SELECT * FROM #t_PROV
/*	SELECT [sign] = case [sign] when 1 then '+' when 2 then '-' else '' end,
			[orderCol] = LTRIM(STR(TMP.orderCol)),
			[KBK] = LEFT(ISNULL(LTRIM(REPLACE(KBK.CODE,'.','')),'') + '00000000000000000', 17) + LEFT(ISNULL(case dt_kt when 1 then DTS.CODE else KTS.CODE end, '') + '000', 3),
			[DT] = DSA.Code,
			[KT] = KSA.Code,
			[DATE] = convert(varchar(10), G.DATE_PROV, 104),
			[SUMMA] = dbo.rn_convert_number(case [sign] when 1 then G2.SUMMA when 2 then - G2.SUMMA else 0 end, 2, ' ')
	FROM 
		dbo.G_PROV G INNER JOIN dbo.G_PROV1 G1 
			ON (G.DATE_PROV BETWEEN @ldBegin AND @dCALC_DATE
			AND G.LINK = G1.LINK_UP) and G.DEP = @iDEP_LINK
		INNER JOIN dbo.G_PROV2 G2 ON (G2.LINK_UP = G1.LINK)
		INNER JOIN dbo.G_PROV_AP DT ON (DT.LINK_UP = G2.LINK AND DT.DB_KR = 0)
		INNER JOIN dbo.G_PROV_AP KT ON (KT.LINK_UP = G2.LINK AND KT.DB_KR = 1)
		LEFT JOIN dbo.KOSGU DTS ON DTS.Link = DT.EKR
		LEFT JOIN dbo.KOSGU KTS ON KTS.Link = KT.EKR
		iNNER JOIN @temp_nastr TMP ON (DT.ACCOUNT = link_dt or link_dt is NULL) and (KT.ACCOUNT = link_kt or link_kt is NULL) and (dbo.RO_LIKE_LIST(DTS.Code, dt_ekr) > 0 or dt_ekr = '') and (dbo.RO_LIKE_LIST(KTS.Code, kt_ekr) > 0 or kt_ekr = '')
		INNER JOIN dbo.KL_KBK KBK ON case dt_kt when 1 then DT.KBK else KT.KBK end = KBK.LINK and TMP.TYPE_KBK & (case KBK.[TYPE] when 3 then 4 when 4 then 8 else KBK.[TYPE] end) > 0  and (@ADM_CODE= left(ltrim(KBK.CODE),3) OR @ADM_CODE IS NULL)
		INNER JOIN @filter_kbk F on KBK.Code = F.kbk or isnull(@nabor_filter, '') = ''
		LEFT JOIN dbo.S_ACCOUNTS DSA ON DT.ACCOUNT = DSA.Link
		LEFT JOIN dbo.S_ACCOUNTS KSA ON KT.ACCOUNT = KSA.Link
	where not exists(select top 1 * from @temp_nastr_xor xor where xor.link_dt = dt.account and xor.link_kt = kt.account and  (CHARINDEX(RTRIM(DTS.Code),xor.dt_ekr) > 0 or RTRIM(isnull(DTS.Code,'')) like RTRIM(xor.dt_ekr) + '%')  and (RTRIM(isnull(KTS.Code,'')) like RTRIM(xor.kt_ekr) + '%' or CHARINDEX(RTRIM(KTS.Code),xor.kt_ekr) > 0)) -- исключаем

*/

----------------- остатки ------------------------------
while exists(select top 1 * from @temp_nastr_rest)
begin
	select top 1 @orderCol = orderCol from @temp_nastr_rest order by orderCol

	set @bid = 'calc_col_' + LTRIM(RTRIM(STR(@orderCol)))

	insert dbo.buffer(ID, Link)
	select @bid, link_account
	from @temp_nastr_rest
	where @orderCol = orderCol

	-- остаток на начало периода
	insert #t_Rest_Begin (signa, orderCol, KBK, ACCOUNT, DATE_REST, SUMMA)
	select [sign] = case [sign] when 1 then '+' when 2 then '-' else '' end,
			[orderCol] = LTRIM(STR(@orderCol)), 	
			CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
					+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 30)
					+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
					+ LEFT(ISNULL(S.CODE,'') + '000', 3) 
					+ LEFT(ISNULL(E.CODE,'') + '000', 3), R.Mask_KBK)
			END,
	
			[ACCOUNT] = SA.Code,
			[DATE] = convert(varchar(10), INDATE, 104),
			[SUMMA] = dbo.rn_convert_number(sum(CASE when(SA.S_PASSIVE = 1 and [sign] = 1) OR (SA.S_ACTIVE = 1 and [sign] = 2)
				then  k_summa - d_summa
			else d_summa - k_summa end),2,' ')
	from dbo.ARestTableByDateAccounts(@ldBegin, @bid) A
	INNER JOIN @temp_nastr_rest R on R.link_account = account and R.orderCol = @orderCol and R.[Type] = 2
	LEFT JOIN dbo.KL_KBK K on K.Link = A.KBK
	LEFT JOIN @filter_kbk F on F.kbk = K.Code 
	left join dbo.KOSGU S on (S.Link = A.SGU) --and (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
	left join dbo.KOSGU E on E.Link = A.EKR
	left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	where dep_link = @iDEP_LINK
		AND (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
		and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and (dbo.RO_LIKE_LIST(S.Code, R1.ekr) > 0  or R1.ekr = '') and R1.link = R.link)
		AND (R.TYPE_KBK = 0 
			OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		AND (F.kbk IS NOT NULL
			OR isnull(@nabor_filter, '') = '')
	group by SA.Code,
		CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 30)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'') + '000', 3)
			+ LEFT(ISNULL(E.CODE,'') + '000', 3), R.Mask_KBK)
		END,
		case [sign] when 1 then '+' when 2 then '-' else '' end,
		convert(varchar(10), INDATE, 104)
	
	-- остаток на конец периода
	insert #t_Rest_End (signa, orderCol, KBK, ACCOUNT, DATE_REST, SUMMA)
	select [sign] = case [sign] when 1 then '+' when 2 then '-' else '' end,
			[orderCol] = LTRIM(STR(@orderCol)), 	
			[KBK] = CASE
					WHEN R.Code_Row <> '' THEN R.Code_Row
					ELSE
					+ dbo.RA_Mask(CASE 
								WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
								ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
							END 
					+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 30)
					+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
					+ LEFT(ISNULL(S.CODE,'') + '000', 3) 
					+ LEFT(ISNULL(E.CODE,'') + '000', 3), R.Mask_KBK)
				END,
			[ACCOUNT] = SA.Code,
			[DATE] = convert(varchar(10), INDATE, 104),
			[SUMMA] = dbo.rn_convert_number(sum(CASE when(SA.S_PASSIVE = 1 and [sign] = 1) OR (SA.S_ACTIVE = 1 and [sign] = 2)
				then  k_summa - d_summa
			else d_summa - k_summa end),2,' ')
	from dbo.ARestTableByDateAccounts(@ldEnd, @bid) A
		join @temp_nastr_rest R on R.link_account = account and R.orderCol = @orderCol and R.[Type] = 3
		left join dbo.KL_KBK K on K.Link = A.KBK and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end)>0)
		LEFT JOIN @filter_kbk F on F.kbk = K.Code 
		left join dbo.KOSGU S on (S.Link = A.EKR)  -- and (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
		left join dbo.KOSGU E on E.Link = A.EKR
		left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	where dep_link = @iDEP_LINK
		and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and (dbo.RO_LIKE_LIST(S.Code, R1.ekr) > 0 or R1.ekr ='') and R1.link = R.link)
		AND (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
		AND (R.TYPE_KBK = 0 
			OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		AND (F.kbk IS NOT NULL
			OR isnull(@nabor_filter, '') = '')
	group by SA.Code,
		CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 30)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'') + '000', 3) 
			+ LEFT(ISNULL(E.CODE,'') + '000', 3), R.Mask_KBK)
		END,
		case [sign] when 1 then '+' when 2 then '-' else '' end,convert(varchar(10), INDATE, 104)

	delete @temp_nastr_rest where orderCol = @orderCol

	exec dbo.BufferClear @bid
end

UPDATE #t_Prov SET KBK = REPLACE (KBK, '#', '')
UPDATE #t_Rest_Begin SET KBK = REPLACE (KBK, '#', '')
UPDATE #t_Rest_End SET KBK = REPLACE (KBK, '#', '')

delete #t_Prov where KBK <> @varKScCodeRow and isnull(@varKScCodeRow, '') <> '' 
delete #t_Rest_Begin where KBK <> @varKScCodeRow and isnull(@varKScCodeRow, '') <> '' 
delete #t_Rest_End where KBK <> @varKScCodeRow and isnull(@varKScCodeRow, '') <> '' 

-- для протокола HTML
CREATE TABLE #protokol_HTML ([order] Integer, [type] Integer, [html] VarChar(8000))
set @tmpStr = 'Протокол расчета для формы: ' + @codeForm + ' Графа: ' + LTRIM(STR(@orderCol)) + ' Строка: ' + @varKScCodeRow
exec HTMLReport @nMode = 0, @cWorkTableName = '#protokol_HTML', @cRepHeader = @tmpStr

if exists(select top 1 * from #t_Prov)
begin
	  exec dbo.HTMLReport @nMode     = 1,@cWorkTableName  = '#protokol_HTML', @cDataDesc    = '<font size=5>Корреспонденция счетов</font>', @cDataTableName  = '#t_Prov',@cShowFields  = 
	'<field name=''signa''  WRAP=''1''></field>
	 <field name=''KBK'' WRAP=''1''></field>
	 <field name=''DT''  WRAP=''1''></field>
	 <field name=''KT''  WRAP=''0''></field>
	<field name=''SUMMA''  WRAP=''0''></field>
	<field name=''COMMENT''  WRAP=''0''></field>
	 <field name=''DATE_PROV''  WRAP=''1''></field>'
	, @cFieldsDesc  = 'Знак|Строка|Дебет|Кредит|Сумма|Документ|Дата пров.', @cGroupFields = 'orderCol|KBK', @cGroupDesc = 'Колонка: @orderCol  Строка: @KBK'
end

if exists(select top 1 * from #t_Rest_Begin)
begin
	  exec dbo.HTMLReport @nMode     = 1,@cWorkTableName  = '#protokol_HTML', @cDataDesc    = '<font size=5>Остатки на начало года</font>', @cDataTableName  = '#t_Rest_Begin',@cShowFields  = 
	'<field name=''signa''  WRAP=''1''></field>
	 <field name=''KBK''  WRAP=''1''></field>
	 <field name=''ACCOUNT''  WRAP=''1''></field>
	<field name=''SUMMA''  WRAP=''0''></field>'
	, @cFieldsDesc  = 'Знак|Строка|Счет|Сумма', @cGroupFields = 'orderCol|KBK', @cGroupDesc = 'Колонка: @orderCol  Строка: @KBK'
end

if exists(select top 1 * from #t_Rest_End)
begin
	  exec dbo.HTMLReport @nMode     = 1,@cWorkTableName  = '#protokol_HTML', @cDataDesc    = '<font size=5>Остатки на конец года</font>', @cDataTableName  = '#t_Rest_End',@cShowFields  = 
	'<field name=''signa''  WRAP=''1''></field>
	 <field name=''KBK''  WRAP=''1''></field>
	 <field name=''ACCOUNT''  WRAP=''1''></field>
	<field name=''SUMMA''  WRAP=''0''></field>'
	, @cFieldsDesc  = 'Знак|Строка|Счет|Сумма', @cGroupFields = 'orderCol|KBK', @cGroupDesc = 'Колонка: @orderCol  Строка: @KBK'
end
	
	select * from #protokol_HTML order by [order]

	drop table #t_Prov
	drop table #t_Rest_Begin
	drop table #t_Rest_End



GO


GRANT EXECUTE ON dbo.[RO_CALC_DETAIL] TO PUBLIC

GO



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

GO
CREATE PROCEDURE dbo.XK_NASTR_NEW_PLAN_ACCOUNTS
		(@BUF_NAME		VARCHAR (254) = '')
AS
BEGIN

	Declare @kassa int,
		@BB datetime,
		@BE datetime,

		@BB_old datetime,
		@BE_old datetime

	SELECT @BB_old = BEGINDATE,
		@BE_old = ENDDATE
	FROM dbo.ADMIN_INFO

	Select @kassa = LINK from dbo.S_OBJECTS Where CODE = 'KASSA'
	SELECT @BB = convert(datetime, '19000101', 112), @BE = convert(datetime, '21000101', 112)
	EXECUTE dbo.I_SET_ADMIN_DATE @kassa, @BB, @BB, @BE

	SET @BUF_NAME = ISNULL (@BUF_NAME, '')

	-- НАСТРОЙКИ ПЛАНА СЧЕТОВ --- 
	DECLARE 
		@KVD varchar (1),
		@KBK VARCHAR (30),  
		@ZABALANCE tinyint,
		@VKR tinyint,
		@KD tinyint,
		@KIVF tinyint,
		@KIVNF tinyint,
		@SINTH CHAR (3),
		@ANALIT CHAR (2),
		@AP TINYINT,
		@KSU TINYINT, @P_KASSA TINYINT, @EKR_ANALIT char (3), @EKR TINYINT, @NOMEN TINYINT,
		@INV TINYINT, @EMP TINYINT, @DEP TINYINT, @DOP TINYINT,
		@ACCT TINYINT, @OSNOV TINYINT, @SUB TINYINT,
		@cJO CHAR (2), @P_CONTROL TINYINT,
		@DEP_ACC TINYINT,
		@intJO	INT,
		@TMC INT,
		@intKBK_TYPE	TINYINT,
		@intP_EKR	TINYINT,
		@int_EKR0	INT,
		@S_ACCTIVE	TINYINT,
		@S_PASSIVE	TINYINT,
		@KAU		TINYINT,
		@MZ 		tinyint,
		@INDATE 	tinyint,
		@P_DATE 	TINYINT,
		@NOMEN_TYPE	TINYINT,
		@AP_KBK		TINYINT,

		@intROW_COUNT	INT,
		@intLINK_SELF	INT,
		@strName_Acct	VARCHAR (254),
		@strSGU CHAR (3),
		@intBUH_TYPE TINYINT,

		@intKVD	TINYINT, 
		@intMAX_KVD	TINYINT,
		@intBUH_TYPE_SOURCE	TINYINT,
		@iADDED_500		TINYINT,
		@iLOOP_COUNT	TINYINT
		

-- Тип КБК биты: 0  - ФКР, 1 - КД, 2 - КИВФ, 3 - КИВнФ
		
	/* --- НАСТРОЙКИ СФОРМИРОВАННОГО ПЛАНА СЧЕТОВ --- */
	DECLARE #ACCT_NASTR CURSOR STATIC LOCAL 
		FOR SELECT T1.SINTH, T1.ANALITH, T1.S_ACTIVE, T1.ZABALANCE,
				T1.KBK, T1.KSU,
				T1.P_KASSA, T1.EKR0, T1.AP_EKR,
				T1.AP_NOMEN, T1.AP_INV,
				T1.AP_EMP, AP_DEP, T1.AP_DOP,
				T1.AP_DEP_ACC, T1.AP_DOC,
				T1.AP_SUB, T1.P_NOCONTROL,
				T1.AP_TMC, T1.AP_INDATE,
				T1.AP_KAU, T1.JONUM,
				T1.[NAME],
				T1.P_DATE, T1.NOMEN_TYPE,
				T1.BUH_TYPE
			FROM dbo.S_ACCOUNTS_NASTR T1
			INNER JOIN dbo.S_ACCOUNTS_NEW_CONV T2 ON
				(
				(@BUF_NAME = ''
					OR @BUF_NAME <> '' AND T2.BUF_NAME = @BUF_NAME)
				AND T2.SINTH_NEW = T1.SINTH
				AND T2.ANALITH_NEW = T1.ANALITH
				AND T2.ZABALANCE = T1.ZABALANCE
				)
			ORDER BY T1.ZABALANCE, T1.SINTH, T1.ANALITH 
	--
	OPEN #ACCT_NASTR
	--
	FETCH #ACCT_NASTR
		INTO @SINTH, @ANALIT, @AP, @ZABALANCE,
			@KBK, @KSU, 
			@P_KASSA, @EKR_ANALIT, @EKR, 
			@NOMEN, @INV,  
			@EMP, @DEP, @DOP,
			@DEP_ACC, @OSNOV,
			@SUB, @P_CONTROL,
			@TMC, @INDATE,
			@KAU, @cJO,
			@strName_Acct,
			@P_DATE, @NOMEN_TYPE,
			@intBUH_TYPE

	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @intKBK_TYPE = CASE
					WHEN CHARINDEX ('КРБ', @KBK) > 0 THEN 1
					ELSE 0
				END
				+ CASE
					WHEN CHARINDEX ('КД', @KBK) > 0 THEN 2
					ELSE 0
				END
				+ CASE
					WHEN CHARINDEX ('КИФ', @KBK) > 0 THEN 12
					ELSE 0
				END

		IF @intKBK_TYPE = 0
			SET @AP_KBK = 0
		ELSE	
			SET @AP_KBK = 1
	
		IF @AP = 0	-- Пассивный счет --
		BEGIN
			SET @S_ACCTIVE	= 0
			SET @S_PASSIVE	= 1
		END
		ELSE
		BEGIN
			SET @S_ACCTIVE	= 1
			SET @S_PASSIVE	= 0
		END
	
--		SET @P_KASSA = 0
		SET @int_EKR0 = (SELECT LINK FROM dbo.KOSGU WHERE CODE = @EKR_ANALIT)
		IF @int_EKR0 IS NOT NULL
		BEGIN
			SET @EKR = 1
			SET @intP_EKR = 1
		END
		ELSE
			SET @intP_EKR = 0

		--- Источники финансирования ---
		IF @SINTH = '108' OR @SINTH = '104' AND LEFT (@ANALIT, 1) = '5'
			SET @intMAX_KVD = 1
		ELSE
			SET @intMAX_KVD = 7
			
		-- Для настройки 500 раздела ПС --
		IF @ZABALANCE = 0 AND @SINTH LIKE '50%' AND @ANALIT <> '00' AND @ANALIT <> ''
			SELECT
				@iADDED_500	=	1,
				@iLOOP_COUNT	=	1
		ELSE
			SELECT
				@iADDED_500	=	0,
				@iLOOP_COUNT	=	4

		WHILE @iLOOP_COUNT < 5
		BEGIN
			SET @intKVD = 0
			
			IF @iADDED_500 = 1
				SET @ANALIT = CONVERT (VARCHAR (2), @iLOOP_COUNT) + RIGHT (@ANALIT, 1)

			WHILE @intKVD <= @intMAX_KVD
			BEGIN 
				IF @intKVD = 3
					SET @intKVD = @intKVD + 1
					
				IF @intKVD = 1 OR @intKVD = 3
					SET @intBUH_TYPE = 1

				IF @intKVD = 2 OR @intKVD > 3
					SET @intBUH_TYPE = 6
					
				SET @KVD = CASE
								WHEN @intKVD = 0 THEN ''
								ELSE CONVERT (VARCHAR (1), @intKVD)
							END
										
				/* ---!!!Настройка аналитики у существующих счетов!!!--- */
				UPDATE dbo.S_ACCOUNTS SET [NAME] = CASE
									WHEN ISNULL (@strName_Acct, '') = '' THEN [NAME]
									ELSE LTRIM (@strName_Acct)
							END,
							KBK_TYPE = ISNULL (@intKBK_TYPE, KBK_TYPE),
							p_EKR = @intP_EKR,
							ANALIT_EKR = @int_EKR0,
							p_KASSA = @P_KASSA,
							KSU = @KSU, 
							p_NOCONTROL = @P_CONTROL,
							S_ACTIVE = ISNULL (@S_ACCTIVE, S_ACTIVE),
							S_PASSIVE = ISNULL (@S_PASSIVE, S_PASSIVE),
			
							/* --- АНАЛИТИКА --- */
							AP_KBK = @AP_KBK,
							ap_NOMEN = CASE
									WHEN @NOMEN = 0 AND ap_NOMEN = 1 
										AND EXISTS (SELECT * FROM dbo.G_PROV_AP WHERE ACCOUNT = SA.LINK AND NOMEN IS NOT NULL)
										AND EXISTS (SELECT * FROM dbo.SALDO WHERE ACCOUNT = SA.LINK AND NOMEN IS NOT NULL)
										THEN 1
									ELSE @NOMEN
								END,
							NOMEN_TYPE = CASE
									WHEN @NOMEN = 0 AND ap_NOMEN = 1
										AND EXISTS (SELECT * FROM dbo.G_PROV_AP WHERE ACCOUNT = SA.LINK AND NOMEN IS NOT NULL)
										AND EXISTS (SELECT * FROM dbo.SALDO WHERE ACCOUNT = SA.LINK AND NOMEN IS NOT NULL)
										THEN 1
									ELSE @NOMEN_TYPE
								END,
							ap_INV = CASE
									WHEN @INV = 0 AND ap_INV = 1
										AND EXISTS (SELECT * FROM dbo.G_PROV_AP WHERE ACCOUNT = SA.LINK AND INV IS NOT NULL)
										AND EXISTS (SELECT * FROM dbo.SALDO WHERE ACCOUNT = SA.LINK AND INV IS NOT NULL)
										THEN 1
									ELSE @INV
								END,
							ap_TMC = CASE
									WHEN @TMC = 0 AND ap_TMC = 1
										AND EXISTS (SELECT * FROM dbo.G_PROV_AP WHERE ACCOUNT = SA.LINK AND TMC IS NOT NULL)
										AND EXISTS (SELECT * FROM dbo.SALDO WHERE ACCOUNT = SA.LINK AND TMC IS NOT NULL)
										THEN 1
									ELSE @TMC
								END,
							ap_DEP = CASE
									WHEN @DEP = 0 AND ap_DEP = 1
										AND EXISTS (SELECT * FROM dbo.G_PROV_AP WHERE ACCOUNT = SA.LINK AND DEP IS NOT NULL)
										AND EXISTS (SELECT * FROM dbo.SALDO WHERE ACCOUNT = SA.LINK AND DEP IS NOT NULL)
										THEN 1
									ELSE @DEP
								END,
							ap_EKR = CASE
									WHEN @EKR = 0 AND ap_EKR = 1
										AND EXISTS (SELECT * FROM dbo.G_PROV_AP WHERE ACCOUNT = SA.LINK AND EKR IS NOT NULL)
										AND EXISTS (SELECT * FROM dbo.SALDO WHERE ACCOUNT = SA.LINK AND EKR IS NOT NULL)
										THEN 1
									ELSE @EKR
								END,
							ap_KAU = CASE
									WHEN @KAU = 0 AND ap_KAU = 1
										AND EXISTS (SELECT * FROM dbo.G_PROV_AP WHERE ACCOUNT = SA.LINK AND KAU IS NOT NULL)
										AND EXISTS (SELECT * FROM dbo.SALDO WHERE ACCOUNT = SA.LINK AND KAU IS NOT NULL)
										THEN 1
									ELSE @KAU
								END,
							ap_EMP = CASE
									WHEN @EMP = 0 AND ap_EMP = 1
										AND EXISTS (SELECT * FROM dbo.G_PROV_AP WHERE ACCOUNT = SA.LINK AND EMP IS NOT NULL)
										AND EXISTS (SELECT * FROM dbo.SALDO WHERE ACCOUNT = SA.LINK AND EMP IS NOT NULL)
										THEN 1
									ELSE @EMP
								END,
							ap_AP1 = CASE
									WHEN @OSNOV = 0 AND ap_AP1 = 1
										AND EXISTS (SELECT * FROM dbo.G_PROV_AP WHERE ACCOUNT = SA.LINK AND AP1 IS NOT NULL)
										AND EXISTS (SELECT * FROM dbo.SALDO WHERE ACCOUNT = SA.LINK AND AP1 IS NOT NULL)
										THEN 1
									ELSE @OSNOV
								END,
							ap_AP2 = CASE
									WHEN @DOP = 0 AND ap_AP2 = 1
										AND EXISTS (SELECT * FROM dbo.G_PROV_AP WHERE ACCOUNT = SA.LINK AND AP2 IS NOT NULL)
										AND EXISTS (SELECT * FROM dbo.SALDO WHERE ACCOUNT = SA.LINK AND AP2 IS NOT NULL)
										THEN 1
									ELSE @DOP
								END,
							ap_DEP_ACC = CASE
									WHEN @DEP_ACC = 0 AND ap_DEP_ACC = 1
										AND EXISTS (SELECT * FROM dbo.G_PROV_AP WHERE ACCOUNT = SA.LINK AND DEP_ACC IS NOT NULL)
										AND EXISTS (SELECT * FROM dbo.SALDO WHERE ACCOUNT = SA.LINK AND DEP_ACC IS NOT NULL)
										THEN 1
									ELSE @DEP_ACC
								END,
							ap_SUB = CASE
									WHEN @SUB = 0 AND ap_SUB = 1
										AND EXISTS (SELECT * FROM dbo.G_PROV_AP WHERE ACCOUNT = SA.LINK AND SUB IS NOT NULL)
										AND EXISTS (SELECT * FROM dbo.SALDO WHERE ACCOUNT = SA.LINK AND SUB IS NOT NULL)
										THEN 1
									ELSE @SUB
								END,
							ap_INDATE = CASE
									WHEN @INDATE = 0 AND ap_INDATE = 1
										AND EXISTS (SELECT * FROM dbo.G_PROV_AP WHERE ACCOUNT = SA.LINK AND INDATE IS NOT NULL)
										AND EXISTS (SELECT * FROM dbo.SALDO WHERE ACCOUNT = SA.LINK AND INDATE IS NOT NULL)
										THEN 1
									ELSE @INDATE
								END,
							BUH_TYPE = CASE
									WHEN SA.cSOURCE = '0' THEN 4
									ELSE @intBUH_TYPE
								END	
				FROM dbo.S_ACCOUNTS SA
				WHERE cSINTH = @SINTH
					AND cANALIT = @ANALIT
					AND cSOURCE = @KVD
					AND ZABALANS = @ZABALANCE
			
				/* ---!!!Добавление отсутсвующих счетов!!!--- */
				SELECT @intROW_COUNT = @@ROWCOUNT
				IF @intROW_COUNT = 0	
				BEGIN
					SET @S_ACCTIVE = ISNULL (@S_ACCTIVE, 0)
					SET @S_PASSIVE = ISNULL (@S_PASSIVE, 0)
		
					IF ISNULL (@strName_Acct, '') = ''
						SET @strName_Acct = 'Счет ' + @SINTH
		
					IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS WHERE cSINTH = @SINTH	/* -- Отсутвует раздел -- */	
									AND cANALIT = ''
									AND cSOURCE = ''
									AND cUSER = ''
									AND ZABALANS = @ZABALANCE)
					BEGIN
						SET @intLINK_SELF = NULL
						EXECUTE dbo.[X_PLAN_ACCOUNTS_GET_PARENT_LINK] @intLINK_SELF OUTPUT, 
																			@SINTH, 
																			'', 
																			'', 
																			'', 
																			@ZABALANCE
		
						IF @intLINK_SELF IS NOT NULL
							INSERT INTO dbo.S_ACCOUNTS ([NAME], cSINTH, cANALIT, cSOURCE, cUSER, LINK_SELF,
										KBK_TYPE, p_EKR, ANALIT_EKR,
										p_KASSA, KSU, p_NOCONTROL, S_ACTIVE, S_PASSIVE, 
										ap_EKR, ap_NOMEN, NOMEN_TYPE, ap_INV, ap_EMP, ap_DEP, ap_AP2,
										ap_DEP_ACC, ap_AP1, ap_SUB, ap_KAU, ZABALANS, AP_KBK,
										BUH_TYPE)
							VALUES (@strName_Acct, @SINTH, @ANALIT, @KVD, '',
									@intLINK_SELF, @intKBK_TYPE, @intP_EKR, @int_EKR0,
									@P_KASSA, @KSU, 0, @S_ACCTIVE, @S_PASSIVE,
									@EKR, @NOMEN, @NOMEN, @INV, @EMP, @DEP, @DOP, 0,
									@DEP_ACC, @OSNOV, @KAU, @ZABALANCE, @AP_KBK,
									@intBUH_TYPE)
					END		/* -- Отсутвует раздел -- */
		
					IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS WHERE cSINTH = @SINTH	/* -- Отсутвует аналитический счет -- */	
									AND cANALIT = @ANALIT
									AND cSOURCE = ''
									AND cUSER = ''
									AND ZABALANS = @ZABALANCE)
					BEGIN
						SET @intLINK_SELF = NULL
						EXECUTE dbo.[X_PLAN_ACCOUNTS_GET_PARENT_LINK] @intLINK_SELF OUTPUT, 
																			@SINTH, 
																			'', 
																			@ANALIT, 
																			'', 
																			@ZABALANCE
		
						IF @intLINK_SELF IS NOT NULL
							INSERT INTO dbo.S_ACCOUNTS ([NAME], cSINTH, cANALIT, cSOURCE, cUSER, LINK_SELF,
									KBK_TYPE, p_EKR, ANALIT_EKR,
									p_KASSA, KSU, p_NOCONTROL, S_ACTIVE, S_PASSIVE, 
									ap_EKR, ap_NOMEN, NOMEN_TYPE, ap_INV, ap_EMP, ap_DEP, ap_AP2,
									ap_DEP_ACC, ap_AP1, ap_SUB, ap_KAU, ZABALANS, ap_kbk,
									BUH_TYPE)
							VALUES (@strName_Acct, @SINTH, @ANALIT, '', '',
									@intLINK_SELF, @intKBK_TYPE, 0, NULL,
									0, @KSU, 0, @S_ACCTIVE, @S_PASSIVE,
									@EKR, @NOMEN, @NOMEN, @INV, 0, @DEP, 0, 0,
									0, 0, @KAU, @ZABALANCE, @AP_KBK,
									@intBUH_TYPE)
					END		/* -- Отсутвует аналитический счет -- */
		
					IF NOT EXISTS (SELECT * FROM dbo.S_ACCOUNTS WHERE cSINTH = @SINTH	/* -- Отсутвует счет C ИФ -- */	
									AND cANALIT = @ANALIT
									AND cSOURCE = @KVD
									AND cUSER = ''
									AND ZABALANS = @ZABALANCE)
					BEGIN
						SET @intLINK_SELF = NULL
						EXECUTE dbo.[X_PLAN_ACCOUNTS_GET_PARENT_LINK] @intLINK_SELF OUTPUT, 
																			@SINTH, 
																			@KVD, 
																			@ANALIT, 
																			'', 
																			@ZABALANCE

						IF @KVD = '0'
							SET @intBUH_TYPE_SOURCE = 4
						ELSE
							SET @intBUH_TYPE_SOURCE = @intBUH_TYPE
		
						IF @intLINK_SELF IS NOT NULL
							INSERT INTO dbo.S_ACCOUNTS ([NAME], cSINTH, cANALIT, cSOURCE, cUSER, LINK_SELF,
									KBK_TYPE, p_EKR, ANALIT_EKR,
									p_KASSA, KSU, p_NOCONTROL, S_ACTIVE, S_PASSIVE, 
									ap_EKR, ap_NOMEN, NOMEN_TYPE, ap_INV, ap_EMP, ap_DEP, ap_AP2,
									ap_DEP_ACC, ap_AP1, ap_SUB, ap_KAU, ZABALANS, AP_KBK,
									BUH_TYPE)
							VALUES (@strName_Acct, @SINTH, @ANALIT, @KVD, '',
									@intLINK_SELF, @intKBK_TYPE, @intP_EKR, @int_EKR0,
									@P_KASSA, @KSU, 0, @S_ACCTIVE, @S_PASSIVE,
									@EKR, @NOMEN, @NOMEN, @INV, @EMP, @DEP, @DOP, 0,
									@DEP_ACC, @OSNOV, @KAU, @ZABALANCE, @AP_KBK,
									@intBUH_TYPE_SOURCE)
					END		 -- Отсутвует аналитический счет -- 
				END			---!!!Добавление отсутсвующих счетов!!!--- 
		
				---!!!Настройка ЖО!!!--- 
				SET @intJO = (SELECT LINK FROM dbo.JOURNAL_OPERATION WHERE CODE = @cJO)
				IF @intJO IS NOT NULL
					INSERT INTO dbo.JOURNAL_OPERATION_ACCOUNTS
					SELECT [JURN_LINK] = @intJO, 
						[ACCOUNT] = SA.LINK,
						[GK] = CONVERT (BIT, 0)
					FROM dbo.S_ACCOUNTS SA
					WHERE SA.cSINTH = @SINTH
						AND SA.cANALIT = @ANALIT
						AND SA.ZABALANS = @ZABALANCE
						AND NOT EXISTS (SELECT * FROM dbo.JOURNAL_OPERATION_ACCOUNTS T
									WHERE T.JURN_LINK = @intJO
										AND T.ACCOUNT = SA.LINK)

				SET @intKVD = @intKVD + 1
			END
			
			SET @iLOOP_COUNT = @iLOOP_COUNT + 1
		END		--	WHILE @iLOOP_COUNT > 0
			

		FETCH NEXT FROM #ACCT_NASTR
			INTO @SINTH, @ANALIT, @AP, @ZABALANCE,
				@KBK, @KSU, 
				@P_KASSA, @EKR_ANALIT, @EKR, 
				@NOMEN, @INV,  
				@EMP, @DEP, @DOP,
				@DEP_ACC, @OSNOV,
				@SUB, @P_CONTROL,
				@TMC, @INDATE,
				@KAU, @cJO,
				@strName_Acct,
				@P_DATE, @NOMEN_TYPE,
				@intBUH_TYPE
	END
	
	CLOSE #ACCT_NASTR
	DEALLOCATE #ACCT_NASTR

	UPDATE dbo.S_ACCOUNTS SET BUH_TYPE = 7 WHERE LINK_SELF IS NULL

	UPDATE SA SET BUH_TYPE = ISNULL (SAN.BUH_TYPE, 7)
	FROM dbo.S_ACCOUNTS SA
	LEFT JOIN dbo.S_ACCOUNTS_NASTR SAN ON (SAN.SINTH = SA.cSINTH
		AND SAN.ANALITH = SA.cANALIT)
	WHERE SA.BUH_TYPE = 0

	EXECUTE I_SET_ADMIN_DATE @kassa, @BB_OLD, @BB_OLD, @BE_OLD 

/*
	EXEC dbo.SA_152N_NASTR_PAYS

	EXEC dbo.XK_152N_INS_CORRECT_PROV
*/
	EXEC dbo.X_SET_OPTION 'XK_CONV_NASTR_SA_157N', 0, '1'

	RETURN 0
END



GO


GRANT EXECUTE ON dbo.[XK_NASTR_NEW_PLAN_ACCOUNTS] TO PUBLIC

GO


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


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

GO

/*
    © Кейсистемс (Keysystems), 2007
    Процедура формирования строк и значений формы 0503125
*/

CREATE PROCEDURE dbo.RT_CALC_0503125G
@LSF int,
@table int
AS

declare @cAccount varchar(9),  -- девять знаков: [1] - код вида деятельности [2..6] - счёт(синт+ан) [7..9] - СГУ
		@cSource char(1),
		@cSinth char(3),
		@cAnalit char(2),
		@cSGU char(3),
		@iLinkAccount int,
		@dBeginDate datetime,
		@dEndDate datetime,
		@dEndDate_pl datetime,
		@iThisDep int,
		@iCorrDep int,
		@i int,
		@j int,
		@iLink_col int,
		@code_row varchar(50),
		@float_val numeric(20,4),
		@str_val varchar(250),
		@cVidForm varchar(250),
		@cVidFormCode tinyint,
		@nPeriod_Type tinyint,
		@cStrSql varchar(8000),
		@nabor_filter varchar(100)
		
declare @table1 table(key_prov int, kbk int, account int, sgu int, db_kr tinyint, account_korr int, sgu_korr int, kpb_korr int, summa numeric(20,4))
create table #table2(nn int IDENTITY(1,1),Name_bp varchar(254), kod_bp varchar(10), ppp char(3), el_bud char(2), okato char(11), KBK varchar(30), Code_Acc varchar(9), summa_db numeric(20,4), summa_kr numeric(20,4),korr_acc varchar(10), link varchar(254), dnd tinyint, key_prov int)
create table #table3(nn int IDENTITY(1,1),Name_bp varchar(254), kod_bp varchar(10), ppp char(3), el_bud char(2), okato char(11), KBK varchar(30), Code_Acc varchar(9), summa_db numeric(20,4), summa_kr numeric(20,4),korr_acc varchar(10), link varchar(254), dnd tinyint, key_prov int)
declare @filter_kbk table (kbk varchar(30))

-- вытаскиваем данные из сохранённой формы
set @cAccount = ltrim(rtrim(replace(dbo.RN_GET_ATR_VALUE(@LSF,'REPORTS_ATR_ACC_2011'),'.','')))
set @cSource = substring(@cAccount,1,1) -- вид деятельности
set @cSinth = substring(@cAccount,2,3)  -- синтетический счёт
set @cAnalit = substring(@cAccount,5,2) -- аналитическая составляющая
set @cSGU = substring(@cAccount,7,3)    -- СГУ

--set @cVidForm = ltrim(rtrim(dbo.RN_GET_ATR_VALUE(@LSF,'REPORTS_ATR_NAFO')))
--select @cVidFormCode = link from dbo.RT_VIEW_NAFO_125 where [Name] = @cVidForm

-- print '@cAccount = '+@cAccount
-- print '@cSource = '+@cSource
-- print '@cSinth = '+@cSinth
-- print '@cAnalit = '+@cAnalit
-- print '@cSGU = '+@cSGU
-- print '@cVidForm = '+@cVidForm
-- print '@cVidFormCode = '+cast(@cVidFormCode as varchar(3))

-- определяем период (если в январе формируем, то берём весь предыдущий год не включая 31 декабря)
select @dEndDate = Begin_Date, @nPeriod_Type = period_type from dbo.report_saved_forms where link_saved_form = @LSF

select @dBeginDate = dbo.DateBeginOfYear(@dEndDate)

-- set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then (@dBeginDate - (datepart(dd,@dBeginDate))) - 1 else @dBeginDate /*- (datepart(dd,@dBeginDate))*/ end
-- set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')


--if @nPeriod_Type <> 1 
--	set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then @dBeginDate - 1 else @dBeginDate end
--else
--	set @dEndDate = @dBeginDate
--
--	set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')

-- получаем линк указанного счёта
select @iLinkAccount = link from dbo.s_accounts
where cSource = @cSource
and cSinth = @cSinth
and cAnalit = @cAnalit

-- линк организации которая собственно формирует справку
select @iThisDep = Link_Organization from dbo.report_saved_forms where link_saved_form = @LSF

-- print '@dBeginDate = '+cast(@dBeginDate as varchar(100))
-- print '@dEndDate = '+cast(@dEndDate as varchar(100))
-- print '@iLinkAccount = '+cast(@iLinkAccount as varchar(10))
-- теперь надо получить список корресп. счетов
if (((@cSinth = '206' and @cAnalit = '51') or (@cSinth = '205' and @cAnalit = '51') or (@cSinth = '207' and (@cAnalit = '11' or @cAnalit = '12' or @cAnalit = '13'))) and @cSGU = '000') /*and @nPeriod_Type = 1*/ begin
	set @dEndDate_pl = dateadd(d,1,@dEndDate)
	insert into @table1
	select 1,kbk, account, sgu, 1, null, null, dep, /*d_summa - */k_summa - d_summa
	from dbo.ARestTableByDate(@dEndDate_pl, @iLinkAccount)
	where dep_link = @iThisDep
end
else begin
	insert into @table1
	select
	C.link,
	D.kbk,
	D.account,
	D.sgu,
	D.DB_KR,
	E.account,
	E.sgu,
	/* Boch, брать организацию из извещения
	(case
	when D.Dep is not NULL and D.Dep <> A.Dep then
	D.Dep
	else (case when E.Dep is not NULL and E.Dep <> A.Dep then E.Dep else NULL end)
	end) as kpb_korr,*/
	(case
	when D.Dep is not NULL and D.Dep <> A.Dep then D.Dep
	when E.Dep is not NULL and E.Dep <> A.Dep then E.Dep
	when OS.Dep_pass is not NULL and OS.Dep_pass <> A.Dep then OS.Dep_pass
	when OS.Dep_receive is not NULL and OS.Dep_receive <> A.Dep then OS.Dep_receive
	else isnull((SELECT GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA, dbo.S_OBJECTS SO WHERE GPDA.DOC_LINK = A.LINK AND GPDA.OBJECT = SO.LINK and SO.CODE = 'NOTICE_LINK_DEP_RECEIVER'), NULL) end)
	as kpb_korr,
	C.Summa
	from dbo.g_prov as A
	inner join dbo.g_prov1 as B
	on A.link = B.link_up
	and A.date_prov between @dBeginDate and @dEndDate
	and A.Dep = @iThisDep
	inner join dbo.g_prov2 as C
	on B.link = C.link_up
	inner join dbo.g_prov_ap as D
	on C.link = D.link_up
	inner join dbo.g_prov_ap as E
	on D.link_up = E.link_up
	and D.account <> E.account
	and D.account = @iLinkAccount
	and (D.sgu = (select link from dbo.kosgu where code = @cSGU) or '000' = @cSGU)
	left join dbo.G_PROV_OS1 OS on OS.LINK_OS1 = A.LINK
end
--select * from @table1

select @nabor_filter = REPLACE (dbo.rn_get_atr_value(@LSF,'REPORTS_FILTER_KBK'), 'Не отобрано', '')
insert @filter_kbk (kbk)   
Select LINK FROM rn_get_filter(@LSF,'REPORTS_FILTER_KBK')


-- теперь необходимо удалить из всего набора таблицы @table1 строчки с ненужными КБК (в зависимости от того для какой таблицы производится рассчёт)
delete from @table1
where kbk not in (select [LINK] 
					from dbo.kl_kbk K
					LEFT JOIN @filter_kbk F on K.LINK = F.KBK
					where @table = case when [TYPE] in (4,8) then 3 when [TYPE] = 1 then 2 when [TYPE] = 2 then 1 else [TYPE] end
					AND (F.kbk IS NULL OR isnull(@nabor_filter, '') = ''))

-- в таблице #table2
insert into #table2
select
(case
when exists(select [FULL_Name] from dbo.Departments where link = kpb_korr)
then (select [FULL_Name] from dbo.Departments where link = kpb_korr)
else 'корреспондент_не_указан'
end),
(case
when exists(select [CODE] from dbo.Departments where link = kpb_korr)
then (select [CODE] from dbo.Departments where link = kpb_korr)
else '0'
end),
(case
when exists(select [CODE] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr))
then (select [CODE] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr))
else '000'
end),
(case
when exists(select [CODE_EL] from dbo.kl_budg_type where link = (select top 1 [Link_Budg] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr)))
then (select [CODE_EL] from dbo.kl_budg_type where link = (select top 1 [Link_Budg] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr)))
else '00'
end),
--     (select [CODE] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr)),
--     (select [CODE_EL] from dbo.kl_budg_type where link = (select top 1 [Link_Budg] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr))),
(case
--when exists(select [OKATO] from dbo.Departments where link = kpb_korr)
--then (select left(replace([OKATO],' ',''),11) from dbo.Departments where link = kpb_korr)
when exists(select [OKTMO] from dbo.Departments where link = kpb_korr)
then (select left(replace([OKTMO],' ',''),8) from dbo.Departments where link = kpb_korr)
else ' '
end),
(case
when exists(select replace(replace(rtrim(code),'.',''),' ','') from dbo.kl_kbk where link = kbk)
then (select replace(replace(rtrim(code),'.',''),' ','') from dbo.kl_kbk where link = kbk)
else '_не_заполнен_кбк_'
end),
	@cSource+@cSinth+@cAnalit+
(case
when exists(select [code] from dbo.kosgu where link = sgu)
then (select [code] from dbo.kosgu where link = sgu)
else '000'
end),
(case when db_kr = 0 then isnull(SUM(summa),0.0) else 0.0 end),
(case when db_kr = 1 then isnull(SUM(summa),0.0) else 0.0 end),
(select left(replace(code,'.',''),6) from dbo.s_accounts where link = account_korr)+
(case
when exists(select [code] from dbo.kosgu where link = sgu_korr)
then (select [code] from dbo.kosgu where link = sgu_korr)
else '000'
end),
(NULL),
(NULL),
MAX(key_prov)

from @table1
group by kbk, account, sgu, db_kr, account_korr, sgu_korr, kpb_korr

--select * from #table2
-- очищаем зёрна от плевел -----------------------------------------------------------

if  @cSinth = '304' AND @cAnalit = '04' AND @cSGU = '000' begin
	update #table2
	set ppp = '', el_bud = '', okato = ''
end

if  @cSinth = '401' AND @cAnalit = '10' AND (@cSGU = '241' or @cSGU = '180')begin
	update #table2
	set el_bud = '',okato = ''
end

if  (@cSinth = '206' AND @cAnalit = '51' and @cSGU = '000')	or (@cSinth = '205' AND @cAnalit = '51' and @cSGU = '000') or (@cSinth = '207' AND (@cAnalit = '11' or @cAnalit = '12' or @cAnalit = '13') and @cSGU = '000') begin
	update #table2
	set summa_db = -(coalesce(summa_db,0.0) - coalesce(summa_kr,0.0)), summa_kr = 0.0, korr_acc = ''
end

if  @cSinth = '301' AND @cSGU = '000'/*@cVidFormCode = 14*/ begin
	update #table2
	set summa_db = 0.0, korr_acc = ''
end

if  (@cSinth = '211' OR @cSinth = '212') AND @cAnalit = '00' AND (@cSGU = '560' or @cSGU = '660') begin
	update #table2
	set ppp = '', el_bud = '',summa_db = 0.0
end

if  (@cSinth = '308' OR @cSinth = '309') AND @cAnalit = '00' AND (@cSGU = '730' or @cSGU = '830') begin
	update #table2
	set ppp = '', el_bud = '',summa_db = 0.0
end
--устанавливаем признак денежный - неденежный ----------------------------------------
update #table2  
set dnd = 
(case
    when 
        right(left(korr_acc,6),5) in ('21002','30405') or
        right(korr_acc,3) in ('510','610')
    then 1 -- денежные рассчёты
    else 0 -- не денежные рассчёты             
 end)
--------------------------------------------------------------------------------------
if (((@cSinth = '206' and @cAnalit = '51') or (@cSinth = '205' and @cAnalit = '51') or (@cSinth = '207' and (@cAnalit = '11' or @cAnalit = '12' or @cAnalit = '13'))) and @cSGU = '000') begin
	set @cStrSql = '
	insert into #table3 (Name_bp,ppp,el_bud,okato,KBK,summa_db,summa_kr,korr_acc,link,dnd,key_prov)
	select Name_bp,ppp,el_bud,okato,KBK,sum(summa_db),sum(summa_kr),korr_acc,null,dnd,null from #table2
	where Name_bp <> ''корреспондент_не_указан'' 
	group by Name_bp,ppp,el_bud,okato,KBK,korr_acc,dnd
	order by Name_bp,ppp

	insert into #table3 (Name_bp,ppp,el_bud,okato,KBK,summa_db,summa_kr,korr_acc,link,dnd,key_prov)
	select Name_bp,ppp,el_bud,okato,KBK,sum(summa_db),sum(summa_kr),korr_acc,null,dnd,null from #table2
	where Name_bp = ''корреспондент_не_указан'' 
	group by Name_bp,ppp,el_bud,okato,KBK,korr_acc,dnd
	order by KBK'
end
else begin
	set @cStrSql = '
	insert into #table3 (Name_bp,ppp,el_bud,okato,KBK,Code_Acc,summa_db,summa_kr,korr_acc,link,dnd,key_prov)
	select Name_bp,ppp,el_bud,okato,KBK,Code_Acc,summa_db,summa_kr,korr_acc,link,dnd,key_prov from #table2
	where Name_bp <> ''корреспондент_не_указан''
	order by Name_bp,ppp

	insert into #table3 (Name_bp,ppp,el_bud,okato,KBK,Code_Acc,summa_db,summa_kr,korr_acc,link,dnd,key_prov)
	select Name_bp,ppp,el_bud,okato,KBK,Code_Acc,summa_db,summa_kr,korr_acc,link,dnd,key_prov from #table2
	where Name_bp = ''корреспондент_не_указан''
	order by KBK,Code_Acc'
end
execute(@cStrSql)

delete from #table3 where summa_db = 0.0 and summa_kr = 0.0

update #table3
set link = LEFT(RTRIM(ISNULL(ppp,''))+'000',3)+LEFT(RTRIM(isnull(okato,'')) + '           ',11)+LEFT(RTRIM(ISNULL(el_bud,''))+'00',2)+LEFT(substring(rtrim(isnull([KBK],'')),1,17)+'00000000000000000',17)+LEFT(RTRIM(ISNULL(korr_acc,''))+'000000000',9)+RIGHT('00000000' + LTRIM(CAST(ISNULL(nn,0) as VARCHAR(8))),8)
--set link = LEFT(RTRIM(ISNULL(ppp,''))+'   ',3)+LEFT(RTRIM(isnull(okato,'')) + '           ',11)+LEFT(RTRIM(ISNULL(el_bud,''))+'  ',2)+LEFT(substring(rtrim(isnull([KBK],'')),1,17)+'                 ',17)+LEFT(RTRIM(ISNULL(korr_acc,''))+'         ',9)+RIGHT('00000000' + LTRIM(CAST(ISNULL(nn,0) as VARCHAR(8))),8)
--set link = LEFT(RTRIM(ISNULL(ppp,''))+'000',3)+LEFT(RTRIM(isnull(okato,''))+'00000000000',11)+LEFT(RTRIM(ISNULL(el_bud,''))+'00',2)+LEFT(substring(rtrim(isnull([KBK],'')),1,17)+'00000000000000000',17)+LEFT(RTRIM(ISNULL(korr_acc,''))+'000000000',9)+RIGHT('00000000' + LTRIM(CAST(ISNULL(nn,0) as VARCHAR(8))),8)

-- удаляем только строчки, принадлежащие указанной таблице. Остальные, соответственно, не трогаем
delete from dbo.report_dinamics where Link_SF = @LSF and Link_Col in (select link_col from dbo.report_coloumns where link_table = (select link_table from dbo.report_tables where link_form = (select top 1 link_form from dbo.report_saved_forms where link_saved_form = @LSF) and Orders = @table))

if @table in (1,3) begin
SELECT 
[CODE] = [link], -- Код строки.
[COL1] = [Name_bp], -- Наименование контрагента
[COL2] = [ppp], -- ППП
[COL3] = [okato], -- ОКАТО
[COL4] = [el_bud], -- Элемент бюджета
[COL5] = substring(rtrim(isnull([KBK],'')),1,3), -- АДМ
[COL6] = substring(rtrim(isnull([KBK],'')),4,14), -- КБК
[COL7] = [summa_db], -- сумма дебет
[COL8] = [summa_kr], -- сумма кредит
[COL9] = [korr_acc], -- Код корреспондирующего счёта бюджетного учета
[COL10] = cast (isnull([dnd],'') as varchar), -- Признак платежа
[COL11]= [link], -- Код строки.
[COL12]= RIGHT('00000000' + LTRIM(CAST(ISNULL(nn,0) as VARCHAR(8))),8)
FROM #table3
ORDER BY [link]
end
else begin
SELECT 
[CODE] = [link], -- Код строки.
[COL1] = [Name_bp], -- Наименование контрагента
[COL2] = [ppp], -- ППП
[COL3] = [okato], -- ОКАТО
[COL4] = [el_bud], -- Элемент бюджета
[COL5] = substring(rtrim(isnull([KBK],'')),1,3), -- АДМ
[COL6] = substring(rtrim(isnull([KBK],'')),4,4), -- РзПр
[COL7] = substring(rtrim(isnull([KBK],'')),8,7), -- ЦСР
[COL8] = substring(rtrim(isnull([KBK],'')),15,3),-- ВР
[COL9] = [summa_db], -- сумма дебет
[COL10] = [summa_kr], -- сумма кредит
[COL11] = [korr_acc], -- Код корреспондирующего счёта бюджетного учета
[COL12] = cast (isnull([dnd],'') as varchar), -- Признак платежа
[COL13] = [link], -- Код строки.
[COL14] = RIGHT('00000000' + LTRIM(CAST(ISNULL(nn,0) as VARCHAR(8))),8)
FROM #table3
ORDER BY [link]
end

drop table #table2
drop table #table3


GO


GRANT EXECUTE ON dbo.[RT_CALC_0503125G] TO PUBLIC

GO



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

GO

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

CREATE PROCEDURE dbo.BK_REPORT_OSV_SYNT
	@varKSdDate1	DATETIME	,
	@varKSdDate2	DATETIME	,
	@varKScVal1 char(1), @varKSnOtborLink1 int	,
	@cVal_KBK char(1), @nOtborLinkKBK int,	-- Отбор КБК --
	@cVal_Dop char(1), @nOtborLinkDOP int,	-- Доп. кл-ция --
	@varKSnPRN_KBK	INT				,
	@varKSnPRN_SGU	INT	,
	@intTYPE_ACCT INT	,
	@intSVOD_ZB INT		,
	@intPRN_DOP	INT
AS
BEGIN
	SET @intTYPE_ACCT = ISNULL (@intTYPE_ACCT, 0)

	DECLARE	@varKSLINK_DEP	INT,
		@varKSDEP_CODE	VARCHAR (20),
		@varKSDEP_NAME	VARCHAR (254),
		@varKSDEP_OKPO	VARCHAR (20),
		@varKScDATE_NEXT	VARCHAR (10)

	SET @varKScDATE_NEXT = CONVERT (VARCHAR (10), DATEADD (DAY, 1, @varKSdDate2), 104)

	DECLARE @ACCT TABLE (LINK_ACCT [INT])

	IF LEN (@varKScVal1) > 0
		INSERT INTO @ACCT
		SELECT RECORD
		FROM OBJECT_VAR_ACCT
		WHERE LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO @ACCT
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode (DEFAULT, DEFAULT, DEFAULT, DEFAULT) ACCT
		WHERE @intTYPE_ACCT = 0
			OR (@intTYPE_ACCT = 1 AND ACCT.ZABALANS = 0)
			OR (@intTYPE_ACCT = 2 AND ACCT.ZABALANS = 1)

	--- ОТБОР ПО КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	--- ОТБОР ПО ДОП. КЛ-ЦИИ --- 
	DECLARE @TAB_DOP TABLE (LINK_DOP INT, DOP_CODE VARCHAR (20))
	
	IF @intPRN_DOP = 1
		IF LEN (@cVal_Dop) > 0
			INSERT INTO @TAB_DOP
			SELECT AP.LINK,
				AP.CODE
			FROM dbo.DOP_CLASSIF AP 
			INNER JOIN dbo.OBJECT_VAR_DOP_CLASSIF OVR ON (OVR.RECORD = AP.LINK)
			WHERE OVR.LINK_UP = @nOtborLinkDOP
		ELSE
			INSERT INTO @TAB_DOP
			SELECT LINK_AP, AP_CODE
			FROM dbo.BK_GetTableDictionByAP ('AP2')
	ELSE
		INSERT INTO @TAB_DOP (LINK_DOP, DOP_CODE)
		VALUES (0, '')

	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)
	SET @varKSLINK_DEP = dbo.BK_GetDepZB ()

	IF @intSVOD_ZB = 1 OR @varKSLINK_DEP IS NULL
		SET @varKSLINK_DEP = dbo.GetOwnDepLink()

	SELECT @varKSLINK_DEP = LINK,
		@varKSDEP_CODE = CODE,
		@varKSDEP_NAME = dbo.BK_GET_PRINT_DEP_NAME (LINK), 
		@varKSDEP_OKPO = OKPO
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @varKSLINK_DEP

	IF @intSVOD_ZB = 1
	BEGIN
		SET @varKSDEP_NAME = RTRIM (@varKSDEP_NAME) + ' (ЦБ)'
		SET @varKSLINK_DEP = NULL
	END

	DECLARE @TABLE1 TABLE (ACCOUNT [INT],
			KBK [INT], KOSGU [INT],
			AP2 INT,
			D_SUMMA [NUMERIC] (20,2),		
			K_SUMMA [NUMERIC] (20,2),		
			IN_SUMMA [NUMERIC] (20,2),		
			OUT_SUMMA [NUMERIC] (20,2))		

	INSERT INTO @TABLE1
	SELECT T1.ACCOUNT,
		CASE
			WHEN @varKSnPRN_KBK = 1 THEN T1.KBK
			ELSE 0
		END,
		CASE
			WHEN @varKSnPRN_SGU = 1 THEN T1.SGU
			ELSE 0
		END,
		CASE
			WHEN @intPRN_DOP = 1 THEN T1.AP2
			ELSE 0
		END,
		SUM (T1.D_SUMMA),
		SUM (T1.K_SUMMA),
		SUM (T1.IN_SUMMA),
		SUM (T1.OUT_SUMMA)
	FROM dbo.BK_GetTableOSVByDate (@varKSdDate1, @varKSdDate2, @varKSLINK_DEP) T1
	INNER JOIN @ACCT AC ON (AC.LINK_ACCT = T1.ACCOUNT)
	INNER JOIN @TAB_KBK T2 ON (T2.LINK_KBK = T1.KBK)
/*	WHERE (@intSVOD_ZB = 1
		OR (@intSVOD_ZB = 0 AND T1.DEP_LINK = @varKSLINK_DEP))
*/	GROUP BY T1.ACCOUNT,
		CASE
			WHEN @varKSnPRN_KBK = 1 THEN T1.KBK
			ELSE 0
		END,
		CASE
			WHEN @varKSnPRN_SGU = 1 THEN T1.SGU
			ELSE 0
		END,
		CASE
			WHEN @intPRN_DOP = 1 THEN T1.AP2
			ELSE 0
		END

	DECLARE @RESULT TABLE (ACCOUNT [INT],
			ACCT_CODE [VARCHAR] (60),
			DOP_CODE	VARCHAR (20),
			D_SUM [NUMERIC] (20,2),			
			K_SUM [NUMERIC] (20,2),			
			DIN_SUM [NUMERIC] (20,2),	KIN_SUM [NUMERIC] (20,2),		
			DOUT_SUM [NUMERIC] (20,2), KOUT_SUM [NUMERIC] (20,2),	
			ORGNAME [VARCHAR](254),
			NEXT_DATE [VARCHAR] (10))

	INSERT INTO @RESULT
	SELECT OSV.ACCOUNT,
		dbo.BK_GetAcctFullCode1 (OSV.ACCOUNT, OSV.KBK, OSV.KOSGU, @varKSnPRN_KBK, @varKSnPRN_SGU),
		D.DOP_CODE, 
		OSV.D_SUMMA,			
		OSV.K_SUMMA,			
		CASE 				
			WHEN SA.S_ACTIVE = 1 THEN OSV.IN_SUMMA
			ELSE 0
		END,			
		CASE 				
			WHEN SA.S_PASSIVE = 1 THEN OSV.IN_SUMMA
			ELSE 0
		END,			
		CASE 				
			WHEN SA.S_ACTIVE = 1 THEN OSV.OUT_SUMMA
			ELSE 0
		END,			
		CASE 				
			WHEN SA.S_PASSIVE = 1 THEN OSV.OUT_SUMMA
			ELSE 0
		END,			
		@varKSDEP_NAME,
		@varKScDATE_NEXT
	FROM @TABLE1 OSV
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = OSV.ACCOUNT)
	INNER JOIN @TAB_DOP D ON (D.LINK_DOP = OSV.AP2)
	WHERE (OSV.D_SUMMA <> 0)
		OR (OSV.K_SUMMA <> 0)
		OR (OSV.IN_SUMMA <> 0)
		OR (OSV.OUT_SUMMA <> 0)

	SELECT * FROM @RESULT ORDER BY ACCT_CODE, DOP_CODE

END




GO


GRANT EXECUTE ON dbo.[BK_REPORT_OSV_SYNT] TO PUBLIC

GO



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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE  PROCEDURE dbo.BK_PRINT_INV_CARD_F0504032_GRP
		@varKSc_BufferName	VARCHAR (100)
AS
BEGIN
	DECLARE	
		@varKSintLINK	INT,
		@varKSnCALC_RATE	NUMERIC (28,4),
		@varKSdDATE_WORK	DATETIME,
		@varKSdDATE_REST	DATETIME,
		@varKSACCT_CODE	VARCHAR (20),
		@varKSDEP		INT,
		@varKSDEP_CODE	VARCHAR (20),
		@varKSDEP_OKPO	VARCHAR (20),
		@varKSDEP_NAME	VARCHAR (254),
		@varKSEMP	INT,
		@varKSACCOUNT	INT,
		@varKSKBK	INT,
		@varKSEMP_CODE	VARCHAR (20),
		@varKSEMP_NAME	VARCHAR (254),
		@varKSSUB_CODE	VARCHAR (20),
		@varKSSUB_NAME	VARCHAR (254),
		@nBALANSE	NUMERIC (28,4),
		@BEGIN_DATE_USED DATETIME,
		@DATE_CALC_REST_AMORT	DATETIME,
		@DATE_AMORT	DATETIME,
		@SUMMA_AM	NUMERIC (28, 4),
		@REST_SUMMA_AM	NUMERIC (28, 4),
		@PREV_SUMMA_AM	NUMERIC (28, 4),
		@YEAR_AM	INT,
		@LAST_RECNO	INT,
		@intCOUNT_ROW	INT

	--- Список ОС для в группе ---		
	DECLARE @LIST_INV TABLE (INV INT,
		ISMAIN TINYINT)

	SELECT TOP 1 @varKSintLINK = LINK
	FROM dbo.BufferGetTableByID (@varKSc_BufferName)

	INSERT INTO @LIST_INV
	SELECT INV_LINK, MAIN_REC
	FROM dbo.XK_SELECT_INV_LIST_GRP (@varKSintLINK)

-- SELECT * FROM @LIST_INV

	SELECT @varKSdDATE_WORK = WORKDATE FROM USER_INFO
	SET @varKSdDATE_REST = DATEADD (DAY, 1, @varKSdDATE_WORK)

	DECLARE @varKSINV_REST TABLE
			(INV_LINK INT,
			ACCOUNT INT,
			ACCT_SINT VARCHAR (10),
			ACCT_CODE VARCHAR (20),
			DEP INT,
			SUB INT,
			EMP INT,
			INV INT,
			KBK INT,
			QTY NUMERIC (28,4),
			SUMMA NUMERIC (28,4))

	INSERT INTO @varKSINV_REST
	SELECT T1.INV,
		T1.ACCOUNT,
		SA.cSinth,
		SA.CODE,
		T1.DEP,
		T1.SUB,
		T1.EMP,
		T1.INV,
		T1.KBK,
		CASE 
			WHEN SA.S_ACTIVE = 1 THEN SUM (T1.D_QUANTITY)
			WHEN SA.S_PASSIVE = 1 THEN SUM (T1.K_QUANTITY)
		END,
		CASE 
			WHEN SA.S_ACTIVE = 1 THEN SUM (T1.D_SUMMA)
			WHEN SA.S_PASSIVE = 1 THEN SUM (T1.K_SUMMA)
		END
	FROM dbo.ARestTableByDate (@varKSdDATE_REST, DEFAULT) T1
	INNER JOIN @LIST_INV LST ON (LST.INV = T1.INV)
	INNER JOIN dbo.S_ACCOUNTS SA ON (T1.ACCOUNT = SA.LINK)
	GROUP BY T1.ACCOUNT, T1.DEP, T1.SUB, T1.EMP, T1.INV, T1.KBK, SA.S_ACTIVE, SA.S_PASSIVE, SA.cSinth, SA.CODE
--	HAVING T1.INV = @varKSintLINK

-- SELECT * FROM @varKSINV_REST

	SELECT TOP 1 @varKSACCT_CODE = ACCT_CODE,
			@varKSACCOUNT	= T1.ACCOUNT,
			@varKSKBK	= T1.KBK,
			@varKSDEP = DEP.LINK,
			@varKSDEP_CODE = DEP.CODE,
			@varKSDEP_NAME = DEP.NAME, 
			@varKSDEP_OKPO = DEP.OKPO,
			@varKSEMP = EMP.LINK,
			@varKSEMP_CODE = EMP.TAB,
			@varKSEMP_NAME = EMP.NAME_EMPL,
			@varKSSUB_CODE	= SUB.CODE,
			@varKSSUB_NAME	= SUB.[NAME],
			@nBALANSE = SUMMA
	FROM @varKSINV_REST T1
	LEFT OUTER JOIN dbo.DICTIONARY_DEPARTMENT DEP ON (DEP.LINK = T1.DEP)
	LEFT OUTER JOIN dbo.KU_EMPL_PLACING EMP ON (EMP.LINK = T1.EMP)
	LEFT OUTER JOIN dbo.DICTIONARY_SUBDIVISION SUB ON (SUB.LINK = T1.SUB)
	WHERE T1.INV_LINK = @varKSintLINK
		AND (T1.ACCT_SINT = '101'
			OR T1.ACCT_SINT = '102'
			OR T1.ACCT_SINT = '103')

	IF @varKSDEP IS NULL
		SELECT TOP 1 @varKSDEP = DEP.LINK,
			@varKSDEP_CODE = DEP.CODE,
			@varKSDEP_NAME = DEP.NAME, 
			@varKSDEP_OKPO = DEP.OKPO
		FROM dbo.DICTIONARY_DEPARTMENT DEP 
		WHERE DEP.LINK = COALESCE (dbo.BK_GetDepZB (), dbo.GetOwnDepLink ())

	SELECT @varKSnCALC_RATE = SUM (SUMMA)
	FROM @varKSINV_REST T1
	WHERE T1.ACCT_SINT = '104'

	--- ДВИЖЕНИЕ ОС ---
	DECLARE @TAB_MOVING TABLE (REC_NO INT IDENTITY, INV INT,
		DATE_ALL DATETIME,
		DATE_OP1 VARCHAR (10), JO_NUM1 VARCHAR (20),
		QTY1 NUMERIC (20,2), SUMMA1 NUMERIC (20,2),
		DATE_OP2 VARCHAR (10), JO_NUM2 VARCHAR (20),
		QTY2 NUMERIC (20,2), SUMMA2 NUMERIC (20,2)
		)

	--- ОПЕРАЦИИ ПОСТУПЛЕНИЯ --- 
	DECLARE @TAB_INPUT TABLE (INV INT,
		DATE_ALL DATETIME,
		DATE_OP1 VARCHAR (10), JO_NUM1 VARCHAR (20),
		QTY1 NUMERIC (20,2), SUMMA1 NUMERIC (20,2))

	INSERT INTO @TAB_INPUT (INV, DATE_ALL, DATE_OP1, JO_NUM1, QTY1, SUMMA1)
	SELECT distinct T1.INV,
		T1.DATE_OPER,
		CONVERT (VARCHAR (10), T1.DATE_OPER, 104),
		T1.JO_NUM,
		CASE WHEN (select COUNT(QTY) from dbo.BK_GetOperationsByOS (T1.INV, @varKSdDATE_WORK,
		'17.01#17.02#17.03#17.05#17.06#17.12#17.13') WHERE QTY <> 0 ) > 0  
			then (select SUM(QTY) from dbo.BK_GetOperationsByOS (T1.INV, @varKSdDATE_WORK,
		'17.01#17.02#17.03#17.05#17.06#17.12#17.13') WHERE QTY <> 0 ) 
			ELSE  t1.QTY END ,
		T1.SUMMA
	FROM dbo.BK_GetOperationsByOS (DEFAULT, @varKSdDATE_WORK,
		'17.01#17.02#17.03#17.05#17.06#17.12#17.13') T1  -- Поступление НФА
	INNER JOIN @LIST_INV INV ON (INV.INV = T1.INV)

 --SELECT * FROM @TAB_INPUT

	SET @intCOUNT_ROW = @@ROWCOUNT

	--- ОПЕРАЦИИ ВЫБЫТИЯ --- 
	DECLARE @TAB_OUTPUT TABLE (INV INT,
		DATE_ALL DATETIME,
		DATE_OP2 VARCHAR (10), JO_NUM2 VARCHAR (20),
		QTY2 NUMERIC (20,2), SUMMA2 NUMERIC (20,2))

	INSERT INTO @TAB_OUTPUT (INV, DATE_ALL, DATE_OP2, JO_NUM2, QTY2, SUMMA2)
	SELECT T1.INV,
		T1.DATE_OPER,
		CONVERT (VARCHAR (10), T1.DATE_OPER, 104),
		T1.JO_NUM,
		T1.QTY,
		T1.SUMMA
	FROM dbo.BK_GetOperationsByOS (DEFAULT, @varKSdDATE_WORK,
		'17.08#17.09#17.10#17.11#17.19') T1 -- Списание 
	INNER JOIN @LIST_INV INV ON (INV.INV = T1.INV)


	SET @intCOUNT_ROW = @intCOUNT_ROW + @@ROWCOUNT

	IF @intCOUNT_ROW = 0
		INSERT INTO @TAB_MOVING (INV, DATE_OP1, JO_NUM1, QTY1, SUMMA1,
			DATE_OP2, JO_NUM2, QTY2, SUMMA2)
		VALUES (@varKSintLINK, '', '', 0, 0, '', '', 0, 0)

	/* -- Переоценка -- */
	DECLARE @TAB_RECALL TABLE (REC_NO INT IDENTITY, DATE_OPER2 VARCHAR (10),
		JO_NUM2 VARCHAR (20), SUMMA2 NUMERIC (20,2))

	INSERT INTO @TAB_RECALL	
	SELECT CONVERT (VARCHAR (10), DATE_OPER, 104) AS DATE_OPER2,
		JO_NUM AS JO_NUM2,
		SUMMA AS SUMMA2
	FROM dbo.BK_GetOperationsByOS (@varKSintLINK, @varKSdDATE_WORK, '17.15') -- Положительная переоценка ОС
	UNION
	SELECT CONVERT (VARCHAR (10), DATE_OPER, 104) AS DATE_OPER2,
		JO_NUM AS JO_NUM2,
		SUMMA AS SUMMA2
	FROM dbo.BK_GetOperationsByOS (@varKSintLINK, @varKSdDATE_WORK, '17.16') -- Отрицательная переоценка ОС
	UNION 
	SELECT CONVERT (VARCHAR (10), DATE_OPER, 104) AS DATE_OPER2,
		JO_NUM AS JO_NUM2,
		SUMMA AS SUMMA2
	FROM dbo.BK_GetOperationsByOS (@varKSintLINK, @varKSdDATE_WORK, '17.17') -- Положительная переоценка амортизации ОС
	UNION 
	SELECT CONVERT (VARCHAR (10), DATE_OPER, 104) AS DATE_OPER2,
		JO_NUM AS JO_NUM2,
		SUMMA AS SUMMA2
	FROM dbo.BK_GetOperationsByOS (@varKSintLINK, @varKSdDATE_WORK, '17.18') -- Отрицательная переоценка амортизации ОС

	IF @@ROWCOUNT = 0
		INSERT INTO @TAB_RECALL	 (DATE_OPER2, JO_NUM2, SUMMA2) VALUES ('', '', 0)

--	SELECT * FROM @TAB_RECALL	

	DECLARE @TAB_AMORT TABLE (REC_NO INT IDENTITY,
			SUM_AM NUMERIC (28,4),
			YEAR_AM INT)

	SELECT @BEGIN_DATE_USED = DATE_BEGIN FROM dbo.BV_INVENTORY_CARD_DOP WHERE LINK_UP = @varKSintLINK

	IF @BEGIN_DATE_USED IS NULL
		SET @BEGIN_DATE_USED = @varKSdDATE_WORK
	
	SET @DATE_CALC_REST_AMORT = dbo.DateEndOfYear (@BEGIN_DATE_USED)
	SET @YEAR_AM = YEAR (@DATE_CALC_REST_AMORT)
	SET @PREV_SUMMA_AM = 0

	WHILE @YEAR_AM <= YEAR (@varKSdDATE_WORK)
	BEGIN
		SET @DATE_AMORT = DATEADD (DAY, 1, @DATE_CALC_REST_AMORT)
		SET @REST_SUMMA_AM = (SELECT SUM (T1.K_SUMMA)
					FROM dbo.ARestTableByDate (@DATE_AMORT, DEFAULT) T1
					INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = T1.ACCOUNT)
					WHERE T1.INV = @varKSintLINK
						AND SA.cSINTH = '104')

		IF ISNULL (@REST_SUMMA_AM, 0) <> 0
		BEGIN
			SET @SUMMA_AM = @REST_SUMMA_AM - @PREV_SUMMA_AM
			SET @PREV_SUMMA_AM = @REST_SUMMA_AM

			IF @SUMMA_AM > 0
			BEGIN
				INSERT INTO @TAB_AMORT (SUM_AM, YEAR_AM) VALUES (@SUMMA_AM, @YEAR_AM)
				SET @LAST_RECNO = @@IDENTITY
			END
		END

		SET @DATE_CALC_REST_AMORT = DATEADD (YEAR, 1, @DATE_CALC_REST_AMORT)
		SET @YEAR_AM = YEAR (@DATE_CALC_REST_AMORT)

	END

	IF @LAST_RECNO IS NULL
		INSERT INTO @TAB_AMORT (SUM_AM, YEAR_AM) VALUES (0, 0)		

--	SELECT * FROM @TAB_AMORT ORDER BY REC_NO
	-- ДВИЖЕНИЕ
	INSERT INTO @TAB_MOVING (INV)
	SELECT INV
	FROM @TAB_INPUT
	UNION 
	SELECT INV
	FROM @TAB_OUTPUT

	
	--- ВЫВОД ОСНОВНЫХ РЕКВИЗИТОВ ---
	-- Стоимость на группу объектов --
	SELECT @nBALANSE = SUM (SUMMA1)
	FROM @TAB_INPUT

	SELECT
		@varKSDEP AS DEP,
		ISNULL (@varKSDEP_CODE, '') AS DEP_CODE,
		ISNULL (@varKSDEP_OKPO, '') AS DEP_OKPO,
		ISNULL (@varKSDEP_NAME, '') AS DEP_NAME,
		ISNULL (@varKSEMP_CODE, '') AS EMP_CODE,
		ISNULL (@varKSEMP_NAME, '') AS EMP_NAME,
		ISNULL (@varKSSUB_CODE, '') AS SUB_CODE,
		ISNULL (@varKSSUB_NAME, '') AS SUB_NAME,
		T1.LINK,
		ISNULL (T1.CODE, '') AS INV_CODE,
		ISNULL (T1.NAME, '') AS INV_NAME,
--		ISNULL (@varKSACCT_CODE, ISNULL (T1.CODE_ACC, '')) AS ACCT_CODE,
		ISNULL (dbo.BK_GetAcctFullCode1 (@varKSACCOUNT, @varKSKBK, NULL, 1, 0), ISNULL (T1.CODE_ACC, '')) AS ACCT_CODE,
		ISNULL (T1.BALANCE, 0)	 AS FIRST_COST,
		ISNULL (@nBALANSE, 0) AS GRP_COST,
		GRP_TYPE = case when LEFT(ISNULL(T1.CODE_GRP,''),4) = '1011' then 'недвижимое имущество'
						WHEN LEFT(ISNULL(T1.CODE_GRP,''),4) = '1012' then 'особо ценное движимое имущество' 
						WHEN LEFT(ISNULL(T1.CODE_GRP,''),4) = '1013' then 'иное движимое имущество' 
						else '' END ,
		ISNULL (T2.CARD_NO, '') AS CARD_NO,
		ISNULL (T2.PASSPORT, '') AS PASSPORT,
		ISNULL (T2.PLANT_NUM, '') AS PLANT_NUM,
		ISNULL (T2.OTHER_NUM, '') AS OTHER_NUM,
		ISNULL (T2.CODE_OKOF, '') AS CODE_OKOF,
		ISNULL (CONVERT (VARCHAR (10), T2.DATE_PROD, 104), '') AS DATE_PROD,
		ISNULL (T2.FIXING, '') AS FIXING,
		ISNULL (T2.LOCATION, '') AS LOCATION,
		ISNULL (T2.MANUFACT, '') AS MANUFACT,		
		ISNULL (CONVERT (VARCHAR (10), T2.DATE_BEGIN, 104), '') AS DATE_BEGIN,
		ISNULL (T2.DOC_NUM, '') AS DOC_BEGIN,
		ISNULL (CONVERT (VARCHAR (10), T2.DATE_FILLING, 104), '') as DATE_FILL,
		(SELECT case when CONVERT (VARCHAR (10), DATE_OPER, 104) = '01.01.1900' then '' else CONVERT (VARCHAR (10), DATE_OPER, 104) end   FROM dbo.BK_GetDateTableOutOS(@varKSintLINK, DEFAULT))  as DATE_END,
--		ISNULL (T2.PERIOD_USED, 0) AS PER_USED,
		CASE
			WHEN T2.D_DT_CALC IS NULL THEN ISNULL (T2.PERIOD_USED, 0)
			ELSE (ISNULL (T2.PERIOD_USED, 0)
--				+ ROUND((CONVERT (NUMERIC (19,2), ISNULL((T2.D_DT_CALC - T2.DATE_BEGIN), 0)) / 365.25), 0)
				+ DATEDIFF (MONTH, T2.DATE_BEGIN, T2.D_DT_CALC) - 1)/ 12
		END AS PER_USED,
		ISNULL (T2.D_GRP_CODE, ISNULL (T2.CODE_RATE, ISNULL (T4.CODE, ''))) AS CODE_RATE,
		CASE
			WHEN T2.WEAR_FLAG = 2 THEN CONVERT (NUMERIC (10,2), 0)
			ELSE ISNULL (ND.DEPRE_RATE, 0)
		END AS DEPRE_Y_R,
		CASE
			WHEN T2.WEAR_FLAG = 2 THEN CONVERT (NUMERIC (10,2), 0)
			ELSE CONVERT (NUMERIC (10,2), ISNULL (ND.DEPRE_RATE/12, 0))
		END AS DEPRE_M_R,
		CASE
			WHEN T2.WEAR_FLAG = 2 THEN CONVERT (NUMERIC (28,2), 0)
			ELSE CONVERT (NUMERIC (28,2), ISNULL (ND.DEPRE_RATE / 100 * @nBALANSE, 0))
		END AS SUM_Y_N,
		CASE
			WHEN T2.WEAR_FLAG = 2 THEN CONVERT (NUMERIC (28,2), 0)
			ELSE CONVERT (NUMERIC (28,2), ISNULL (ND.DEPRE_RATE / 100 / 12 * @nBALANSE, 0))
		END AS SUM_M_N,
		ISNULL (@varKSnCALC_RATE, 0) AS SUM_RATE,
--		ISNULL (EMP.NAME_EMPL, '') AS FIL_NAME,
--		ISNULL (EMP.POST_NAME, '') AS FIL_POST,
--		ISNULL (CONVERT (VARCHAR (10), DATE_FILLING, 104), '') AS FIL_DATE,
		CONVERT (VARCHAR (10), @varKSdDATE_WORK, 104) AS DATE_CARD,
		ISNULL (dbo.DateMonthName (month (dbo.CalcLastDateWearOS (T1.LINK)))
			+ SPACE (1) + LTRIM (STR (dbo.CalcLastYearWearOS (T1.LINK))), '') AS LAST_DATE,
		DATE_RCALC	=	DATE_OPER2,
		JO_RCALC	=	JO_NUM2,
		SUM_RCALC	=	SUMMA2, 
		SUM_AM	=	TA1.SUM_AM, 
		YEAR_AM	=	TA1.YEAR_AM, 
		LAST_COST = (select isnull(dbo.RestOSByDate(T1.LINK_ACC,T1.LINK,DEFAULT),0) - isnull(dbo.RestOSDepreByDate(DEFAULT, T1.LINK,DEFAULT),0) ) ,
		REC_NO = 1,
		CNT_INV = (SELECT COUNT(*) FROM @TAB_MOVING )
	INTO #RES1		
	FROM dbo.INVENTORY_CARD T1
	LEFT OUTER JOIN dbo.BV_INVENTORY_CARD_DOP T2 ON (T2.LINK_UP = T1.LINK)
	LEFT OUTER JOIN dbo.ASSETS_GROUP_OKOF T3 ON (T3.LINK = T2.LINK_OKOF)
	LEFT OUTER JOIN dbo.DEPRE_GROUP T4 ON (T4.LINK = T3.DEPRE_GROUP)
--	LEFT OUTER JOIN dbo.KU_EMPL_PLACING EMP ON (EMP.LINK = T2.LINK_EMP_F)
	LEFT OUTER JOIN dbo.BK_GetNormDepreTableByOS (@varKSintLINK) ND ON (ND.INV = T1.LINK)
	LEFT JOIN @TAB_RECALL TR1 ON (TR1.REC_NO = 1)
	LEFT JOIN @TAB_AMORT TA1 ON (TA1.REC_NO = 1)
	WHERE T1.LINK = @varKSintLINK


	INSERT INTO #RES1 (
			DEP, DEP_CODE, DEP_OKPO, DEP_NAME, EMP_CODE, EMP_NAME, SUB_CODE, SUB_NAME,
			LINK, INV_CODE, INV_NAME, ACCT_CODE,
			FIRST_COST, GRP_COST,GRP_TYPE, CARD_NO, PASSPORT, PLANT_NUM, OTHER_NUM, CODE_OKOF, DATE_PROD,
			FIXING, LOCATION, MANUFACT,	DATE_BEGIN, DOC_BEGIN,DATE_FILL,DATE_END, PER_USED, CODE_RATE,
			DEPRE_Y_R, DEPRE_M_R, SUM_Y_N, SUM_M_N, SUM_RATE, DATE_CARD, LAST_DATE,
			REC_NO,CNT_INV,
			DATE_RCALC, JO_RCALC, SUM_RCALC,
			SUM_AM, YEAR_AM, LAST_COST)
	SELECT
		0, '', '', '', '', '', '', '',
		0, '', '', '', 
		0, 0, '','', '', '', '', '', '',
		'', '','', '', '', '', '', 0, '',
		0, 0, 0, 0, 0, '', '',
		T1.REC_NO, 0,
		ISNULL (CONVERT (VARCHAR (10), TR.DATE_OPER2, 104), ''),
		ISNULL (JO_NUM2, ''),
		ISNULL (SUMMA2, 0),
		ISNULL (SUM_AM, 0), ISNULL (YEAR_AM, 0),
		0
	FROM (
		SELECT
			REC_NO
		FROM @TAB_RECALL
		
		UNION

		SELECT
			REC_NO
		FROM @TAB_AMORT
		) AS T1
	LEFT JOIN @TAB_RECALL TR ON (TR.REC_NO = T1.REC_NO)
	LEFT JOIN @TAB_AMORT TA ON (TA.REC_NO = T1.REC_NO)
	WHERE T1.REC_NO > 1
	ORDER BY
	 	T1.REC_NO

	SELECT *
	FROM #RES1
	ORDER BY
	 	REC_NO

	
	--- ВЫВОД ДВИЖЕНИЯ --- 

	
	SELECT T2.CODE AS INV_CODE,
		ISNULL (T_IN.DATE_OP1, '') AS [DATE_D],
		ISNULL (T_IN.JO_NUM1, '') AS [JO_D],
		ISNULL (T_IN.QTY1, 0) AS QTY_D,
		ISNULL (T_IN.SUMMA1, 0) AS SUM_D,
		ISNULL (T_OUT.DATE_OP2, '') AS DATE_K,
		ISNULL (T_OUT.JO_NUM2, '') AS JO_K,
		ISNULL (T_OUT.QTY2, 0) AS QTY_K,
		ISNULL (T_OUT.SUMMA2, 0) AS SUM_K,
		ISNULL (TR.QTY, 0) AS QTY_R,
		ISNULL (TR.SUMMA, 0) AS SUM_R,
		ISNULL (EMP.NAME_EMPL, '') AS FIL_NAME,
		ISNULL (EMP.POST_NAME, '') AS FIL_POST,
		ISNULL (CONVERT (VARCHAR (10), ASS.DATE_FILLING, 104), '') AS FIL_DATE

	FROM @TAB_MOVING T1
	INNER JOIN dbo.INVENTORY T2 ON (T2.LINK = T1.INV)
	LEFT JOIN @TAB_INPUT T_IN ON (T_IN.INV = T1.INV)
	LEFT JOIN @TAB_OUTPUT T_OUT ON (T_OUT.INV = T1.INV)
	LEFT OUTER JOIN dbo.ASSETS ASS ON (ASS.LINK_UP = T2.LINK)
	LEFT OUTER JOIN dbo.KU_EMPL_PLACING EMP ON (EMP.LINK = ASS.EMP_FILLING)
	LEFT OUTER JOIN @varKSINV_REST TR ON (TR.INV_LINK = T1.INV
		AND TR.ACCT_SINT = '101')
--	ORDER BY DATE_ALL

	DROP TABLE #RES1

	EXEC dbo.BUFFERCLEAR @varKSc_BufferName
END






GO


GRANT EXECUTE ON dbo.[BK_PRINT_INV_CARD_F0504032_GRP] TO PUBLIC

GO


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


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

GO

/*
    © Кейсистемс (Keysystems), 2007
    Процедура формирования строк и значений формы 0503125
*/

CREATE PROCEDURE dbo.RT_CALC_0503125G_15
@LSF int,
@table int
AS

declare @cAccount varchar(9),  -- девять знаков: [1] - код вида деятельности [2..6] - счёт(синт+ан) [7..9] - СГУ
		@cSource char(1),
		@cSinth char(3),
		@cAnalit char(2),
		@cSGU char(3),
		@iLinkAccount int,
		@dBeginDate datetime,
		@dEndDate datetime,
		@dEndDate_pl datetime,
		@iThisDep int,
		@iCorrDep int,
		@i int,
		@j int,
		@iLink_col int,
		@code_row varchar(50),
		@float_val numeric(20,4),
		@str_val varchar(250),
		@cVidForm varchar(250),
		@cVidFormCode tinyint,
		@nPeriod_Type tinyint,
		@cStrSql varchar(8000),
		@nabor_filter varchar(100),
		@DEP_LINK int 
		
declare @table1 table(key_prov int, kbk int, account int, sgu int, db_kr tinyint, account_korr int, sgu_korr int, kpb_korr int, summa numeric(20,4))
create table #table2(nn int IDENTITY(1,1),Name_bp varchar(254), kod_bp varchar(10),INN VARCHAR(12), ppp char(3),OKTMO varchar(11), el_bud char(2), KBK varchar(30), Code_Acc varchar(9), summa_db numeric(20,4), summa_kr numeric(20,4),korr_acc varchar(10),DEP_K_NAME varchar(254),INN_K VARCHAR(12),PPP_K varchar(3),OKTMO_K varchar(11),  link varchar(254), dnd tinyint, key_prov int)
create table #table3(nn int IDENTITY(1,1),Name_bp varchar(254), kod_bp varchar(10),INN VARCHAR(12), ppp char(3),OKTMO varchar(11), el_bud char(2), KBK varchar(30), Code_Acc varchar(9), summa_db numeric(20,4), summa_kr numeric(20,4),korr_acc varchar(10),DEP_K_NAME varchar(254),INN_K VARCHAR(12),PPP_K varchar(3),OKTMO_K varchar(11), link varchar(254), dnd tinyint, key_prov int)
declare @filter_kbk table (kbk varchar(30))

-- вытаскиваем данные из сохранённой формы
set @cAccount = ltrim(rtrim(replace(dbo.RN_GET_ATR_VALUE(@LSF,'REPORTS_ATR_ACC_2011'),'.','')))
set @cSource = substring(@cAccount,1,1) -- вид деятельности
set @cSinth = substring(@cAccount,2,3)  -- синтетический счёт
set @cAnalit = substring(@cAccount,5,2) -- аналитическая составляющая
set @cSGU = substring(@cAccount,7,3)    -- СГУ


--set @cVidForm = ltrim(rtrim(dbo.RN_GET_ATR_VALUE(@LSF,'REPORTS_ATR_NAFO')))
--select @cVidFormCode = link from dbo.RT_VIEW_NAFO_125 where [Name] = @cVidForm

-- print '@cAccount = '+@cAccount
-- print '@cSource = '+@cSource
-- print '@cSinth = '+@cSinth
-- print '@cAnalit = '+@cAnalit
-- print '@cSGU = '+@cSGU
-- print '@cVidForm = '+@cVidForm
-- print '@cVidFormCode = '+cast(@cVidFormCode as varchar(3))

-- определяем период (если в январе формируем, то берём весь предыдущий год не включая 31 декабря)
select @dEndDate = Begin_Date, @nPeriod_Type = period_type  from dbo.report_saved_forms where link_saved_form = @LSF

select @dBeginDate = dbo.DateBeginOfYear(@dEndDate)


-- set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then (@dBeginDate - (datepart(dd,@dBeginDate))) - 1 else @dBeginDate /*- (datepart(dd,@dBeginDate))*/ end
-- set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')


--if @nPeriod_Type <> 1 
--	set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then @dBeginDate - 1 else @dBeginDate end
--else
--	set @dEndDate = @dBeginDate
--
--	set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')

-- получаем линк указанного счёта
select @iLinkAccount = link from dbo.s_accounts
where cSource = @cSource
and cSinth = @cSinth
and cAnalit = @cAnalit

-- линк организации которая собственно формирует справку
select @iThisDep = Link_Organization from dbo.report_saved_forms where link_saved_form = @LSF

-- print '@dBeginDate = '+cast(@dBeginDate as varchar(100))
-- print '@dEndDate = '+cast(@dEndDate as varchar(100))
-- print '@iLinkAccount = '+cast(@iLinkAccount as varchar(10))
-- теперь надо получить список корресп. счетов
if (((@cSinth = '206' and @cAnalit = '51') or (@cSinth = '205' and @cAnalit = '51') or (@cSinth = '207' and (@cAnalit = '11' or @cAnalit = '12' or @cAnalit = '13'))) and @cSGU = '000') /*and @nPeriod_Type = 1*/ begin
	set @dEndDate_pl = dateadd(d,1,@dEndDate)
	insert into @table1
	select 1,kbk, account, sgu, 1, null, null, dep, /*d_summa - */k_summa - d_summa
	from dbo.ARestTableByDate(@dEndDate_pl, @iLinkAccount)
	where dep_link = @iThisDep
end
else begin
	insert into @table1
	select
	C.link,
	D.kbk,
	D.account,
	D.sgu,
	D.DB_KR,
	E.account,
	E.sgu,
	/* Boch, брать организацию из извещения
	(case
	when D.Dep is not NULL and D.Dep <> A.Dep then
	D.Dep
	else (case when E.Dep is not NULL and E.Dep <> A.Dep then E.Dep else NULL end)
	end) as kpb_korr,*/
	(case
	when D.Dep is not NULL and D.Dep <> A.Dep then D.Dep
	when E.Dep is not NULL and E.Dep <> A.Dep then E.Dep
	when OS.Dep_pass is not NULL and OS.Dep_pass <> A.Dep then OS.Dep_pass
	when OS.Dep_receive is not NULL and OS.Dep_receive <> A.Dep then OS.Dep_receive
	else isnull((SELECT GPDA.DEPARTMENT FROM dbo.G_PROV_DEPARTMENT GPDA, dbo.S_OBJECTS SO WHERE GPDA.DOC_LINK = A.LINK AND GPDA.OBJECT = SO.LINK and SO.CODE = 'NOTICE_LINK_DEP_RECEIVER'), NULL) end)
	as kpb_korr,
	C.Summa
	from dbo.g_prov as A
	inner join dbo.g_prov1 as B
	on A.link = B.link_up
	and A.date_prov between @dBeginDate and @dEndDate
	and A.Dep = @iThisDep
	inner join dbo.g_prov2 as C
	on B.link = C.link_up
	inner join dbo.g_prov_ap as D
	on C.link = D.link_up
	inner join dbo.g_prov_ap as E
	on D.link_up = E.link_up
	and D.account <> E.account
	and D.account = @iLinkAccount
	and (D.sgu = (select link from dbo.kosgu where code = @cSGU) or '000' = @cSGU)
	left join dbo.G_PROV_OS1 OS on OS.LINK_OS1 = A.LINK
end


select @nabor_filter = REPLACE (dbo.rn_get_atr_value(@LSF,'REPORTS_FILTER_KBK'), 'Не отобрано', '')
insert @filter_kbk (kbk)   
Select LINK FROM rn_get_filter(@LSF,'REPORTS_FILTER_KBK')


-- теперь необходимо удалить из всего набора таблицы @table1 строчки с ненужными КБК (в зависимости от того для какой таблицы производится рассчёт)
delete from @table1
where kbk not in (select [LINK] 
					from dbo.kl_kbk K
					LEFT JOIN @filter_kbk F on K.LINK = F.KBK
					where @table = case when [TYPE] in (4,8) then 3 when [TYPE] = 1 then 2 when [TYPE] = 2 then 1 else [TYPE] end
					AND (F.kbk IS NULL OR isnull(@nabor_filter, '') = ''))


-- в таблице #table2
insert into #table2
select
(case
when exists(select [FULL_Name] from dbo.Departments where link = kpb_korr)
then (select [FULL_Name] from dbo.Departments where link = kpb_korr)
else 'корреспондент_не_указан'
end),
(case
when exists(select [CODE] from dbo.Departments where link = kpb_korr)
then (select [CODE] from dbo.Departments where link = kpb_korr)
else '0'
end),
(case
when exists(select [INN] from dbo.Departments where link = kpb_korr)
then (select [INN] from dbo.Departments where link = kpb_korr)
else '   '
end),
(case
when exists(select [CODE] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr))
then (select [CODE] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr))
else '000'
end),

--     (select [CODE] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr)),
--     (select [CODE_EL] from dbo.kl_budg_type where link = (select top 1 [Link_Budg] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr))),
(case
--when exists(select [OKATO] from dbo.Departments where link = kpb_korr)
--then (select left(replace([OKATO],' ',''),11) from dbo.Departments where link = kpb_korr)
when exists(select [OKTMO] from dbo.Departments where link = kpb_korr)
then (select isnull(replace(OKTMO,' ',''), '') from dbo.Departments where link = kpb_korr)
else ' '
end),
(case
when exists(select [CODE_EL] from dbo.kl_budg_type where link = (select top 1 [Link_Budg] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr)))
then (select [CODE_EL] from dbo.kl_budg_type where link = (select top 1 [Link_Budg] from dbo.kl_admin_bs where link = (select top 1 VED_LINK from dbo.Departments where link = kpb_korr)))
else '00'
end),
(case
when exists(select replace(replace(rtrim(code),'.',''),' ','') from dbo.kl_kbk where link = kbk)
then (select replace(replace(rtrim(code),'.',''),' ','') from dbo.kl_kbk where link = kbk)
else '_не_заполнен_кбк_'
end),
	@cSource+@cSinth+@cAnalit+
(case
when exists(select [code] from dbo.kosgu where link = sgu)
then (select [code] from dbo.kosgu where link = sgu)
else '000'
end),
(case when db_kr = 0 then isnull(SUM(summa),0.0) else 0.0 end),
(case when db_kr = 1 then isnull(SUM(summa),0.0) else 0.0 end),
(select left(replace(code,'.',''),6) from dbo.s_accounts where link = account_korr)+
(case
when exists(select [code] from dbo.kosgu where link = sgu_korr)
then (select [code] from dbo.kosgu where link = sgu_korr)
else '000'
end),
isnull((select top 1 NAME from DICTIONARY_DEPARTMENT where link = @iThisDep),''),
isnull((select top 1 INN from DICTIONARY_DEPARTMENT where link = @iThisDep),''),
isnull((select top 1 VED from DICTIONARY_DEPARTMENT where link = @iThisDep),''),
isnull((select top 1 OKTMO from DICTIONARY_DEPARTMENT where link = @iThisDep),''),
(NULL),
(NULL),
MAX(key_prov)

from @table1
group by kbk, account, sgu, db_kr, account_korr, sgu_korr, kpb_korr

--select * from #table2
-- очищаем зёрна от плевел -----------------------------------------------------------

if  @cSinth = '304' AND @cAnalit = '04' AND @cSGU = '000' begin
	update #table2
	set ppp = '', el_bud = '', oktmo = ''
end

if  @cSinth = '401' AND @cAnalit = '10' AND (@cSGU = '241' or @cSGU = '180')begin
	update #table2
	set el_bud = '',oktmo = ''
end

if  (@cSinth = '206' AND @cAnalit = '51' and @cSGU = '000')	or (@cSinth = '205' AND @cAnalit = '51' and @cSGU = '000') or (@cSinth = '207' AND (@cAnalit = '11' or @cAnalit = '12' or @cAnalit = '13') and @cSGU = '000') begin
	update #table2
	set summa_db = -(coalesce(summa_db,0.0) - coalesce(summa_kr,0.0)), summa_kr = 0.0, korr_acc = ''
end

if  @cSinth = '301' AND @cSGU = '000'/*@cVidFormCode = 14*/ begin
	update #table2
	set summa_db = 0.0, korr_acc = ''
end

if  (@cSinth = '211' OR @cSinth = '212') AND @cAnalit = '00' AND (@cSGU = '560' or @cSGU = '660') begin
	update #table2
	set ppp = '', el_bud = '',summa_db = 0.0
end

if  (@cSinth = '308' OR @cSinth = '309') AND @cAnalit = '00' AND (@cSGU = '730' or @cSGU = '830') begin
	update #table2
	set ppp = '', el_bud = '',summa_db = 0.0
end
--устанавливаем признак денежный - неденежный ----------------------------------------
update #table2  
set dnd = 
(case
    when 
        right(left(korr_acc,6),5) in ('21002','30405') or
        right(korr_acc,3) in ('510','610')
    then 1 -- денежные рассчёты
    else 0 -- не денежные рассчёты             
 end)
--------------------------------------------------------------------------------------

if (((@cSinth = '206' and @cAnalit = '51') or (@cSinth = '205' and @cAnalit = '51') or (@cSinth = '207' and (@cAnalit = '11' or @cAnalit = '12' or @cAnalit = '13'))) and @cSGU = '000') begin
	set @cStrSql = '
	insert into #table3 (Name_bp,INN,ppp,oktmo,el_bud,KBK,summa_db,summa_kr,korr_acc, dep_k_name, inn_k, ppp_k, OKTMO_K,link,dnd,key_prov)
	select Name_bp,INN,ppp,oktmo,el_bud,KBK,sum(summa_db),sum(summa_kr),korr_acc, dep_k_name, inn_k, ppp_k, OKTMO_K,null,dnd,null from #table2
	where Name_bp <> ''корреспондент_не_указан'' 
	group by Name_bp,ppp,el_bud,okato,KBK,korr_acc,dnd
	order by Name_bp,ppp

	insert into #table3 (Name_bp,INN,ppp,oktmo,el_bud,KBK,summa_db,summa_kr,korr_acc, dep_k_name, inn_k, ppp_k, OKTMO_K,link,dnd,key_prov)
	select Name_bp,INN,ppp,oktmo,el_bud,KBK,sum(summa_db),sum(summa_kr),korr_acc, dep_k_name, inn_k, ppp_k, OKTMO_K,null,dnd,null from #table2
	where Name_bp = ''корреспондент_не_указан'' 
	group by Name_bp,ppp,el_bud,okato,KBK,korr_acc,dnd
	order by KBK'
end
else begin
	set @cStrSql = '
	insert into #table3 (Name_bp,INN,ppp,oktmo,el_bud,KBK,Code_Acc,summa_db,summa_kr,korr_acc, dep_k_name, inn_k, ppp_k, OKTMO_K,link,dnd,key_prov)
	select			   	 Name_bp,INN,ppp,oktmo,el_bud,KBK,Code_Acc,summa_db,summa_kr,korr_acc, dep_k_name, inn_k, ppp_k, OKTMO_K,link,dnd,key_prov from #table2
	where Name_bp <> ''корреспондент_не_указан''
	order by Name_bp,ppp

	insert into #table3 (Name_bp,INN,ppp,oktmo,el_bud,KBK,Code_Acc,summa_db,summa_kr,korr_acc, dep_k_name, inn_k, ppp_k, OKTMO_K,link,dnd,key_prov)
	select Name_bp,INN,ppp,oktmo,el_bud,KBK,Code_Acc,summa_db,summa_kr,korr_acc, dep_k_name, inn_k, ppp_k, OKTMO_K,link,dnd,key_prov from #table2
	where Name_bp = ''корреспондент_не_указан''
	order by KBK,Code_Acc'
end
execute(@cStrSql)

delete from #table3 where summa_db = 0.0 and summa_kr = 0.0

update #table3
set link = LEFT(RTRIM(ISNULL(ppp,''))+'000',3)+LEFT(RTRIM(isnull(oktmo,'')) + '           ',11)+LEFT(RTRIM(ISNULL(el_bud,''))+'00',2)+LEFT(substring(rtrim(isnull([KBK],'')),1,17)+'00000000000000000',17)+LEFT(RTRIM(ISNULL(korr_acc,''))+'000000000',9)+RIGHT('00000000' + LTRIM(CAST(ISNULL(nn,0) as VARCHAR(8))),8)
--set link = LEFT(RTRIM(ISNULL(ppp,''))+'   ',3)+LEFT(RTRIM(isnull(okato,'')) + '           ',11)+LEFT(RTRIM(ISNULL(el_bud,''))+'  ',2)+LEFT(substring(rtrim(isnull([KBK],'')),1,17)+'                 ',17)+LEFT(RTRIM(ISNULL(korr_acc,''))+'         ',9)+RIGHT('00000000' + LTRIM(CAST(ISNULL(nn,0) as VARCHAR(8))),8)
--set link = LEFT(RTRIM(ISNULL(ppp,''))+'000',3)+LEFT(RTRIM(isnull(okato,''))+'00000000000',11)+LEFT(RTRIM(ISNULL(el_bud,''))+'00',2)+LEFT(substring(rtrim(isnull([KBK],'')),1,17)+'00000000000000000',17)+LEFT(RTRIM(ISNULL(korr_acc,''))+'000000000',9)+RIGHT('00000000' + LTRIM(CAST(ISNULL(nn,0) as VARCHAR(8))),8)

-- удаляем только строчки, принадлежащие указанной таблице. Остальные, соответственно, не трогаем
delete from dbo.report_dinamics where Link_SF = @LSF and Link_Col in (select link_col from dbo.report_coloumns where link_table = (select link_table from dbo.report_tables where link_form = (select top 1 link_form from dbo.report_saved_forms where link_saved_form = @LSF) and Orders = @table))

if @table in (1,3) begin
SELECT 
[CODE] = [link], -- Код строки.
[COL1] = [Name_bp], -- Наименование контрагента
[COL2] = INN,
[COL3] = [ppp], -- ППП
[COL4] = [oktmo], -- ОКТМО
[COL5] = [el_bud], -- Элемент бюджета
[COL6] = substring(rtrim(isnull([KBK],'')),1,3), -- АДМ
[COL7] = substring(rtrim(isnull([KBK],'')),4,14), -- КБК
[COL8] = [summa_db], -- сумма дебет
[COL9] = [summa_kr], -- сумма кредит
[COL10] = [korr_acc], -- Код корреспондирующего счёта бюджетного учета
[COL11] = DEP_K_NAME,
[COL12] = INN_K,
[COL13] = PPP_K,
[COL14] = OKTMO_K,
[COL15] = cast (isnull([dnd],'') as varchar), -- Признак платежа
[COL16]= [link], -- Код строки.
[COL17]= RIGHT('00000000' + LTRIM(CAST(ISNULL(nn,0) as VARCHAR(8))),8)
FROM #table3
ORDER BY [link]
end
else begin
SELECT 
[CODE] = [link], -- Код строки.
[COL1] = [Name_bp], -- Наименование контрагента
[COL2] = INN,
[COL3] = [ppp], -- ППП
[COL4] = [oktmo], -- ОКАТО
[COL5] = [el_bud], -- Элемент бюджета
[COL6] = substring(rtrim(isnull([KBK],'')),1,3), -- АДМ
[COL7] = substring(rtrim(isnull([KBK],'')),4,4), -- РзПр
[COL8] = substring(rtrim(isnull([KBK],'')),8,7), -- ЦСР
[COL9] = substring(rtrim(isnull([KBK],'')),15,3),-- ВР
[COL10] = [summa_db], -- сумма дебет
[COL11] = [summa_kr], -- сумма кредит
[COL12] = [korr_acc], -- Код корреспондирующего счёта бюджетного учета
[COL13] = DEP_K_NAME,
[COL14] = INN_K,
[COL15] = PPP_K,
[COL16] = OKTMO_K,
[COL17] = cast (isnull([dnd],'') as varchar), -- Признак платежа
[COL18] = [link], -- Код строки.
[COL19] = RIGHT('00000000' + LTRIM(CAST(ISNULL(nn,0) as VARCHAR(8))),8)
FROM #table3
ORDER BY [link]
end

drop table #table2
drop table #table3



GO


GRANT EXECUTE ON dbo.[RT_CALC_0503125G_15] 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(replace(ZT.BK_CODE,'.',''),'00000000000000000000',''),20),
			TYPE_KBK_RCP  = case ZKR.SHORT when 0 then case ZT.KBK_TYPE_d when 1 then '10'
																		  when 2 then '20'
																		  when 4 then '31'
																		  when 8 then '32'
																		  else '' end else '' end,
			KBK_RCP		  = case ZKR.SHORT when 0 then left(replace(ZT.BKD_CODE,'.',''),30) 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.[SA_P4_NZ_PREPARE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_P4_NZ_PREPARE]

GO

----- Пример выполнения: 
/* DECLARE  @p float 
 SET @p = ''
 exec [dbo].SA_P4_NZ_PREPARE @p output, '20130401' , '20130630' , 74578 , 40841
*/
CREATE PROCEDURE DBO.SA_P4_NZ_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 @DB1	DATETIME,
	@DE1	DATETIME,
	@DB2	DATETIME,
	@DE2	DATETIME,
	@DB3	DATETIME,
	@DE3	DATETIME,
	@DBYEAR DATETIME

/* КВАРТАЛЬНАЯ ФОРМА, РАСПРЕДЕЛИМ КВАРТАЛ ПО МЕСЯЦАМ*/
SET @DB1 = DBO.DATEBEGINOFMONTH (@ENDDATE) 
SET @De1 = DATEADD(MONTH,1,@DB1)-1
SET @DB2 = DBO.DATEBEGINOFMONTH (@DB1 -1 )
SET @De2 = DATEADD(MONTH,1,@DB2)-1
SET @DB3 = DBO.DATEBEGINOFMONTH (@DB2 -1 )
SET @De3 = DATEADD(MONTH,1,@DB3)-1

SET @DBYEAR = DBO.DATEBEGINOFYEAR(@BDATE)


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(@De1, @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)

/**********************************************************************************************************************/	
--- ИНФОРМАЦИЯ ПО СОТРУДНИКАМ ОРАГНИЗАЦИИ ЗА ПЕРИОД
select * 
INTO #EMPLS_INFO_PERIOD
 from dbo.SA_EMPLS_INFO_PERIOD(@DB3,@ENDDATE, DEFAULT, @DEP_LINK)

--------------- 
--------ИНФОРМАЦИЯ О СОТРУДНИКАХ И ОТРАБОТАННОМ ВРЕМЕНИ ЗА МЕСЯЦ ПО ВСЕМ ТАБЕЛЯМ 

CREATE TABLE #DPEE (
	LINK_EMPL INT,
	LINK_SOVM INT,
	LINK_PAYS INT,
	CODE_PAYS VARCHAR(10),
	NAME_PAYS VARCHAR(60),
	DATE_BEGIN DATETIME,
	DATE_END DATETIME,
	WAY_CALC TINYINT,
	SUMMA_BASE NUMERIC(18,2),
	PERC NUMERIC(18,4),
	SUMMA NUMERIC(18,2),
	LINK_KBK INT,
	CODE_KBK VARCHAR(30),
	[DAYS] NUMERIC(5,2), 
	[HOURS] NUMERIC(18,2),
	NO_TIME BIT 
)
INSERT INTO #DPEE (LINK_EMPL, LINK_SOVM, LINK_PAYS, CODE_PAYS, NAME_PAYS, DATE_BEGIN, DATE_END, WAY_CALC, SUMMA_BASE, PERC, SUMMA, LINK_KBK, CODE_KBK, DAYS, HOURS, NO_TIME)
SELECT LINK_EMPL, LINK_SOVM, LINK_PAYS, CODE_PAYS, NAME_PAYS, DATE_BEGIN, DATE_END, WAY_CALC, SUMMA_BASE, PERC, SUMMA, LINK_KBK, CODE_KBK, DAYS, HOURS, NO_TIME
FROM DBO.SA_ALL_PAYS_ALL(-1,@De1,NULL, @DEP_LINK, -1)
UNION all
SELECT LINK_EMPL, LINK_SOVM, LINK_PAYS, CODE_PAYS, NAME_PAYS, DATE_BEGIN, DATE_END, WAY_CALC, SUMMA_BASE, PERC, SUMMA, LINK_KBK, CODE_KBK, DAYS, HOURS, NO_TIME
FROM DBO.SA_ALL_PAYS_ALL(-1,@De2,NULL, @DEP_LINK, -1)
UNION all
SELECT LINK_EMPL, LINK_SOVM, LINK_PAYS, CODE_PAYS, NAME_PAYS, DATE_BEGIN, DATE_END, WAY_CALC, SUMMA_BASE, PERC, SUMMA, LINK_KBK, CODE_KBK, DAYS, HOURS, NO_TIME
FROM DBO.SA_ALL_PAYS_ALL(-1,@De3,NULL, @DEP_LINK, -1)
order by DATE_BEGIN, DATE_END


------- *ВСЕ ДОЛЖНОСТИ СОТРУДНИКА В ЗАДАННОМ МЕСЯЦЕ (ОСНОВНОЕ И ВСЕ ВРЕМЕННЫЕ СОВМЕЩЕНИЯ)
CREATE TABLE #SA_EMPLS_W (LINK_EMPL INT, LINK_SOVM INT, GRAPH_LINK INT, NUM_STAKE NUMERIC(5,2), SYST_PAY TINYINT, DATE_BEGIN DATETIME, DATE_END DATETIME, LINK_SFIN INT, SALPERC NUMERIC(18,2), link_type INT)
INSERT INTO #SA_EMPLS_W (LINK_EMPL, LINK_SOVM, GRAPH_LINK, NUM_STAKE, SYST_PAY, DATE_BEGIN, DATE_END, LINK_SFIN, SALPERC, link_type)
SELECT LINK_EMPL, LINK_SOVM, GRAPH_LINK, NUM_STAKE, SYST_PAY, DATE_BEGIN, DATE_END, LINK_SFIN, SALPERC, link_type FROM DBO.SA_EMPLS_W_LITE_FN (-1,@ENDDATE,NULL)




/*** НАЧАЛЬНЫЕ УСТАНОВКИ ***/
/* ТАБЛИЦА РЕЗУЛЬТАТОВ РАСЧЕТА (СТОЛБЕЦ/ЗНАЧЕНИЕ) */
CREATE  TABLE #P4NZ_PART1(CODE_STR VARCHAR(10) , COL	INT, VAL NUMERIC(18,2), VAL_STR VARCHAR(20))

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




/*********************************************************************************************************************/
CREATE TABLE #VARKSTMP
([LINK_EMPL]					[INT],
 [ORDERS]				[INT] IDENTITY(1,1),
 [TAB_NUMER]			[VARCHAR] (6),
 [NAME_EMPL]			[VARCHAR] (30),
 [LINK_SOVM]			[INT],
 [DATE1]				[DATETIME],		
 [DATE2]				[DATETIME],		
 [DAY]					[NUMERIC] (4,0),
 [HOUR]					[NUMERIC] (10,2),
 [DAY_NORM]				[NUMERIC] (4,0),
 [HOUR_NORM]			[NUMERIC] (10,2),
 [GRAPH_NAME]			[VARCHAR] (30),
 [GRAPH_LINK]			[INT],
 [PERCENT]				[NUMERIC] (18,4),
 [RATE]					[NUMERIC] (5,2),
 [REF_PAY]				[INT],
 [CODE_PAY]				[VARCHAR] (10),
 [NAME_PAY]				[VARCHAR] (60),
 [WAY_CALC]				[TINYINT],
 [DATE1_PAY]			[DATETIME],  
 [DATE2_PAY]			[DATETIME],
 LINK_KBK				INT,
 CODE_KBK				VARCHAR(30),
 SYST_PAY				INT,
 ORD					INT,
 DAY_OLD				[NUMERIC] (18,2) , 
 HOUR_OLD				[NUMERIC] (18,2),
 NO_TIME				BIT 		
)


-------------  ИНФОРМАЦИЯ НА БАЗЕ ОСНОВНОГО ТАБЕЛЯ ПО СТАВКАМ , ОТРАБОТАННЫМ ЧАСАМ/ДНЯМ ---------------
INSERT INTO #VARKSTMP ([LINK_EMPL], [TAB_NUMER],[NAME_EMPL],[LINK_SOVM],[DATE1],[DATE2],		
						[DAY],[HOUR],[DAY_NORM],[HOUR_NORM],[GRAPH_NAME],[GRAPH_LINK],[PERCENT],[RATE],[REF_PAY],[CODE_PAY],[NAME_PAY],[WAY_CALC],
						[DATE1_PAY],[DATE2_PAY], LINK_KBK, CODE_KBK, SYST_PAY, DAY_OLD,HOUR_OLD, NO_TIME)
---------ПЕРВЫЙ МЕСЯЦ КВАРТАЛА
SELECT 
	[LINK_EMPL]			= EI.EMPL_LINK,
	[TAB_NUMER]		= SUBSTRING(RTRIM(LTRIM(EM.TAB)),1,6),
	[NAME_EMPL]		= SUBSTRING(LTRIM(RTRIM(ISNULL(P.FM,''))) + ' ' + LEFT(LTRIM(RTRIM(ISNULL(P.IM,''))),1) + '.' + LEFT(LTRIM(RTRIM(ISNULL(P.OT,''))),1) + '.',1,30),
	[LINK_SOVM] 	= E.LINK_SOVM,
	[DATE1]			= DPE.DATE_BEGIN,
	[DATE2]			= ISNULL(DPE.DATE_END,CONVERT(DATETIME,'01.01.3000',104)),
	[DAY]			= DPE.DAYS,
	[HOUR]			= DPE.HOURS,
	[DAY_NORM]		= ISNULL(CONVERT(NUMERIC(4,0),G1.DAY_NORM),0),
	[HOUR_NORM] 	= ISNULL(CONVERT(NUMERIC(10,2),G1.HOUR_NORM),0),
	[GRAPH_NAME]	= SUBSTRING(RTRIM(LTRIM(G.NAME)),1,30),
	[GRAPH_LINK]	= E.GRAPH_LINK,
	[PERCENT] 		= CONVERT(NUMERIC(18,4),ISNULL( DPE.PERC,0)),
	[RATE]			= ISNULL(E.NUM_STAKE,0),
	[REF_PAY]		= DPE.LINK_PAYS,
	[CODE_PAY]		= SUBSTRING(RTRIM(LTRIM(DPE.CODE_PAYS)),1,10),
	[NAME_PAY]		= SUBSTRING(RTRIM(LTRIM(DPE.NAME_PAYS)),1,60),
	[WAY_CALC]		= DPE.WAY_CALC,
	[DATE1_PAY]		= DPE.DATE_BEGIN,
	[DATE2_PAY]		= ISNULL(DPE.DATE_END,CONVERT(DATETIME,'01.01.3000',104)),
	DPE.LINK_KBK, LEFT(DPE.CODE_KBK,30),
	E.SYST_PAY,
	DAY_OLD = CONVERT(NUMERIC(18,2),ISNULL(OLDA.DAYS,0)) , 
	HOUR_OLD =  CONVERT(NUMERIC(18,2),ISNULL(OLDA.HOURS,0)) ,
	DPE.NO_TIME

FROM 
	#EMPLS_INFO_PERIOD EI
	INNER JOIN DBO.EMPL EM ON EI.EMPL_LINK = EM.LINK
	INNER JOIN DBO.PERSON P ON EM.PERS_LINK = P.LINK
	INNER JOIN #SA_EMPLS_W  E ON EI.EMPL_LINK = E.LINK_EMPL --DBO.SA_EMPLS_W_LITE_FN (@P,@VARKSDAT2,@BUF_ID) E ON T.LINK_EMPL = E.LINK_EMPL 
	INNER JOIN #DPEE DPE ON DPE.LINK_EMPL = E.LINK_EMPL AND DPE.LINK_SOVM = E.LINK_SOVM and @DE3 between DPE.date_begin and DPE.date_END
	INNER JOIN DBO.GRAPH G ON E.GRAPH_LINK = G.LINK
	INNER JOIN DBO.GRAPHICS G1 ON G1.GRAPH_LINK = G.LINK AND MONTH(G1.PERIOD) = MONTH(@DE3) AND YEAR(G1.PERIOD) = YEAR(@DE3)
	LEFT JOIN ( 
		SELECT SJC.LINK_EMPL, LINK_SOVM = ISNULL(LINK_SOVM,0), LINK_PAYS, LINK_VKR, [DAYS] = MAX([DAYS]), [HOURS] = MAX([HOURS]), SUMMA = SUM(SUMMA) 
		FROM DBO.CALCULATE_JURNAL SJC INNER JOIN DBO.SDOC_TABEL ST ON (SJC.LINK_DOC = ST.LINK_UP)
		WHERE 
			MONTH(DATE_BEGIN) = MONTH(@DE3) AND YEAR(DATE_BEGIN) = YEAR(@DE3) 
		GROUP BY SJC.LINK_EMPL, LINK_SOVM, LINK_PAYS, LINK_VKR) OLDA 
		ON OLDA.LINK_EMPL = E.LINK_EMPL  AND OLDA.LINK_SOVM = E.LINK_SOVM AND OLDA.LINK_PAYS = DPE.LINK_PAYS AND OLDA.LINK_VKR = DPE.LINK_KBK
	WHERE 
		(
		@BUFFER_SUBDIV IS NULL 
			OR 
		@BUFFER_SUBDIV IS NOT NULL AND EI.SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
		)
	

 ---------ВТОРОЙ МЕСЯЦ КВАРТАЛА
UNION ALL 
SELECT 
	[LINK_EMPL]			= EI.EMPL_LINK,
	[TAB_NUMER]		= SUBSTRING(RTRIM(LTRIM(EM.TAB)),1,6),
	[NAME_EMPL]		= SUBSTRING(LTRIM(RTRIM(ISNULL(P.FM,''))) + ' ' + LEFT(LTRIM(RTRIM(ISNULL(P.IM,''))),1) + '.' + LEFT(LTRIM(RTRIM(ISNULL(P.OT,''))),1) + '.',1,30),
	[LINK_SOVM] 	= E.LINK_SOVM,
	[DATE1]			= DPE.DATE_BEGIN,
	[DATE2]			= ISNULL(DPE.DATE_END,CONVERT(DATETIME,'01.01.3000',104)),
	[DAY]			= DPE.DAYS,
	[HOUR]			= DPE.HOURS,
	[DAY_NORM]		= ISNULL(CONVERT(NUMERIC(4,0),G1.DAY_NORM),0),
	[HOUR_NORM] 	= ISNULL(CONVERT(NUMERIC(10,2),G1.HOUR_NORM),0),
	[GRAPH_NAME]	= SUBSTRING(RTRIM(LTRIM(G.NAME)),1,30),
	[GRAPH_LINK]	= E.GRAPH_LINK,
	[PERCENT] 		= CONVERT(NUMERIC(18,4),ISNULL( DPE.PERC,0)),
	[RATE]			= ISNULL(E.NUM_STAKE,0),
	[REF_PAY]		= DPE.LINK_PAYS,
	[CODE_PAY]		= SUBSTRING(RTRIM(LTRIM(DPE.CODE_PAYS)),1,10),
	[NAME_PAY]		= SUBSTRING(RTRIM(LTRIM(DPE.NAME_PAYS)),1,60),
	[WAY_CALC]		= DPE.WAY_CALC,
	[DATE1_PAY]		= DPE.DATE_BEGIN,
	[DATE2_PAY]		= ISNULL(DPE.DATE_END,CONVERT(DATETIME,'01.01.3000',104)),
	DPE.LINK_KBK, LEFT(DPE.CODE_KBK,30),
	E.SYST_PAY,
	DAY_OLD = CONVERT(NUMERIC(18,2),ISNULL(OLDA.DAYS,0)) , 
	HOUR_OLD =  CONVERT(NUMERIC(18,2),ISNULL(OLDA.HOURS,0)) ,
	DPE.NO_TIME

FROM 
	#EMPLS_INFO_PERIOD EI
	INNER JOIN DBO.EMPL EM ON EI.EMPL_LINK = EM.LINK
	INNER JOIN DBO.PERSON P ON EM.PERS_LINK = P.LINK
	INNER JOIN #SA_EMPLS_W  E ON EI.EMPL_LINK = E.LINK_EMPL --DBO.SA_EMPLS_W_LITE_FN (@P,@VARKSDAT2,@BUF_ID) E ON T.LINK_EMPL = E.LINK_EMPL 
	INNER JOIN #DPEE DPE ON DPE.LINK_EMPL = E.LINK_EMPL AND DPE.LINK_SOVM = E.LINK_SOVM and @DE2 between DPE.date_begin and DPE.date_END
	INNER JOIN DBO.GRAPH G ON E.GRAPH_LINK = G.LINK
	INNER JOIN DBO.GRAPHICS G1 ON G1.GRAPH_LINK = G.LINK AND MONTH(G1.PERIOD) = MONTH(@DE2) AND YEAR(G1.PERIOD) = YEAR(@DE2)	
	LEFT JOIN ( 
		SELECT SJC.LINK_EMPL, LINK_SOVM = ISNULL(LINK_SOVM,0), LINK_PAYS, LINK_VKR, [DAYS] = MAX([DAYS]), [HOURS] = MAX([HOURS]), SUMMA = SUM(SUMMA) 
		FROM DBO.CALCULATE_JURNAL SJC INNER JOIN DBO.SDOC_TABEL ST ON (SJC.LINK_DOC = ST.LINK_UP)
		WHERE 
			MONTH(DATE_BEGIN) = MONTH(@DE2) AND YEAR(DATE_BEGIN) = YEAR(@DE2) 
		GROUP BY SJC.LINK_EMPL, LINK_SOVM, LINK_PAYS, LINK_VKR) OLDA 
		ON OLDA.LINK_EMPL = E.LINK_EMPL  AND OLDA.LINK_SOVM = E.LINK_SOVM AND OLDA.LINK_PAYS = DPE.LINK_PAYS AND OLDA.LINK_VKR = DPE.LINK_KBK
	WHERE 
		(
		@BUFFER_SUBDIV IS NULL 
			OR 
		@BUFFER_SUBDIV IS NOT NULL AND EI.SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
		)

 ---------ТРЕТИЙ МЕСЯЦ КВАРТАЛА 
UNION ALL 
SELECT 
	[LINK_EMPL]			= EI.EMPL_LINK,
	[TAB_NUMER]		= SUBSTRING(RTRIM(LTRIM(EM.TAB)),1,6),
	[NAME_EMPL]		= SUBSTRING(LTRIM(RTRIM(ISNULL(P.FM,''))) + ' ' + LEFT(LTRIM(RTRIM(ISNULL(P.IM,''))),1) + '.' + LEFT(LTRIM(RTRIM(ISNULL(P.OT,''))),1) + '.',1,30),
	[LINK_SOVM] 	= E.LINK_SOVM,
	[DATE1]			= DPE.DATE_BEGIN,
	[DATE2]			= ISNULL(DPE.DATE_END,CONVERT(DATETIME,'01.01.3000',104)),
	[DAY]			= DPE.DAYS,
	[HOUR]			= DPE.HOURS,
	[DAY_NORM]		= ISNULL(CONVERT(NUMERIC(4,0),G1.DAY_NORM),0),
	[HOUR_NORM] 	= ISNULL(CONVERT(NUMERIC(10,2),G1.HOUR_NORM),0),
	[GRAPH_NAME]	= SUBSTRING(RTRIM(LTRIM(G.NAME)),1,30),
	[GRAPH_LINK]	= E.GRAPH_LINK,
	[PERCENT] 		= CONVERT(NUMERIC(18,4),ISNULL( DPE.PERC,0)),
	[RATE]			= ISNULL(E.NUM_STAKE,0),
	[REF_PAY]		= DPE.LINK_PAYS,
	[CODE_PAY]		= SUBSTRING(RTRIM(LTRIM(DPE.CODE_PAYS)),1,10),
	[NAME_PAY]		= SUBSTRING(RTRIM(LTRIM(DPE.NAME_PAYS)),1,60),
	[WAY_CALC]		= DPE.WAY_CALC,
	[DATE1_PAY]		= DPE.DATE_BEGIN,
	[DATE2_PAY]		= ISNULL(DPE.DATE_END,CONVERT(DATETIME,'01.01.3000',104)),
	DPE.LINK_KBK, LEFT(DPE.CODE_KBK,30),
	E.SYST_PAY,
	DAY_OLD = CONVERT(NUMERIC(18,2),ISNULL(OLDA.DAYS,0)) , 
	HOUR_OLD =  CONVERT(NUMERIC(18,2),ISNULL(OLDA.HOURS,0)) ,
	DPE.NO_TIME

FROM 
	#EMPLS_INFO_PERIOD EI
	INNER JOIN DBO.EMPL EM ON EI.EMPL_LINK = EM.LINK 
	INNER JOIN DBO.PERSON P ON EM.PERS_LINK = P.LINK
	INNER JOIN #SA_EMPLS_W  E ON EI.EMPL_LINK = E.LINK_EMPL --DBO.SA_EMPLS_W_LITE_FN (@P,@VARKSDAT2,@BUF_ID) E ON T.LINK_EMPL = E.LINK_EMPL 
	INNER JOIN #DPEE DPE ON DPE.LINK_EMPL = E.LINK_EMPL AND DPE.LINK_SOVM = E.LINK_SOVM and @DE1 between DPE.date_begin and DPE.date_END
	INNER JOIN DBO.GRAPH G ON E.GRAPH_LINK = G.LINK
	INNER JOIN DBO.GRAPHICS G1 ON G1.GRAPH_LINK = G.LINK AND MONTH(G1.PERIOD) = MONTH(@DE1) AND YEAR(G1.PERIOD) = YEAR(@DE1)	
	LEFT JOIN ( 
		SELECT SJC.LINK_EMPL, LINK_SOVM = ISNULL(LINK_SOVM,0), LINK_PAYS, LINK_VKR, [DAYS] = MAX([DAYS]), [HOURS] = MAX([HOURS]), SUMMA = SUM(SUMMA) 
		FROM DBO.CALCULATE_JURNAL SJC INNER JOIN DBO.SDOC_TABEL ST ON (SJC.LINK_DOC = ST.LINK_UP)
		WHERE 
			MONTH(DATE_BEGIN) = MONTH(@DE1) AND YEAR(DATE_BEGIN) = YEAR(@DE1) 
		GROUP BY SJC.LINK_EMPL, LINK_SOVM, LINK_PAYS, LINK_VKR) OLDA 
		ON OLDA.LINK_EMPL = E.LINK_EMPL  AND OLDA.LINK_SOVM = E.LINK_SOVM AND OLDA.LINK_PAYS = DPE.LINK_PAYS AND OLDA.LINK_VKR = DPE.LINK_KBK
	WHERE 
		(
		@BUFFER_SUBDIV IS NULL 
			OR 
		@BUFFER_SUBDIV IS NOT NULL AND EI.SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
		)	


/*Численность работников списочного состава, работавших неполное рабочее время по инициативе работодателя */
/* COL3!  код 01 */
INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
		SELECT '01' , 3, 0
/*Пока строку 01 оставляем пустой*/
/*INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
		SELECT '01' , 3, count(a.link_empl) from 
			(select link_empl from #VARKSTMP 
			where RATE < 1 and [day] !=0 and [hour] !=0
			GROUP BY link_empl) a
*/

--/*Численность работников списочного состава, работавших неполное рабочее время по соглашению между работником и работодателем */
--/* COL3!  код 02 */
INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
		SELECT '02' , 3, count(a.link_empl) from 
			(select link_empl  from #VARKSTMP 
			where rate<1 and [day] !=0 and [hour] !=0
			GROUP BY link_empl) a
-- /*Численность работников списочного состава, находившихся в простое по вине работодателя и по причинам, не зависящим от работодателя и работника */ ---
--/* COL3!  код 03 */
INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
		SELECT '03' , 3, 0


----- СОТРУДНИКИ У КОТОРЫХ БЫЛИ ОТПУСКА (NO_SAL = 0 - С СОХРАНЕНИЕМ ЗП И NO_SAL = 1 - БЕЗ СОХРАНЕНИЯ )
create table #EMPLS_VAC (LINK_EMPL INT, DATE_BEGIN DATETIME, DATE_END DATETIME,NO_SAL TINYINT)
INSERT INTO #EMPLS_VAC (LINK_EMPL, DATE_BEGIN, DATE_END,NO_SAL)
	select  E.EMPL_LINK,
			V.DATE_BEGIN,
			V.DATE_END, 
			VV.NO_SAL 		
	from  #EMPLS_INFO_PERIOD E
	INNER JOIN item_vacation v on E.EMPL_LINK = V.EMPL_LINK and V.DATE_END between @BDATE and @ENDDATE and v.ACTIVE = 1 
 	INNER JOIN vacation_vid VV on  VV.link = V.TYPE_LINK
	WHERE
			(
		@BUFFER_SUBDIV IS NULL 
			OR 
		@BUFFER_SUBDIV IS NOT NULL AND E.SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
		)
		
-----/*Численность работников списочного состава, которым были предоставлены отпуска без сохранения заработной платы по письменному заявлению работника*/
--/* COL3!  код 05 */
INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
	SELECT '05' , 3, count(a.LINK_EMPL) from 
			(select LINK_EMPL 
			 from #EMPLS_VAC 
			 where NO_SAL = 1 group by LINK_EMPL) a 


------ ПРИНЯТЫЕ НА РАБОТУ В ПЕРИОД ОТЧЕТНОГО КВАРТАЛА
create table #EMPLS_NEW (LINK_EMPL INT, DATE_BEGIN DATETIME,DATE_END DATETIME, ACTIVE TINYINT)
INSERT INTO #EMPLS_NEW (LINK_EMPL, DATE_BEGIN, DATE_END,ACTIVE)
select  E.EMPL_LINK,
		N.DATE_BEGIN,
		N.DATE_END2,
		N.ACTIVE 		
	from  #EMPLS_INFO_PERIOD E
	INNER JOIN NEW_FACE N on E.EMPL_LINK = N.EMPL_LINK  and N.DATE_BEGIN between @BDATE and @ENDDATE and N.ACTIVE = 1
	and N.dep_link = @dep_link
	WHERE 
		(
		@BUFFER_SUBDIV IS NULL 
			OR 
		@BUFFER_SUBDIV IS NOT NULL AND E.SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
		)
-----/*Численность принятых работников списочного состава - всего */
--/* COL3!  код 06 */
INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
	SELECT '06' , 3, count(a.LINK_EMPL) from 
			(select LINK_EMPL 
			 from #EMPLS_NEW
			 group by LINK_EMPL) a 

------ ПРИНЯТЫЕ НА РАБОТУ В СВЯЗИ С РАСШИРЕНИЕМ , ВВЕДЕНИЕМ НОВЫХ ВАКАНСИЙ , НА ВНОВЬ СОЗДАННЫЕ ДОЛЖНОСТИ
CREATE TABLE #EMPLS_NEW_STAFF (LINK_EMPL INT, DATE_BEGIN DATETIME,DATE_END DATETIME, ACTIVE TINYINT)
INSERT INTO #EMPLS_NEW_STAFF(LINK_EMPL, DATE_BEGIN,DATE_END, ACTIVE)
select n.empl_link, s.date_begin, s.date_end, n.active 
from #EMPLS_NEW E
inner join NEW_FACE n on E.LINK_EMPL = N.EMPL_LINK /*and N.DATE_BEGIN between @BDATE and @ENDDATE */and N.ACTIVE = 1
inner join  staff s on n.staff_LINK = s.link_up /*and  s.date_begin  between @BDATE and @ENDDATE*/ 
			and s.date_begin = (select max(DATE_BEGIN ) from staff where link_up = n.staff_LINK /*and date_begin between  @BDATE and @ENDDATE*/)
			/*and s.num_stake > (select s1.num_stake from  staff s1 where s1.date_end = s.date_begin-1 )*/


-----/*Численность принятых работников списочного состава на дополнительно введенные (созданные) рабочие места */
--/* COL3!  код 07 */
INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
	SELECT '07' , 3, 0 
/*Строку 07 оставляем пустой*/
/*
INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
	SELECT '07' , 3, count(a.LINK_EMPL) from 
			(select LINK_EMPL 
			 from #EMPLS_NEW_STAFF
			 group by LINK_EMPL) a 
*/

--- УВОЛЕННЫЕ В ОТЧЕТНЫЙ КВАРТАЛ РАБОТНИКИ , ВСЕ 
CREATE TABLE #EMPLS_DIS (LINK_EMPL INT, DIS_DATE DATETIME, REASON INT , CODE VARCHAR(4),ACTIVE TINYINT)
INSERT INTO #EMPLS_DIS(LINK_EMPL, DIS_DATE, REASON, CODE, ACTIVE)
select E.EMPL_LINK, d.dis_date, d.REASON, di.CODE, D.ACTIVE from 
	#EMPLS_INFO_PERIOD E
	inner join item_dis_face d on  E.EMPL_LINK= D.EMPL_LINK and d.dis_date between @BDATE and @ENDDATE and d.ACTIVE = 1
	inner join  diction di on d.reason = di.link
	WHERE 	
		(
		@BUFFER_SUBDIV IS NULL 
			OR 
		@BUFFER_SUBDIV IS NOT NULL AND E.SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
		)

-----/*Численность выбывших работников списочного состава - всего */
--/* COL3!  код 08 */
INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
	SELECT '08' , 3, count(a.LINK_EMPL) from 
			(select LINK_EMPL 
			 from #EMPLS_DIS
			 group by LINK_EMPL) a 

-----/*Численность выбывших работников списочного состава по соглашению сторон */
--/* COL3!  код 09 */
INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
	SELECT '09' , 3, count(a.LINK_EMPL) from 
			(select LINK_EMPL 
			 from #EMPLS_DIS
			 where CODE in ('0101', '2000')
			 group by LINK_EMPL) a 

-----/*Численность выбывших работников списочного состава в связи с сокращением численности работников */
--/* COL3!  код 10 */
INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
	SELECT '10' , 3, count(a.LINK_EMPL) from 
			(select LINK_EMPL 
			 from #EMPLS_DIS
			 where CODE = ('0402')
			 group by LINK_EMPL) a 


-----
	/*Численность выбывших работников списочного состава по собственному желанию 
		включаются работники списочного состава, выбывшие из организации в следующих случаях: по инициативе работника; 
		избрание на должности, замещаемые по конкурсу; переезд в другую местность; перевод супруга в другую местность, за границу; 
		зачисление в образовательное учреждение, аспирантуру или клиническую ординатуру; увольнение по собственному желанию в связи с выходом на пенсию; 
		необходимость ухода за больными членами семьи или инвалидами I группы; 
		увольнение по собственному желанию беременных женщин, женщин, имеющих детей в возрасте до трех лет, одиноких матерей, воспитывающих ребенка в возрасте до 14 лет (ребенка-инвалида до 18 лет)*/
--/* COL3!  код 12 */
INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
	SELECT '12' , 3, count(a.LINK_EMPL) from 
			(select LINK_EMPL 
			 from #EMPLS_DIS
			 where CODE in ('0300','2023', '2002', '0501')
			 group by LINK_EMPL) a 
			 
---- Численность работников на конец отчетного периода 
  
/* ВЫЧИСЛЯЕМ ОСН. РАБОТНИКОВ и ВНЕШ. СОВМЕСИТЕЛЕЙ  */
	INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL) SELECT '13', 3, CONVERT(NUMERIC(18,1), DBO.SA_SCH_EMPLS(@ENDDATE, @DEP_LINK, 0, 0, 0, @BUFFER_SUBDIV))


/* ВЫЧИСЛЯЕМ ВНЕШ. СОВМЕСИТЕЛЕЙ */
--	INSERT INTO #NZP_PART1 (CODE_STR, COL, VAL) SELECT '100', 5, CONVERT(NUMERIC(18,1), DBO.SA_SCH_EMPLS(@ENDDATE, @DEP_LINK, 0, 3, 0, @BUFFER_SUBDIV))
DELETE FROM DBO.BUFFER WHERE ID = @BUFFER_SUBDIV AND @BUFFER_SUBDIV IS NOT NULL	

------ РАБОТНИКИ КОТОРЫЕ БУДУТ ПРИНЯТЫ НА ПОСЛЕДНЕЕ ЧИСЛО ОТЧЕТНОГО КВАРТАЛА
create table #EMPLS_NEW_ENDDATE (LINK_EMPL INT, DATE_BEGIN DATETIME,DATE_END DATETIME, ACTIVE TINYINT)
INSERT INTO #EMPLS_NEW_ENDDATE  (LINK_EMPL, DATE_BEGIN, DATE_END,ACTIVE)
select  N.EMPL_LINK,
		N.DATE_BEGIN,
		N.DATE_END2,
		N.ACTIVE 		
	from  NEW_FACE N WHERE N.DATE_BEGIN = @ENDDATE and N.ACTIVE = 1
	and N.dep_link = @dep_link
	AND 
		(
		@BUFFER_SUBDIV IS NULL 
			OR 
		@BUFFER_SUBDIV IS NOT NULL AND SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
		)
-----/*Численность требуемых работников списочного состава на вакантные рабочие места на конец отчетного квартала */
--/* COL3!  код 14 */
INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
	SELECT '14' , 3, 0
INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
	SELECT '15' , 3, 0	
/*Строки 14 - 22 пустые - для ручного заполнения*/
/*INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
	SELECT '14' , 3, count(a.LINK_EMPL) from 
			(select LINK_EMPL 
			 from #EMPLS_NEW_ENDDATE
			 group by LINK_EMPL) a 
*/
--- Численность женщин, находящихся в отпуске по уходу за ребенком до достижения им возраста 1,5 лет, на конец отчетного квартала 
--	и в возрасте от 1,5 до 3 лет, на конец отчетного квартала
IF year(@ENDDATE) >='2015' 
begin
	CREATE TABLE #EMPLS_UHOD_CHILD (LINK_EMPL INT, VAC_DATE DATETIME, VAC_VID INT ,ACTIVE TINYINT)
	INSERT INTO #EMPLS_UHOD_CHILD (LINK_EMPL, VAC_DATE, VAC_VID,ACTIVE)
	select E.EMPL_LINK, v.date
		,CASE WHEN 	vv.NAME LIKE '%до 1,5 лет%' THEN 1 
			  WHEN  vv.NAME LIKE '%до 3 лет%'  THEN 2 END 
		, v.ACTIVE from 
		#EMPLS_INFO_PERIOD E
		inner join dbo.VACATION v  on  E.EMPL_LINK = v.EMPL_LINK  and v.children = 1 and (v.date_end between @BDATE and @ENDDATE or v.date_begin between @BDATE and @ENDDATE)  and v.ACTIVE = 1
		INNER JOIN dbo.VACATION_VID AS vv ON vv.LINK = v.TYPE_LINK 
		INNER JOIN dbo.person p ON p.LINK = e.PERS_LINK AND p.SEX = 2
		where E.EMPL_LINK not in (select link_empl  from #VARKSTMP 
				where rate<1 and [day] !=0 and [hour] !=0
				GROUP BY link_empl) -- не должны попадать  женщины с неполным рабочим временем
				and 
				(
			@BUFFER_SUBDIV IS NULL 
				OR 
			@BUFFER_SUBDIV IS NOT NULL AND E.SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
			)
	-----/*Численность женщин, находящихся в отпуске по уходу за ребенком до достижения им возраста 1,5 лет, на конец отчетного квартала 
	--	и в возрасте от 1,5 до 3 лет, на конец отчетного квартала
	--/* COL3!  код 16, 17 */
	INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
		SELECT '16' , 3, count(a.LINK_EMPL) from 
				(select LINK_EMPL 
				 from #EMPLS_UHOD_CHILD WHERE VAC_VID = 1 
				 group by LINK_EMPL) a 
	INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
		SELECT '17' , 3, count(a.LINK_EMPL) from 
				(select LINK_EMPL 
				 from #EMPLS_UHOD_CHILD WHERE VAC_VID = 2 
				 group by LINK_EMPL) a 
end
------ 
/*--- СОТРУДНИКИ КОТОРЫХ УВОЛЯТ ПОСЛЕ ОТЧЕТНОГО ПЕРИОДА , КРОМЕ ИСТЕЧЕНИЯ СРОЧНЫХ ТРУДОВЫХ ДОГОВОРОВ И ВЫХОДОВ НА ПЕНСИЮ 
CREATE TABLE #EMPLS_DIS_NEXT (LINK_EMPL INT, DIS_DATE DATETIME, REASON INT , CODE VARCHAR(4),ACTIVE TINYINT)
INSERT INTO #EMPLS_DIS_NEXT(LINK_EMPL, DIS_DATE, REASON, CODE, ACTIVE)
select E.EMPL_LINK, d.dis_date, d.reason_link, di.CODE, D.ACTIVE from 
	#EMPLS_INFO_PERIOD E
	inner join DIS_FACE d on  E.EMPL_LINK = D.EMPL_LINK  and d.dis_date >= @ENDDATE and d.ACTIVE = 1 
	inner join  diction di on d.reason_link = di.link and di.code not in ('0501' , '2001')
	WHERE 	
		(
		@BUFFER_SUBDIV IS NULL 
			OR 
		@BUFFER_SUBDIV IS NOT NULL AND E.SUBDIV_LINK IN (SELECT LINK FROM @SUBDIV)
		)

-----/*Численность работников списочного состава, намеченных к высвобождению в следующем квартале*/
--/* COL3!  код 15 */
INSERT INTO #P4NZ_PART1 (CODE_STR, COL, VAL)
	SELECT '15' , 3, count(a.LINK_EMPL) from 
			(select LINK_EMPL 
			 from #EMPLS_DIS_NEXT
			 group by LINK_EMPL) a 
*/

---- очистка лишних задвоений для тех у кого перевод, и дальнейшая работа происходила в течении месяца
--delete FROM 
--	#EMPL1 
--WHERE
--	LINK in (SELECT LINK FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1 ) 
--	AND PERIOD_END not in (SELECT min(PERIOD_END) FROM  #EMPL1 E1 GROUP BY LINK HAVING COUNT(*) > 1 /*and  min(PERIOD_END) = @D2*/ ) 

DROP TABLE #EMPLS_INFO_PERIOD 
DROP TABLE #DPEE
DROP TABLE #SA_EMPLS_W 
DROP TABLE #VARKSTMP
DROP TABLE #EMPLS_VAC 
DROP TABLE #EMPLS_NEW
DROP TABLE #EMPLS_NEW_STAFF 
DROP TABLE #EMPLS_DIS
--DROP TABLE #EMPLS_DIS_NEXT
DROP TABLE #EMPLS_NEW_ENDDATE

/**********************************************************************************************************************/
/* СОЗДАЕМ ВРЕМЕНННУЮ ТАБЛИЦУ */
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 #P4NZ_PART1 ')
EXEC DBO.BUFFERPUSH -152, @RESULT_TABLE
	SET @OUT_VAL = ''


DROP TABLE #P4NZ_PART1

END











GO


GRANT EXECUTE ON dbo.[SA_P4_NZ_PREPARE] TO PUBLIC

GO



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

GO

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(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 @ATR_TYPE_KOR INT
SET @ATR_TYPE_KOR  = (SELECT DBO.RN_GET_ATR_VALUE(@Link, 'REPORTS_ATR_TYPE_KOR'))	

--Атрибут "Прекращение деятельности"
SET @WORK_END = (SELECT DBO.RN_GET_ATR_VALUE(@Link, 'REPORTS_ATR_LIKVID'))
SET @WORK_END = CASE WHEN @WORK_END LIKE 'ДА' THEN 'Л' ELSE '' END
	
DECLARE @LINK_DEP INT, @YEAR INT, @Version TINYINT, @Period_Number TINYINT, @LINK_FORM INT, @Begin_Date DATETIME, @End_Date DATETIME, @modify_date DATETIME
SELECT
	@LINK_DEP = LINK_ORGANIZATION,
	@YEAR = YEAR(Begin_Date),
	@Version = [Version],
	@Period_Number = Period_Number,
	@LINK_FORM = LINK_FORM,
	@Begin_Date = dbo.DateBeginOfYear(Begin_Date),
	@End_Date = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,Period_Number*3,YEAR(Begin_Date))),
	@modify_date = modify_date
FROM dbo.REPORT_SAVED_FORMS WHERE LINK_SAVED_FORM = @link

SELECT top 1
	DD1.OKPO AS OKPO1,
	RIGHT(REPLICATE('0',12) + LTRIM(RTRIM(DD1.INN)), 12) AS INN1,
	DD1.KPP AS KPP1,
	FULL_NAME = CONVERT(VARCHAR(160),UPPER(DD1.FULL_NAME)),
	UPPER(DD1.NAME) AS ORGNAME,
	DD2.NALOG AS IMNS_SONO, DD2.NAME AS IMNS_NAME,
	DD2.NALOG AS SONO,
	RIGHT(REPLICATE('0',15) + LTRIM(RTRIM(DD1.OGRN)), 15) AS OGRN1,
	LTRIM(RTRIM(dbo.GetAddressBykladr(DD1.REF_LINK_A)))
		+ CASE WHEN ISNULL(DD1.HOUSE, '') = '' THEN '' ELSE ' ' + LTRIM(RTRIM(DD1.HOUSE)) END
		+ CASE WHEN ISNULL(DD1.FLAT, '') = '' THEN '' ELSE ' - ' + LTRIM(RTRIM(DD1.FLAT)) END
	AS ADDR_STR,
	CAST(NULL AS DATETIME) AS DATE_END,
	UPPER(RTRIM(CHIEF.FM) + ' ' + LEFT(CHIEF.IM, 1) + '. ' + LEFT(CHIEF.OT,1) + '.') AS CHIEF_FIO,
	RTRIM(CHIEF.PHONE) AS CH_PHONE,
	UPPER(RTRIM(GLBUH.FM) + ' ' + LEFT(GLBUH.IM, 1) + '. ' + LEFT(GLBUH.OT,1) + '.') AS GLBUH_FIO,
	RTRIM(GLBUH.PHONE) AS GL_PHONE,
	OGRN = RIGHT(REPLICATE('0',15) + LTRIM(RTRIM(DD1.OGRN)), 15),
	DD1.OKATO,
	DD1.OKTMO,
	OKVED = (CASE WHEN LEN(ltrim(rtrim(DD1.OKVED)))<8 AND RIGHT(DD1.OKVED,1) = '.' THEN STUFF(DD1.OKVED,LEN(ltrim(rtrim(DD1.OKVED))),1,'') ELSE DD1.OKVED end) ,
	DD1.OKPO,
	DD1.FSS_REG_NUM, --Регистрационный номер (код) страхователя ТФОМС
	DD1.FSS_KOD_P, --Код подчиненности - код, состоящий из пяти цифр, указывающий на территориальный орган Фонда, в котором страхователь зарегистрирован в текущий момент;	
	DD1.FSS_KOD_DOP, --Дополнительный код предусмотрен для обособленных подразделений организаций
	DD1.OKOPF, --- код Общероссийского классификатора организационно-правовых форм;
	DD1.OKFS, --- код Общероссийского классификатора форм собственности;
	DD1.PFNUMBER,
	DA.PINDEX, REGION = UPPER(DA.REGION), DA.REGCODE, RAION = UPPER(DA.RAION), GOROD = UPPER(DA.GOROD),
	NASEL = UPPER(DA.NASEL), STREET = UPPER(DA.STREET), DA.HOUSE, DA.KORP, DA.FLAT,
	TFOMS_RNUM = DD1.TFOMS_REG_NUM,
	TFOMS_KT = DD1.TFOMS_KT,
	TFOMS_KTI = '03',
	WORK_END = '1'
INTO #DEP_DATA	
FROM DICTIONARY_DEPARTMENT DD1
	LEFT OUTER JOIN DICTIONARY_DEPARTMENT DD2 ON DD1.IMNS_LINK = DD2.LINK
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Руководитель') chief on chief.link_dep = dd1.link
	LEFT OUTER JOIN dbo.GetOtvFaceData(@LINK_DEP, 'Главный бухгалтер') GLBUH ON GLBUH.link_dep = dd1.link
	LEFT JOIN DBO.DEP_ADRESS(@LINK_DEP) DA ON 1=1
WHERE DD1.LINK = @LINK_DEP


/*Узнаем с какого номера начинаются пачки ондивидуальных сведений, для того чтобы вычислить номер пачки описи*/
IF OBJECT_ID('tempdb..#t_osn') IS NOT NULL DROP TABLE #t_osn
CREATE table #t_osn (code CHAR(4), COL1 INT , COL2 VARCHAR(10) , COL3 NUMERIC(18,2), COL4 NUMERIC(18,2), COL5 INT, COL6 VARCHAR(100), COL7 VARCHAR(10), col8 int , col9 int, col10 int, col11 int)
IF OBJECT_ID('tempdb..#t_kor') IS NOT NULL DROP TABLE #t_kor
CREATE table #t_kor (code CHAR(4), COL1 INT , COL2 CHAR(4) , COL3 NUMERIC(18,2), COL4 NUMERIC(18,2), COL5 VARCHAR(50), COL6 VARCHAR(50), COL7 VARCHAR(50), col8 int , col9 VARCHAR(100), col10 VARCHAR(10), col11 int, col12 int , col13 int, col14 VARCHAR(50), col15 VARCHAR(50), col16 VARCHAR(10))

INSERT INTO #t_osn /*(code, COL1, COL2, COL3, COL4, COL5, COL6, COL7, col8, col9, col10, col11)*/
exec [dbo].RSA_RSV_1_PERS_UCH @Begin_Date, @End_Date, @LINK_DEP ,0,  @link   

INSERT INTO #t_kor
exec [dbo].RSA_RSV_1_PERS_UCH @Begin_Date, @End_Date, @LINK_DEP ,1,  @link   

INSERT INTO #t_osn (code, COL1 , COL2 , COL4)
SELECT code, COL1 , COL2 , COL4
FROM #t_kor

DECLARE @NUM_P INT 
IF COALESCE(dbo.sa_get_option_by_code('SA_SZV4_OPT3'),0) = 1
	SET @NUM_P = (SELECT MIN(COALESCE(COL1,0))-1 FROM #t_osn) 
ELSE 
	SET @NUM_P = (SELECT MAX(COALESCE(COL1,0))+1 FROM #t_osn) 

drop table #t_osn 
drop table #t_kor

/**/





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-' + REPLACE(str((@NUM_P),5),' ','0') + '-DPT-000000-DCK-00000.XML' FROM #DEP_DATA

	--exec SA_RSV1_EXPORT_0700_2014   2565	


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) + '<РАСЧЕТ_ПО_СТРАХОВЫМ_ВЗНОСАМ_НА_ОПС_И_ОМС_ПЛАТЕЛЬЩИКАМИ_ПРОИЗВОДЯЩИМИ_ВЫПЛАТЫ_ФЛ_2015>'
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<НомерВпачке>1</НомерВпачке>'
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<РегистрационныйНомерПФР>' + LTRIM(RTRIM(ISNULL(PFNUMBER,''))) + '</РегистрационныйНомерПФР>' + CHAR(10) +
								 SPACE(3) + '<НомерКорректировки>' + CASE @Version WHEN 0 THEN '000' ELSE (REPLICATE('0',2) + ltrim(rtrim(CONVERT(varchar(3),@Version)))) END + '</НомерКорректировки>' + CHAR(10) +
								 SPACE(3) + '<КодОтчетногоПериода>' + CASE @Period_Number WHEN 1 THEN '3' WHEN 2 THEN '6' WHEN 3 THEN '9' ELSE '0' END +'</КодОтчетногоПериода>' + CHAR(10) +
								 SPACE(3) + '<КалендарныйГод>' + LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),@YEAR),''))) + '</КалендарныйГод> ' + CHAR(10) +
							   CASE WHEN LTRIM(RTRIM(ISNULL(@WORK_END,''))) = 'Л' THEN
										SPACE(3) + '<ПрекращениеДеятельности>' + LTRIM(RTRIM(ISNULL(@WORK_END,''))) + '</ПрекращениеДеятельности> ' + CHAR(10)
								 ELSE '' END
		FROM #DEP_DATA	
		UNION ALL SELECT @lcFNAME, (	CASE  WHEN isnull(@ATR_TYPE_KOR,0) = 0 /*OR  @Version = 0*/ THEN ''
								ELSE
								SPACE(3) + '<ТипКорректировки>' + CONVERT(varchar(1),@ATR_TYPE_KOR) + '</ТипКорректировки>' + CHAR(10)
								END)

	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<НаименованиеОрганизации>' + LTRIM(RTRIM(ISNULL(FULL_NAME,''))) + '</НаименованиеОрганизации>' FROM #DEP_DATA
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + '<РегистрационныйНомерТФОМС>' + LTRIM(RTRIM(ISNULL(TFOMS_RNUM,''))) + '</РегистрационныйНомерТФОМС>' FROM #DEP_DATA
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<ИННсимвольный>' + LTRIM(RTRIM(ISNULL(INN1,''))) + '</ИННсимвольный>' FROM #DEP_DATA
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<КПП>' + LTRIM(RTRIM(ISNULL(KPP1,''))) + '</КПП>' FROM #DEP_DATA
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + '<ОГРН>' + LTRIM(RTRIM(ISNULL(OGRN1,''))) + '</ОГРН>' FROM #DEP_DATA
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + case when @OKATO_OR_OKTMO = 1
				--							 then ('<КодПоОКАТО>' + REPLACE(LTRIM(RTRIM(ISNULL(OKATO,''))),SPACE(1),'') + '</КодПоОКАТО>' )
				--							 ELSE ('<КодПоОКТМО>' + REPLACE(LTRIM(RTRIM(ISNULL(OKTMO,''))),SPACE(1),'') + '</КодПоОКТМО>' ) END
				--							 FROM #DEP_DATA
	  											
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКВЭД>' + LTRIM(RTRIM(ISNULL(OKVED,''))) + '</КодПоОКВЭД>' FROM #DEP_DATA
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКПО>' + LTRIM(RTRIM(ISNULL(OKPO,''))) + '</КодПоОКПО>' FROM #DEP_DATA
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКОПФ>' + LTRIM(RTRIM(ISNULL(OKOPF,''))) + '</КодПоОКОПФ>' FROM #DEP_DATA
	  --UNION ALL SELECT @lcFNAME, SPACE(3) + '<КодПоОКФС>' + LTRIM(RTRIM(ISNULL(OKFS,''))) + '</КодПоОКФС>' FROM #DEP_DATA
	  UNION ALL SELECT @lcFNAME, SPACE(3) + '<Телефон>' + LTRIM(RTRIM(ISNULL(GL_PHONE,''))) + '</Телефон>' FROM #DEP_DATA
		
	 -- UNION ALL SELECT @lcFNAME, SPACE(3) + '<АдресРегистрации>'
		 -- UNION ALL SELECT @lcFNAME, SPACE(4) + '<ТипАдреса>РОССИЙСКИЙ</ТипАдреса>'
		 -- UNION ALL SELECT @lcFNAME, SPACE(4) + '<Индекс>'+ LTRIM(RTRIM(ISNULL(PINDEX,''))) + '</Индекс>' FROM #DEP_DATA
		 -- UNION ALL SELECT @lcFNAME, SPACE(4) + '<РоссийскийАдрес>' + CHAR(10) +

			--								CASE WHEN LTRIM(RTRIM(ISNULL(REGION,''))) <> '' THEN
			--								 SPACE(5) + '<Регион>' + CHAR(10) +
			--									SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(REGION,len(REGION)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(REGION),1,' '))) ) )) + '</ГеографическоеНазвание>' + CHAR(10) +
			--									SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(REGION),1,' ')) )) + '</Сокращение>' + CHAR(10) +
			--								SPACE(5) + '</Регион>' + CHAR(10)
			--								ELSE '' END +
											
			--								CASE WHEN LTRIM(RTRIM(ISNULL(RAION,''))) <> '' THEN
			--								 SPACE(5) + '<Район>' + CHAR(10) +
			--									SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(RAION,len(RAION)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(RAION),1,' '))) ) )) + '</ГеографическоеНазвание>' + CHAR(10) +
			--									SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(RAION),1,' ')) )) + '</Сокращение>' + CHAR(10) +
			--								SPACE(5) + '</Район>' + CHAR(10)
			--								ELSE '' END +

			--								CASE WHEN LTRIM(RTRIM(ISNULL(GOROD,''))) <> '' THEN
			--								 SPACE(5) + '<Город>' + CHAR(10) +
			--									SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(GOROD,len(GOROD)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(GOROD),1,' '))) ) )) + '</ГеографическоеНазвание>' + CHAR(10) +
			--									SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(GOROD),1,' ')) )) + '</Сокращение>' + CHAR(10) +
			--								SPACE(5) + '</Город>' + CHAR(10)
			--								ELSE '' END +

			--								CASE WHEN LTRIM(RTRIM(ISNULL(NASEL,''))) <> '' THEN
			--								 SPACE(5) + '<НаселенныйПункт>' + CHAR(10) +
			--									SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(NASEL,len(NASEL)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(NASEL),1,' '))) ) )) + '</ГеографическоеНазвание>' + CHAR(10) +
			--									SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(NASEL),1,' ')) )) + '</Сокращение>' + CHAR(10) +
			--								SPACE(5) + '</НаселенныйПункт>' + CHAR(10)
			--								ELSE '' END +	

			--								CASE WHEN LTRIM(RTRIM(ISNULL(STREET,''))) <> '' THEN
			--								SPACE(5) + '<Улица>' + CHAR(10)
			--									+ SPACE(6) + '<ГеографическоеНазвание>'+ RTRIM(LTRIM(Left(STREET,len(STREET)-len(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(STREET),1,' '))) ) ))+'</ГеографическоеНазвание>' + CHAR(10)
			--									+ SPACE(6) + '<Сокращение>'+ RTRIM(LTRIM(REVERSE(dbo.SA_GET_WORD_NUM(REVERSE(STREET),1,' ')) ))+'</Сокращение>' + CHAR(10)
			--									+ SPACE(5) + '</Улица>' + CHAR(10)
			--								ELSE '' END	+			

			--								CASE WHEN LTRIM(RTRIM(ISNULL(HOUSE,''))) <> '' THEN
			--								 SPACE(5) + '<Дом>' + CHAR(10) +
			--									SPACE(6) + '<Сокращение>ДОМ</Сокращение>' + CHAR(10) +
			--									SPACE(6) + '<Номер>'+ UPPER(LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),HOUSE),'')))) + '</Номер>' + CHAR(10) +
			--								SPACE(5) + '</Дом>' + CHAR(10)
			--								ELSE '' END +												

			--								CASE WHEN LTRIM(RTRIM(ISNULL(KORP,''))) <> '' THEN
			--								 SPACE(5) + '<Корпус>' + CHAR(10) +
			--									SPACE(6) + '<Сокращение>КОРП.</Сокращение>' + CHAR(10) +
			--									SPACE(6) + '<Номер>'+ UPPER(LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),KORP),'')))) + '</Номер>' + CHAR(10) +
			--								SPACE(5) + '</Корпус>' + CHAR(10)
			--								ELSE '' END +																

			--								CASE WHEN LTRIM(RTRIM(ISNULL(FLAT,''))) <> '' THEN
			--								 SPACE(5) + '<Квартира>' + CHAR(10) +
			--									SPACE(6) + '<Сокращение>КВ.</Сокращение>' + CHAR(10) +
			--									SPACE(6) + '<Номер>'+ UPPER(LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(10),FLAT),'')))) + '</Номер>' + CHAR(10) +
			--								SPACE(5) + '</Квартира>' + CHAR(10)
			--								ELSE '' END +				
											
			--						SPACE(4) + '</РоссийскийАдрес>' + CHAR(10) +
			--					SPACE(3) + '</АдресРегистрации>'
			--FROM #DEP_DATA

------ стр.1_2
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
select @lcFNAME,
		CASE WHEN T.COL = 3 THEN
			SPACE(3) + '<КоличествоЗЛ>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ>'
		ELSE
			SPACE(3) + '<СреднесписочнаяЧисленность>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</СреднесписочнаяЧисленность>'		
		END	
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 1, 1, DEFAULT) T WHERE T.COL IN (3,4) ORDER BY T.COL

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)	
		 --SELECT @lcFNAME, SPACE(3) + '<КодУстановленногоТарифа>' + LTRIM(RTRIM(ISNULL(TFOMS_KT,''))) + '</КодУстановленногоТарифа>' FROM #DEP_DATA
/*UNION ALL*/ SELECT @lcFNAME, SPACE(3) + '<КоличествоСтраниц>14</КоличествоСтраниц>'
UNION ALL SELECT @lcFNAME, SPACE(3) + '<КоличествоЛистовПриложения>0</КоличествоЛистовПриложения>'

----- стр.2
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '<Раздел1РасчетПоНачисленнымУплаченным2014>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ОстатокЗадолженностиНаНачалоРасчетногоПериода>'
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) + '</ОстатокЗадолженностиНаНачалоРасчетногоПериода>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<НачисленоСначалаРасчетногоПериода>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME,
	CASE T.COL
	WHEN 3 THEN
		CASE T.ROW 
			WHEN 2 THEN SPACE(5) + '<ВсегоСначалаРасчетногоПериода>' 
			WHEN 6 THEN SPACE(5) + '<ПоследниеТриМесяцаИтого>' 
			ELSE SPACE(5) + '<ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 2))) + '>' 
		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) + '</ВсегоСначалаРасчетногоПериода>' 
			WHEN 6 THEN SPACE(5) + '</ПоследниеТриМесяцаИтого>' 
			ELSE SPACE(5) + '</ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.ROW - 2))) + '>' 
		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) + '</НачисленоСначалаРасчетногоПериода>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ДоначисленоСначалаРасчетногоПериодаВсего>'
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) + '</ДоначисленоСначалаРасчетногоПериодаВсего>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ДоначисленоСначалаРасчетногоПериодаПревышающие>'
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) + '</ДоначисленоСначалаРасчетногоПериодаПревышающие>'

---------------------
DECLARE @N_STR INT
IF @YEAR = 2015 AND @Period_Number = 1 
begin
	SET @N_STR = 10
END 
ELSE BEGIN 
	SET @N_STR = 12
	END 	
	
----------------------
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<ВсегоКуплате>'
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, @N_STR, 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) + '</ВсегоКуплате>'


INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<УплаченоСначалаРасчетногоПериода>'
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
SELECT @lcFNAME,
	CASE T.COL
		WHEN 3 THEN
			CASE T.ROW_CODE 
					WHEN '140' THEN SPACE(5) + '<ВсегоСначалаРасчетногоПериода>' 
					WHEN '144' THEN SPACE(5) + '<ПоследниеТриМесяцаИтого>' 
					ELSE SPACE(5) + '<ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),CONVERT(INT,T.ROW_CODE) - 140))) + '>' 
			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_CODE
			WHEN '140' THEN SPACE(5) + '</ВсегоСначалаРасчетногоПериода>' 
			WHEN '144' THEN SPACE(5) + '</ПоследниеТриМесяцаИтого>' 
			ELSE SPACE(5) + '</ПоследниеТриМесяца' + LTRIM(RTRIM(CONVERT(VARCHAR(1),CONVERT(INT,T.ROW_CODE) - 140))) + '>' 
		END	
	END						
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 2, 0, DEFAULT) T WHERE ROW_CODE IN ('140','141','142','143','144') 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) + '</УплаченоСначалаРасчетногоПериода>'

--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) + '<ОстатокЗадолженностиНаКонецРасчетногоПериода>'
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, DEFAULT, DEFAULT) T WHERE T.ROW_CODE = '150' AND T.COL IN (3,4,5,6,7,8) ORDER BY T.COL
INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</ОстатокЗадолженностиНаКонецРасчетногоПериода>'


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,'НаОбязательноеПенсионноеСтрахование'
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,'СуммаРасходовПринимаемыхКвычету'

IF @Period_Number = 1 AND @YEAR = 2015
begin 
	INSERT INTO #STR_2_1B -- первый квартал 2015 года не выводится
		SELECT 13,2,'ПревышающиеПредельнуюВеличинуБазы' 
		UNION	SELECT 14,2,'БазаДляНачисленияСтраховыхВзносовНаОМС'
		UNION	SELECT 15,2,'НачисленоНаОМС'
END 
ELSE BEGIN 
	INSERT INTO #STR_2_1B  -- со второго квартала 2015 года выводится	
		SELECT 13,2,'БазаДляНачисленияСтраховыхВзносовНаОМС'
		UNION	SELECT 14,2,'НачисленоНаОМС'
		UNION SELECT 15,2,'КоличествоФЛвсего'
	END 


--- ДОП ТАРИФЫ раздел 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
---- exec [dbo].SA_RSV1_EXPORT_0700_2014    2195

create table #T21 (tabl int , row int, ROW_CODE varchar(10) , COL int , SUMMA numeric(10) , summa2 numeric(15,2), STR_VAL varchar(100) )
insert into #T21
select tabl,
row,
ROW_CODE,
COL,
SUMMA = sum(summa) ,
summa2  = sum(summa2),
STR_VAL
from
(select tabl ,
row,
ROW_CODE,
COL,
SUMMA ,
summa2 ,
STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, DEFAULT, DEFAULT) T WHERE T.COL IN (3,4,5,6) --ORDER BY T.COL
union all
select 	
tabl = 3 ,
ROW ,
ROW_CODE  = CASE ROW_CODE WHEN '2000' then '200'
							WHEN '2010' then '201'
							WHEN '2020' then '202'
							WHEN '2030' then '203'
							WHEN '2040' then '204'
							WHEN '2050' then '205'
							WHEN '2060' then '206'
							WHEN '2070' then '207'
							WHEN '2080' then '208'
							WHEN '2090' then '209'
							WHEN '2100' then '210'
							WHEN '2110' then '211'
							WHEN '2120' then '212'
							WHEN '2130' then '213'
							WHEN '2140' then '214'
							WHEN '2150' then '215'   end,
COL ,
SUMMA ,
summa2,
STR_VAL
FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, DEFAULT, DEFAULT) T WHERE T.COL IN (3,4,5,6)
) a
group by  tabl,
row,
ROW_CODE,
COL, STR_VAL



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 ((@Period_Number != 1 AND @YEAR >= 2015) AND @NUM != 13 ) 
								--BEGIN
									if @num = 8 or @num = 9 OR  (@Period_Number != 1 AND @YEAR >= 2015 and  @NUM = 15) 
									BEGIN
										IF @Period_Number !=1 AND @YEAR >= 2015 
										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),SUM(T.SUMMA)),''))) + '</КоличествоЗЛ_Всего>'
												ELSE SPACE(7) + '<КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),sum(T.SUMMA)),''))) + + '</КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
												END				
											FROM #t21 t WHERE T.COL IN (3,4,5,6) and  row = @NUM GROUP BY T.COL , T.ROW_CODE ORDER BY T.COL
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'
										END
									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),SUM(T.SUMMA2)),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
												ELSE SPACE(8) + '<СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),SUM(T.SUMMA2)),''))) + + '</СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
												END				
											FROM #t21 t WHERE T.COL IN (3,4,5,6) and  row = @NUM GROUP BY T.COL , T.ROW_CODE 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
							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_KT,'')))  + '</КодТарифа>' FROM #DEP_DATA

					SET @CurI = CURSOR FORWARD_ONLY
					FOR select NUM, RAZDEL_NAME from #STR_2_1R WHERE TAB_NUM = @TAB1_NUM order by NUM
					OPEN @CurI
					FETCH NEXT FROM @CurI INTO @RAZDEL_NUM, @RAZDEL_NAME
					WHILE (@@fetch_status <> -1)
					BEGIN
						IF (@@fetch_status <> -2)
						BEGIN		

							INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<' + @RAZDEL_NAME + '>'
					
							SET @CurI1 = CURSOR FORWARD_ONLY
							FOR select NUM, BLOK_NAME from #STR_2_1B WHERE RAZDEL_NUM = @RAZDEL_NUM OR RAZDEL_NUM = @RAZDEL_NUM order by NUM
							OPEN @CurI1
							FETCH NEXT FROM @CurI1 INTO @NUM, @BLOK_NAME
							WHILE (@@fetch_status <> -1)
							BEGIN
								IF (@@fetch_status <> -2)
								BEGIN
									if @num = 8 or @num = 9
									begin
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @BLOK_NAME + '>'
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
											SELECT @lcFNAME,
												CASE WHEN T.COL = 3 THEN SPACE(7) + '<КодСтроки>' + substring(LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))),1,3) + '</КодСтроки>' + CHAR(10) +
													 SPACE(7) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
												ELSE SPACE(7) + '<КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + + '</КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
												END				
											FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'
									end
									else begin
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @BLOK_NAME + '>'
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
											SELECT @lcFNAME,
												CASE WHEN T.COL = 3 THEN SPACE(7) + '<КодСтроки>' + substring(LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))),1,3) + '</КодСтроки>' + CHAR(10) +
													 SPACE(7) + '<РасчетСумм>' + CHAR(10) +
													 SPACE(8) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
												ELSE SPACE(8) + '<СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + + '</СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
												END				
											FROM DBO.SA_SAVED_REPORT_VIEW (@link, 4, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</РасчетСумм>'
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'

									end
								END
								FETCH NEXT FROM @CurI1 INTO @NUM, @BLOK_NAME
							END
							CLOSE @CurI1
							DEALLOCATE @CurI1

							INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</' + @RAZDEL_NAME + '>'
						END
						FETCH NEXT FROM @CurI INTO @RAZDEL_NUM, @RAZDEL_NAME
					END
					CLOSE @CurI
					DEALLOCATE @CurI
						
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TAB1_NAME + '>'
				END
				FETCH NEXT FROM @CurI0 INTO @TAB1_NUM, @TAB1_NAME
			END
			CLOSE @CurI0
			DEALLOCATE @CurI0	
		end

*/

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

		--- ДОП ТАРИФЫ
		---Раздел 2.2 и 2.3
		SET @CurD0 = CURSOR FORWARD_ONLY
		FOR select NUM, TAB_NAME from #TABLES1 order by NUM
		OPEN @CurD0
		FETCH NEXT FROM @CurD0 INTO @TABD_NUM, @TABD_NAME
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN	
			
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @TABD_NAME + '>'
				--- ДОП ТАРИФЫ 01
				--IF @TAB_NUM = 5
				--	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<КодТарифа>' + LTRIM(RTRIM(ISNULL(TFOMS_KT,''))) + '</КодТарифа>' FROM #DEP_DATA

				--SET @Cur = CURSOR FORWARD_ONLY
				--FOR select NUM, RAZDEL_NAME from #STR_2_1R WHERE TAB_NUM = @TAB_NUM order by NUM
				--OPEN @Cur
				--FETCH NEXT FROM @Cur INTO @RAZDEL_NUM, @RAZDEL_NAME
				--WHILE (@@fetch_status <> -1)
				--BEGIN
				--	IF (@@fetch_status <> -2)
				--	BEGIN		

				--		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @RAZDEL_NAME + '>'
						
						SET @Cur = CURSOR FORWARD_ONLY
						FOR select NUM, BLOK_NAME from #STR_2_2C WHERE TAB_NUM = @TABD_NUM OR TAB_NUM = @TABD_NUM order by NUM
						OPEN @Cur
						FETCH NEXT FROM @Cur INTO @NUM, @BLOK_NAME
						WHILE (@@fetch_status <> -1)
						BEGIN
							IF (@@fetch_status <> -2)
							BEGIN
								if @num = 5 or @num = 10
								begin
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @BLOK_NAME + '>'
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME,
											CASE WHEN T.COL = 3 THEN SPACE(7) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
												 SPACE(7) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
											ELSE SPACE(7) + '<КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + + '</КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
											END				
										FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'

								end
								else begin
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @BLOK_NAME + '>'
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME,
											CASE WHEN T.COL = 3 THEN SPACE(7) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
												 SPACE(7) + '<РасчетСумм>' + CHAR(10) +
												 SPACE(8) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
											ELSE SPACE(8) + '<СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + + '</СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
											END				
										FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</РасчетСумм>'
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @BLOK_NAME + '>'
								end
							END
							FETCH NEXT FROM @Cur INTO @NUM, @BLOK_NAME
						END
						CLOSE @Cur
						DEALLOCATE @Cur

				--		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @RAZDEL_NAME + '>'
				--	END
				--	FETCH NEXT FROM @Cur INTO @RAZDEL_NUM, @RAZDEL_NAME
				--END
				--CLOSE @Cur
				--DEALLOCATE @Cur
			
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TABD_NAME + '>'
			END
			FETCH NEXT FROM @CurD0 INTO @TABD_NUM, @TABD_NAME

		END
		CLOSE @CurD0
		DEALLOCATE @CurD0

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

		--- ДОП ТАРИФЫ
		---Раздел 2.4_1 и 2.4_2
		SET @Cur00 = CURSOR FORWARD_ONLY
		FOR select NUM2, TAB2_NAME from #TABLES_2
		OPEN @Cur00
		FETCH NEXT FROM @Cur00 INTO @TAB1_NUM, @TAB1_NAME
		WHILE (@@fetch_status <> -1)
		BEGIN
			IF (@@fetch_status <> -2)
			BEGIN	
			
				if (select count(*) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, DEFAULT, DEFAULT) T WHERE T.COL = 3 AND SUMMA <> 0 ) > 0
				BEGIN	
			--- --- доп тариф 01
				IF @TAB1_NUM = 7
				BEGIN
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @TAB1_NAME + '>'
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<КодОснованияРасчетаПоДопТарифу>' + LTRIM(RTRIM('1')) + '</КодОснованияРасчетаПоДопТарифу>'
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ОснованиеЗаполненияРаздела2_4>' + LTRIM(RTRIM('РЕЗУЛЬТАТЫ СПЕЦОЦЕНКИ')) + '</ОснованиеЗаполненияРаздела2_4>'
				end
				SET @Cur000 = CURSOR FORWARD_ONLY
				FOR select NUM, RAZDEL_NAME from #STR_2_4R WHERE TAB_NUM = @TAB1_NUM order by NUM
				OPEN @Cur000
				FETCH NEXT FROM @Cur000 INTO @RAZDEL_NUM, @RAZDEL_NAME
				WHILE (@@fetch_status <> -1)
				BEGIN
					IF (@@fetch_status <> -2)
					BEGIN		

						
						
						
						--NUM TINYINT, RAZDEL_NUM TINYINT, BLOK_NAME
						SET @Cur1 = CURSOR FORWARD_ONLY
						FOR select NUM, BLOK_NAME from #STR_2_4R1 WHERE RAZDEL_NUM = @RAZDEL_NUM order by NUM
						OPEN @Cur1
						FETCH NEXT FROM @Cur1 INTO @TABD_NUM, @TABD_NAME
						WHILE (@@fetch_status <> -1)
						BEGIN
							IF (@@fetch_status <> -2)
							BEGIN		
								
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<' + @RAZDEL_NAME + '>'
								
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
											SELECT @lcFNAME,
													SPACE(6) + '<КодСпециальнойОценкиУсловийТруда>' +
													(CASE WHEN @TABD_NUM = 1 THEN LTRIM(RTRIM('О4'))
														 WHEN @TABD_NUM = 2 THEN LTRIM(RTRIM('В3.4'))
														 WHEN @TABD_NUM = 3 THEN LTRIM(RTRIM('В3.3'))
														 WHEN @TABD_NUM = 4 THEN LTRIM(RTRIM('В3.2'))
														 ELSE LTRIM(RTRIM('В3.1')) END ) + '</КодСпециальнойОценкиУсловийТруда>'
								
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @TABD_NAME + '>'	
									
									
									SET @Cur2 = CURSOR FORWARD_ONLY
									FOR select NUM, BLOK_NAME from #STR_2_4B WHERE RAZDEL_NUM = @TABD_NUM OR RAZDEL_NUM = @TABD_NUM order by NUM
									OPEN @Cur2
									FETCH NEXT FROM @Cur2 INTO @NUM, @BLOK_NAME
									WHILE (@@fetch_status <> -1)
									BEGIN
										IF (@@fetch_status <> -2)
										BEGIN
												
																						
											if @num = 5 or @num = 10 or @num = 15 or @num = 20 or @num = 25
											begin
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '<' + @BLOK_NAME + '>'
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT @lcFNAME,
														CASE WHEN T.COL = 3 THEN SPACE(8) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
															 SPACE(8) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
														ELSE SPACE(8) + '<КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + + '</КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
														END				
													FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</' + @BLOK_NAME + '>'

											end
											else begin
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '<' + @BLOK_NAME + '>'
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT @lcFNAME,
														CASE WHEN T.COL = 3 THEN SPACE(8) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))) + '</КодСтроки>' + CHAR(10) +
															 SPACE(8) + '<РасчетСумм>' + CHAR(10) +
															 SPACE(9) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
														ELSE SPACE(9) + '<СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + + '</СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
														END				
													FROM DBO.SA_SAVED_REPORT_VIEW (@link, 6, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(8) + '</РасчетСумм>'
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</' + @BLOK_NAME + '>'
											end
										END
										FETCH NEXT FROM @Cur2 INTO @NUM, @BLOK_NAME
									END
									CLOSE @Cur2
									DEALLOCATE @Cur2
								
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @TABD_NAME + '>'	
								INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</' + @RAZDEL_NAME + '>'
							END
							FETCH NEXT FROM @Cur1 INTO @TABD_NUM, @TABD_NAME
					
						END
						CLOSE @Cur1
						DEALLOCATE @Cur1						
						
						
						
					END
					FETCH NEXT FROM @Cur000 INTO @RAZDEL_NUM, @RAZDEL_NAME	
				END 	
				CLOSE @Cur000
				DEALLOCATE @Cur000
				
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TAB1_NAME + '>'
				END
				/***************************/	
			--- доп тариф 2
				/***************************/
				if (select count(*) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, DEFAULT, DEFAULT) T WHERE T.COL = 3 AND SUMMA <> 0 ) > 0
				begin
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<' + @TAB1_NAME + '>'
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<КодОснованияРасчетаПоДопТарифу>' + LTRIM(RTRIM('2')) + '</КодОснованияРасчетаПоДопТарифу>'
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ОснованиеЗаполненияРаздела2_4>' + LTRIM(RTRIM('РЕЗУЛЬТАТЫ СПЕЦОЦЕНКИ')) + '</ОснованиеЗаполненияРаздела2_4>'

					SET @CurI0 = CURSOR FORWARD_ONLY
					FOR select NUM, RAZDEL_NAME from #STR_2_4R WHERE TAB_NUM = @TAB1_NUM order by NUM
					OPEN @CurI0
					FETCH NEXT FROM @CurI0 INTO @RAZDEL_NUM, @RAZDEL_NAME
					WHILE (@@fetch_status <> -1)
					BEGIN
						IF (@@fetch_status <> -2)
						BEGIN		

							
														
							--NUM TINYINT, RAZDEL_NUM TINYINT, BLOK_NAME
							SET @CurI00 = CURSOR FORWARD_ONLY
							FOR select NUM, BLOK_NAME from #STR_2_4R1 WHERE RAZDEL_NUM = @RAZDEL_NUM order by NUM
							OPEN @CurI00
							FETCH NEXT FROM @CurI00 INTO @TABD_NUM, @TABD_NAME
							WHILE (@@fetch_status <> -1)
							BEGIN
								IF (@@fetch_status <> -2)
								BEGIN	
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<' + @RAZDEL_NAME + '>'	
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
											SELECT @lcFNAME,
													SPACE(6) + '<КодСпециальнойОценкиУсловийТруда>' +
													(CASE WHEN @TABD_NUM = 1 THEN LTRIM(RTRIM('О4'))
														 WHEN @TABD_NUM = 2 THEN LTRIM(RTRIM('В3.4'))
														 WHEN @TABD_NUM = 3 THEN LTRIM(RTRIM('В3.3'))
														 WHEN @TABD_NUM = 4 THEN LTRIM(RTRIM('В3.2'))
														 ELSE LTRIM(RTRIM('В3.1')) END ) + '</КодСпециальнойОценкиУсловийТруда>'
									
									
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<' + @TABD_NAME + '>'	
										
										
										SET @CurI000 = CURSOR FORWARD_ONLY
										FOR select NUM, BLOK_NAME from #STR_2_4B WHERE RAZDEL_NUM = @TABD_NUM OR RAZDEL_NUM = @TABD_NUM order by NUM
										OPEN @CurI000
										FETCH NEXT FROM @CurI000 INTO @NUM, @BLOK_NAME
										WHILE (@@fetch_status <> -1)
										BEGIN
											IF (@@fetch_status <> -2)
											BEGIN
												if @num = 5 or @num = 10 or @num = 15 or @num = 20 or @num = 25
												begin
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '<' + @BLOK_NAME + '>'
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT @lcFNAME,
															CASE WHEN T.COL = 3 THEN SPACE(8) + '<КодСтроки>' + substring(LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))),1,3) + '</КодСтроки>' + CHAR(10) +
																 SPACE(8) + '<КоличествоЗЛ_Всего>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + '</КоличествоЗЛ_Всего>'
															ELSE SPACE(8) + '<КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA),''))) + + '</КоличествоЗЛ_' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
															END				
														FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</' + @BLOK_NAME + '>'

												end
												else begin
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '<' + @BLOK_NAME + '>'
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT @lcFNAME,
															CASE WHEN T.COL = 3 THEN SPACE(8) + '<КодСтроки>' + substring(LTRIM(RTRIM(ISNULL(T.ROW_CODE,''))),1,3) + '</КодСтроки>' + CHAR(10) +
																 SPACE(8) + '<РасчетСумм>' + CHAR(10) +
																 SPACE(9) + '<СуммаВсегоСначалаРасчетногоПериода>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + '</СуммаВсегоСначалаРасчетногоПериода>'
															ELSE SPACE(9) + '<СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),T.SUMMA2),''))) + + '</СуммаПоследние' + LTRIM(RTRIM(CONVERT(VARCHAR(1),T.COL - 3))) + 'месяц>'
															END				
														FROM DBO.SA_SAVED_REPORT_VIEW (@link, 7, @NUM, DEFAULT) T WHERE T.COL IN (3,4,5,6) ORDER BY T.COL
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(8) + '</РасчетСумм>'
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(7) + '</' + @BLOK_NAME + '>'
												end
											END
											FETCH NEXT FROM @CurI000 INTO @NUM, @BLOK_NAME
										END
										CLOSE @CurI000
										DEALLOCATE @CurI000
									
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '</' + @TABD_NAME + '>'	
									
									INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</' + @RAZDEL_NAME + '>'
								END
								FETCH NEXT FROM @CurI00 INTO @TABD_NUM, @TABD_NAME
						
							END
							CLOSE @CurI00
							DEALLOCATE @CurI00						
							
							
							
						END
						FETCH NEXT FROM @CurI0 INTO @RAZDEL_NUM, @RAZDEL_NAME	
					END 	
					CLOSE @CurI0
					DEALLOCATE @CurI0
				
					INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TAB1_NAME + '>'
				/*****************/
				END
			
				--INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</' + @TAB1_NAME + '>'
			end	
			FETCH NEXT FROM @Cur00 INTO @TAB1_NUM, @TAB1_NAME
		END
		CLOSE @Cur00
		DEALLOCATE @Cur00

		-----Разделы 2.5.1 и 2.5.2
		CREATE TABLE #PACHKA_ISH (
			LINK INT, NOM_PACH VARCHAR(10), SUM_BASE NUMERIC(18,2), SUM_NACH NUMERIC(18,2), KOL_ZL NUMERIC(5),
			NAME_FILE VARCHAR(254))

		CREATE TABLE #TAB3 (ROW_CODE VARCHAR(10), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
		INSERT INTO #TAB3 (ROW_CODE, COL, SUMMA, STR_VAL)
		SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

		INSERT INTO #PACHKA_ISH (NOM_PACH, SUM_BASE, SUM_NACH, KOL_ZL, NAME_FILE)
		SELECT DISTINCT
			NOM_PACH = (SELECT TOP 1 ROW_CODE FROM #TAB3 T WHERE T.COL = 2 AND T.ROW_CODE = T3.ROW_CODE),
			SUM_BASE = (SELECT TOP 1 SUMMA FROM #TAB3 T WHERE T.COL = 3 AND T.ROW_CODE = T3.ROW_CODE),
			SUM_NACH = (SELECT TOP 1 SUMMA FROM #TAB3 T WHERE T.COL = 4 AND T.ROW_CODE = T3.ROW_CODE),
			KOL_ZL = (SELECT TOP 1 SUMMA FROM #TAB3 T WHERE T.COL = 5 AND T.ROW_CODE = T3.ROW_CODE),
			NAME_FILE = (SELECT TOP 1 STR_VAL FROM #TAB3 T WHERE T.COL = 6 AND T.ROW_CODE = T3.ROW_CODE)
		FROM
			#TAB3 T3

		DROP TABLE #TAB3

		DECLARE @NUM_pp INT
		SET @NUM_pp = 0
		UPDATE #PACHKA_ISH SET @NUM_pp = @NUM_pp + 1, LINK = @NUM_pp

		
		CREATE TABLE #PACHKA_KOR (
			LINK INT, NOM_PACH VARCHAR(4), PERIOD_CODE VARCHAR(1), PERIOD_YEAR VARCHAR(4),SUM_D NUMERIC(18,2), SUM_D_STR NUMERIC(18,2) , SUM_D_NAK NUMERIC(18,2), KOL_ZL NUMERIC(5),
			NAME_FILE VARCHAR(254))

		CREATE TABLE #TAB4 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
		INSERT INTO #TAB4 (ROW_CODE, COL, SUMMA, STR_VAL)
		SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

		INSERT INTO #PACHKA_KOR (NOM_PACH, PERIOD_CODE, PERIOD_YEAR,SUM_D, SUM_D_STR, SUM_D_NAK, KOL_ZL, NAME_FILE)
		SELECT DISTINCT
			NOM_PACH = (SELECT TOP 1 ROW_CODE FROM #TAB4 T WHERE T.COL = 2 AND T.ROW_CODE = T4.ROW_CODE),
			PERIOD_CODE = (SELECT TOP 1 STR_VAL FROM #TAB4 T WHERE T.COL = 3 AND T.ROW_CODE = T4.ROW_CODE),
			PERIOD_YEAR = (SELECT TOP 1 STR_VAL FROM #TAB4 T WHERE T.COL = 4 AND T.ROW_CODE = T4.ROW_CODE),
			SUM_D = (SELECT TOP 1 SUMMA FROM #TAB4 T WHERE T.COL = 5 AND T.ROW_CODE = T4.ROW_CODE),
			SUM_D_STR = (SELECT TOP 1 SUMMA FROM #TAB4 T WHERE T.COL = 6 AND T.ROW_CODE = T4.ROW_CODE),
			SUM_D_NAK = (SELECT TOP 1 SUMMA FROM #TAB4 T WHERE T.COL = 7 AND T.ROW_CODE = T4.ROW_CODE),
			KOL_ZL = (SELECT TOP 1 SUMMA FROM #TAB4 T WHERE T.COL = 8 AND T.ROW_CODE = T4.ROW_CODE),
			NAME_FILE = (SELECT TOP 1 STR_VAL FROM #TAB4 T WHERE T.COL = 9 AND T.ROW_CODE = T4.ROW_CODE)
		FROM
			#TAB4 T4

		DROP TABLE #TAB4
		
		SET @NUM_pp = 0
		UPDATE #PACHKA_KOR SET @NUM_pp = @NUM_pp + 1, LINK = @NUM_pp


		IF (SELECT COUNT(*) FROM #PACHKA_ISH) > 0 -- исходные сведения
			OR (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 8, DEFAULT, DEFAULT) WHERE COL = 5 AND SUMMA2 <> 0) > 0
		BEGIN
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '<Раздел_2_5>'

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ПереченьПачекИсходныхСведенийПУ>'
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<КоличествоПачек>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),(SELECT COUNT(*) FROM #PACHKA_ISH)),''))) + '</КоличествоПачек>'

			UNION ALL SELECT @lcFNAME,
				SPACE(6) + '<СведенияОпачкеИсходных>' + CHAR(10) +
					SPACE(7) + '<НомерПП>' + LTRIM(RTRIM(CONVERT(VARCHAR(10),ISNULL(LINK,0)))) + '</НомерПП>' + CHAR(10) +			
					SPACE(7) + '<БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_BASE,0)))) + '</БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + CHAR(10) +	
					SPACE(7) + '<СтраховыхВзносовОПС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_NACH,0)))) + '</СтраховыхВзносовОПС>' + CHAR(10) +	
					SPACE(7) + '<КоличествоЗЛвПачке>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(KOL_ZL,0)))) + '</КоличествоЗЛвПачке>' + CHAR(10) +
					SPACE(7) + '<ИмяФайла>' + LTRIM(RTRIM(ISNULL(NAME_FILE,''))) + '</ИмяФайла>'+ CHAR(10) +					
					SPACE(6) + '</СведенияОпачкеИсходных>'		
			    FROM #PACHKA_ISH
			UNION ALL SELECT @lcFNAME,
				SPACE(7) + '<ИтогоСведенияПоПачкам>' + CHAR(10) +
					SPACE(8) + '<БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SUM_BASE),0)))) + '</БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + CHAR(10) +			
					SPACE(8) + '<СтраховыхВзносовОПС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SUM_NACH),0)))) + '</СтраховыхВзносовОПС>' + CHAR(10) +
					SPACE(8) + '<КоличествоЗЛвПачке>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(KOL_ZL),0)))) + '</КоличествоЗЛвПачке>' + CHAR(10) +
				SPACE(7) + '</ИтогоСведенияПоПачкам>'
			FROM #PACHKA_ISH	
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ПереченьПачекИсходныхСведенийПУ>'

			IF (SELECT COUNT(*) FROM #PACHKA_KOR) > 0 -- исходные сведения
				OR (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 9, DEFAULT, DEFAULT) WHERE COL = 8 AND SUMMA2 <> 0) > 0
			BEGIN
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '<ПереченьПачекКорректирующихСведенийПУ>'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(6) + '<КоличествоПачек>'+ LTRIM(RTRIM(ISNULL(CONVERT(VARCHAR(20),(SELECT COUNT(*) FROM #PACHKA_KOR)),''))) + '</КоличествоПачек>'

				UNION ALL SELECT @lcFNAME,
					SPACE(6) + '<СведенияОпачкеКорректирующих>' + CHAR(10) +
						SPACE(7) + '<НомерПП>' + LTRIM(RTRIM(CONVERT(VARCHAR(10),ISNULL(LINK,0)))) + '</НомерПП>' + CHAR(10) +			
						SPACE(7) + '<КорректируемыйОтчетныйПериод>' + CHAR(10) +
							SPACE(8) + '<Квартал>' + LTRIM(RTRIM(ISNULL(/*(CASE WHEN */ PERIOD_CODE/*= '1' THEN '3'
																			 WHEN PERIOD_CODE= '2' THEN '6'
																			 WHEN PERIOD_CODE= '3' THEN '9'
																			 ELSE 0 END
																		 )*/,''))) + '</Квартал>' + CHAR(10) +	
							SPACE(8) + '<Год>' + LTRIM(RTRIM(ISNULL(PERIOD_YEAR,''))) + '</Год>' + CHAR(10) +
							SPACE(8) + '<Название>' + LTRIM(RTRIM(ISNULL((CASE WHEN PERIOD_CODE= '1' THEN 'С 01.01.'+PERIOD_YEAR+' ПО 31.03.'+PERIOD_YEAR+''
																			 WHEN PERIOD_CODE= '2' THEN 'С 01.01.'+PERIOD_YEAR+' ПО 30.06.'+PERIOD_YEAR+''
																			 WHEN PERIOD_CODE= '3' THEN 'С 01.01.'+PERIOD_YEAR+' ПО 30.09.'+PERIOD_YEAR+''
																			 ELSE 'С 01.01.'+PERIOD_YEAR+' ПО 31.12.'+PERIOD_YEAR+'' END
																		 ),''))) + '</Название>' + CHAR(10) +
						SPACE(7) + '</КорректируемыйОтчетныйПериод>' + CHAR(10) +
						SPACE(7) + '<ДоначисленоСтраховыхВзносовОПС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_D,0)))) + '</ДоначисленоСтраховыхВзносовОПС>' + CHAR(10) +	
						SPACE(7) + '<ДоначисленоНаСтраховуюЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_D_STR,0)))) + '</ДоначисленоНаСтраховуюЧасть>' + CHAR(10) +	
						SPACE(7) + '<ДоначисленоНаНакопительнуюЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_D_NAK,0)))) + '</ДоначисленоНаНакопительнуюЧасть>' + CHAR(10) +	
						SPACE(7) + '<КоличествоЗЛвПачке>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(KOL_ZL,0)))) + '</КоличествоЗЛвПачке>' + CHAR(10) +
						SPACE(7) + '<ИмяФайла>' + LTRIM(RTRIM(ISNULL(NAME_FILE,''))) + '</ИмяФайла>'+ CHAR(10) +					
					SPACE(6) + '</СведенияОпачкеКорректирующих>' 	
					FROM #PACHKA_KOR
				UNION ALL SELECT @lcFNAME,
					SPACE(7) + '<ИтогоСведенияПоПачкамКорректирующих>' + CHAR(10) +
						SPACE(8) + '<ДоначисленоСтраховыхВзносовОПС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SUM_D),0)))) + '</ДоначисленоСтраховыхВзносовОПС>' + CHAR(10) +			
						SPACE(8) + '<ДоначисленоНаСтраховуюЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SUM_D_STR),0)))) + '</ДоначисленоНаСтраховуюЧасть>' + CHAR(10) +
						SPACE(8) + '<ДоначисленоНаНакопительнуюЧасть>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(SUM_D_NAK),0)))) + '</ДоначисленоНаНакопительнуюЧасть>' + CHAR(10) +
						SPACE(8) + '<КоличествоЗЛвПачке>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM(KOL_ZL),0)))) + '</КоличествоЗЛвПачке>' + CHAR(10) +
					SPACE(7) + '</ИтогоСведенияПоПачкамКорректирующих>'
				FROM #PACHKA_KOR	
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(5) + '</ПереченьПачекКорректирующихСведенийПУ>'
			END


			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(4) + '</Раздел_2_5>'	

		END


		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(3) + '</' + @TAB_NAME + '>'


	END
	FETCH NEXT FROM @Cur0 INTO @TAB_NUM, @TAB_NAME
END
CLOSE @Cur0
DEALLOCATE @Cur0


drop table #t21

-----Разделы 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
		IF @Period_Number = 1 AND @YEAR = '2015'  -- если первый квартал 2015 то радел Раздел3_2 выводится (если заполнен) , со 2го квартала(полугодия) 2015 не заполняется   		
		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 	
	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
		IF @Period_Number = 1 AND @YEAR = '2015'  -- если первый квартал 2015 то радел Раздел3_2 выводится (если заполнен) , со 2го квартала(полугодия) 2015 не заполняется   
		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 
	END --IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 10, 4, DEFAULT) WHERE SUMMA <> 0) > 0
	
	DECLARE @NUM_TABL INT ---@ со второго квартала @NUM_TABL = 10 на первый квартал @NUM_TABL = 11
	IF @Period_Number != 1 AND @YEAR = '2015'
	BEGIN
		SET @NUM_TABL = 10
	END
	ELSE BEGIN 
		SET @NUM_TABL = 11
	END 	

	--Раздел3_3
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, @NUM_TABL, DEFAULT, DEFAULT) WHERE COL = 3 AND SUMMA <> 0) > 0 -- информ. технол. @ со второго квартала @NUM_TABL = 10 на первый квартал @NUM_TABL = 11
	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, @NUM_TABL, 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, @NUM_TABL, 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, @NUM_TABL, 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, @NUM_TABL, 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, @NUM_TABL, 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
		IF @Period_Number = 1 AND @YEAR = '2015'  -- если первый квартал 2015 то радел Раздел3_2 выводится (если заполнен) , со 2го квартала(полугодия) 2015 не заполняется   
		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	
	END --IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, 12, DEFAULT, DEFAULT) WHERE COL = 5 AND SUMMA <> 0) > 0
	
	SET @NUM_TABL = @NUM_TABL + 2  
----Раздел3_5	
	IF (SELECT COUNT(*) FROM DBO.SA_SAVED_REPORT_VIEW (@LINK, @NUM_TABL, 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, @NUM_TABL, 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, @NUM_TABL, 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, @NUM_TABL, 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, @NUM_TABL, 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, @NUM_TABL, 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, @NUM_TABL, 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, @NUM_TABL, 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, @NUM_TABL, 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, @NUM_TABL, 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) + '<СуммаДоначисленныхВзносовЗаПериодНачинаяС2014>' + 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) +	
				
				CASE WHEN LTRIM(RTRIM(ISNULL(CODE_OSN,''))) != '' THEN   
				(SPACE(4) + '<КодОснованияДляДопТарифа>' + LTRIM(RTRIM(CONVERT(VARCHAR(1),ISNULL(OSN,0)))) + '</КодОснованияДляДопТарифа>')  
				 END + 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) + '<СуммаДоначисленныхВзносовОПС2014всего>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_14,0)))) + '</СуммаДоначисленныхВзносовОПС2014всего>' + CHAR(10) +
				SPACE(4) + '<СуммаДоначисленныхВзносовОПС2014превыщающие>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_LIM_14,0)))) + '</СуммаДоначисленныхВзносовОПС2014превыщающие>' + CHAR(10) +
				SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховуюВсего>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR,0)))) + '</СуммаДоначисленныхВзносовНаСтраховуюВсего>' + CHAR(10) +
				SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховуюПревышающие>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_LIM,0)))) + '</СуммаДоначисленныхВзносовНаСтраховуюПревышающие>' + CHAR(10) +
				SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_NAK,0)))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10) +
				SPACE(4) + '<СтраховыхДоначисленныхВзносовПоДопТарифуЧ1>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_D1,0)))) + '</СтраховыхДоначисленныхВзносовПоДопТарифуЧ1>' + CHAR(10) +
				SPACE(4) + '<СтраховыхДоначисленныхВзносовПоДопТарифуЧ2>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_D2,0)))) + '</СтраховыхДоначисленныхВзносовПоДопТарифуЧ2>' + CHAR(10) +								
				SPACE(4) + '<СтраховыхДоначисленныхВзносовПоДопТарифуЧ2_1>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_STR_D2_1,0))))  + '</СтраховыхДоначисленныхВзносовПоДопТарифуЧ2_1>' + CHAR(10) +								
				SPACE(4) + '<СтраховыеВзносыОМС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SUM_MED_STR,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) + '</СуммаДоначисленныхВзносовЗаПериодНачинаяС2014>'
		FROM #DONACHISL				


		UNION ALL SELECT @lcFNAME,
			SPACE(3) + '<ИтогоДоначисленоНачинаяС2014>' + CHAR(10) +
				SPACE(4) + '<СуммаДоначисленныхВзносовОПС2014всего>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_14,0))))) + '</СуммаДоначисленныхВзносовОПС2014всего>' + CHAR(10) +
				SPACE(4) + '<СуммаДоначисленныхВзносовОПС2014превыщающие>' +LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_LIM_14,0))))) + '</СуммаДоначисленныхВзносовОПС2014превыщающие>' + 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) + '<СтраховыхДоначисленныхВзносовПоДопТарифуЧ2_1>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_STR_D2_1,0))))) + '</СтраховыхДоначисленныхВзносовПоДопТарифуЧ2_1>' + CHAR(10) +								
				SPACE(4) + '<СтраховыеВзносыОМС>' + LTRIM(RTRIM(CONVERT(VARCHAR(20),SUM(ISNULL(SUM_MED_STR,0))))) + '</СтраховыеВзносыОМС>' + CHAR(10) +	
			SPACE(3) + '</ИтогоДоначисленоНачинаяС2014>'
		
		
			/*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) + '</РАСЧЕТ_ПО_СТРАХОВЫМ_ВЗНОСАМ_НА_ОПС_И_ОМС_ПЛАТЕЛЬЩИКАМИ_ПРОИЗВОДЯЩИМИ_ВЫПЛАТЫ_ФЛ_2015>'

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(1) + '</ПачкаВходящихДокументов>'
	UNION ALL SELECT @lcFNAME, SPACE(0) + '</ФайлПФР>'	


/*-----------------------------------------------------------------------------------------------*/


--Раздел_6


--ОПИСЬ

CREATE TABLE #OPIS (
	LINK INT, [TYPE] INT, NOM_PP INT, NOM_PACH VARCHAR(10), SUM_BASE NUMERIC(18,2), SUM_STR NUMERIC(18,2), PERS_CNT NUMERIC(5), DATE_DOC VARCHAR(10),
	PER VARCHAR(1), YEAR_BEGIN VARCHAR(4), PER_EDT VARCHAR(1), YEAR_EDT VARCHAR(4), F_NAME varchar(100), link_doc int)

CREATE TABLE #TAB16 (ROW_CODE VARCHAR(10), COL INT, SUMMA NUMERIC(18), SUMMA2 NUMERIC(18,2), STR_VAL VARCHAR(254))
INSERT INTO #TAB16 (ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL)
SELECT ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, DEFAULT, DEFAULT) T WHERE T.COL >= 3 ORDER BY T.COL

CREATE TABLE #TAB17 (ROW_CODE VARCHAR(10), COL INT, SUMMA NUMERIC(18), SUMMA2 NUMERIC(18,2), STR_VAL VARCHAR(254))
INSERT INTO #TAB17 (ROW_CODE, COL, SUMMA,SUMMA2, STR_VAL)
SELECT ROW_CODE, COL, SUMMA, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 9, DEFAULT, DEFAULT) T WHERE T.COL >= 3 ORDER BY T.COL


INSERT INTO #OPIS ([TYPE], NOM_PACH, SUM_BASE, SUM_STR, PERS_CNT, DATE_DOC,	PER, YEAR_BEGIN,F_NAME, link_doc)
SELECT DISTINCT
	[TYPE] = (SELECT TOP 1 summa FROM #TAB16 T WHERE T.COL = 8 AND T.ROW_CODE = T16.ROW_CODE),
	NOM_PACH = (SELECT TOP 1 LTRIM(RTRIM(ROW_CODE)) FROM #TAB16 T WHERE T.COL = 3 AND T.ROW_CODE = T16.ROW_CODE),
	SUM_BASE = (SELECT TOP 1 SUMMA2 FROM #TAB16 T WHERE T.COL = 3 AND T.ROW_CODE = T16.ROW_CODE),
	SUM_STR = (SELECT TOP 1 SUMMA2 FROM #TAB16 T WHERE T.COL = 4 AND T.ROW_CODE = T16.ROW_CODE),
	PERS_CNT = (SELECT TOP 1 SUMMA FROM #TAB16 T WHERE T.COL = 5 AND T.ROW_CODE = T16.ROW_CODE),
	DATE_DOC = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB16 T WHERE T.COL = 7 AND T.ROW_CODE = T16.ROW_CODE),
	PER = (SELECT TOP 1 LTRIM(RTRIM(str(SUMMA))) FROM #TAB16 T WHERE T.COL = 9 AND T.ROW_CODE = T16.ROW_CODE),
	YEAR_BEGIN = (SELECT TOP 1 LTRIM(RTRIM(str(SUMMA))) FROM #TAB16 T WHERE T.COL = 10 AND T.ROW_CODE = T16.ROW_CODE),
	F_NAME = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB16 T WHERE T.COL = 6 AND T.ROW_CODE = T16.ROW_CODE),
	LINK_DOC = (SELECT TOP 1 SUMMA FROM #TAB16 T WHERE T.COL = 11 AND T.ROW_CODE = T16.ROW_CODE)
FROM
	#TAB16 T16

INSERT INTO #OPIS ([TYPE], NOM_PACH, SUM_BASE, SUM_STR, PERS_CNT, DATE_DOC,	PER, YEAR_BEGIN, PER_EDT, YEAR_EDT,F_NAME, link_doc)
SELECT DISTINCT
	[TYPE] = (SELECT TOP 1 summa FROM #TAB17 T WHERE T.COL = 11 AND T.ROW_CODE = T17.ROW_CODE),
	NOM_PACH = (SELECT TOP 1 LTRIM(RTRIM(ROW_CODE)) FROM #TAB17 T WHERE T.COL = 3 AND T.ROW_CODE = T17.ROW_CODE),
	SUM_BASE = (SELECT TOP 1 SUMMA2 FROM #TAB17 T WHERE T.COL = 14 AND T.ROW_CODE = T17.ROW_CODE),
	SUM_STR = (SELECT TOP 1 SUMMA2 FROM #TAB17 T WHERE T.COL = 15 AND T.ROW_CODE = T17.ROW_CODE),
	PERS_CNT = (SELECT TOP 1 SUMMA FROM #TAB17 T WHERE T.COL = 8 AND T.ROW_CODE = T17.ROW_CODE),
	DATE_DOC = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 10 AND T.ROW_CODE = T17.ROW_CODE),
	PER = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 12 AND T.ROW_CODE = T17.ROW_CODE),
	YEAR_BEGIN = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 13 AND T.ROW_CODE = T17.ROW_CODE),
	PER_EDT = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 3 AND T.ROW_CODE = T17.ROW_CODE),
	YEAR_EDT = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 4 AND T.ROW_CODE = T17.ROW_CODE),
	F_NAME = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB17 T WHERE T.COL = 9 AND T.ROW_CODE = T17.ROW_CODE),
	LINK_DOC = (SELECT TOP 1 SUMMA FROM #TAB17 T WHERE T.COL = 16 AND T.ROW_CODE = T17.ROW_CODE)
FROM
	#TAB17 T17	



DROP TABLE #TAB16
DROP TABLE #TAB17


--Проставить номера попорядку
DECLARE @NEXT_NUM3 INT
SET @NEXT_NUM3 = 0
UPDATE #OPIS SET @NEXT_NUM3 = @NEXT_NUM3 + 1, LINK = @NEXT_NUM3

DECLARE @NEXT_NUM4 INT
SET @NEXT_NUM4 = 0
UPDATE #OPIS SET @NEXT_NUM4 = @NEXT_NUM4 + 1, NOM_PP = @NEXT_NUM4
WHERE TYPE = 1


SET @NEXT_NUM4 = 0
UPDATE #OPIS SET @NEXT_NUM4 = @NEXT_NUM4 + 1, NOM_PP = @NEXT_NUM4
WHERE TYPE = 2


---------------------------------------------------------------
----------------------------------------------------------------
DECLARE @Cur3 CURSOR, @Cur4 CURSOR, @LINK_OP INT, @NGROUP int /*Номер пачки*/, @lcF_NAME varchar(254) /*наименование файла*/,
	@NOM_PP INT, @TYP_D varchar(20), @DATE_DOC VARCHAR(10),@SUM_BASE NUMERIC(18,2), @SUM_STR NUMERIC(18,2), @PERS_CNT NUMERIC(5),
	@PER VARCHAR(1), @YEAR_BEGIN VARCHAR(4), @PER_EDT VARCHAR(1), @YEAR_EDT VARCHAR(4)


	CREATE TABLE #TAB61 (LINK INT , FM VARCHAR(100), IM VARCHAR(100), OT VARCHAR(100), SNILS VARCHAR(14), CODE VARCHAR(14), SNILS1 VARCHAR(14), [TYPE] TINYINT , NGROUP VARCHAR(10), FNAME varchar(80), doc_date varchar(10), per_edt int)
	INSERT INTO #TAB61 (CODE, SNILS, FM, IM, OT, SNILS1, [TYPE], NGROUP, FNAME, doc_date, per_edt)
	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 #P_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), UVOL CHAR(1))
	
	INSERT INTO #P_64 (/*LINK,*/ [TYPE], NOM_PP,SNILS,CODE_STR,CODE_KAT,INSUR,B_BEF, GB_BEF, B_AFT,
							PER,YEAR_BEGIN,PER_EDT,YEAR_EDT,FM,IM,OT,
							k_PER_EDT1,k_YEAR_EDT1,k_INSUR1,k_INSUR_1,k_GAIN1,k_PER_EDT2,k_YEAR_EDT2,k_INSUR2,k_INSUR_2,k_GAIN2,
							k_PER_EDT3,k_YEAR_EDT3,k_INSUR3,k_INSUR_3,k_GAIN3,k_PER_EDT4,k_YEAR_EDT4,k_INSUR4,k_INSUR_4,k_GAIN4,
							k_PER_EDT5,k_YEAR_EDT5,k_INSUR5,k_INSUR_5,k_GAIN5,SUM_VZNOS,UVOL)
	SELECT
				---LINK = dEnse_RANK() OVER (ORDER BY  [type],snils ),
				[TYPE],
				NOM_PP = ROW_NUMBER() OVER (PARTITION BY SNILS, [TYPE], PER_EDT ORDER BY CODE_STR , PER_EDT ),
				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,UVOL

		FROM
	(
	SELECT DISTINCT
		[TYPE] = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 12 AND T.ROW_CODE = T64.ROW_CODE),
		SNILS = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 2 AND T.ROW_CODE = T64.ROW_CODE),
		CODE_STR = convert(int, (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 4 AND T.ROW_CODE = T64.ROW_CODE)),
		CODE_KAT = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 5 AND T.ROW_CODE = T64.ROW_CODE),
		INSUR = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 6 AND T.ROW_CODE = T64.ROW_CODE),
		B_BEF = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 7 AND T.ROW_CODE = T64.ROW_CODE ),
		GB_BEF = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 8 AND T.ROW_CODE = T64.ROW_CODE ),
		B_AFT = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 9 AND T.ROW_CODE = T64.ROW_CODE ),
		PER = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL))FROM #TAB64 T WHERE T.COL = 10 AND T.ROW_CODE = T64.ROW_CODE),
		YEAR_BEGIN = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 11 AND T.ROW_CODE = T64.ROW_CODE),
		PER_EDT = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 13 AND T.ROW_CODE = T64.ROW_CODE),
		YEAR_EDT = (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 14 AND T.ROW_CODE = T64.ROW_CODE),
		FM= (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 16 AND T.ROW_CODE = T64.ROW_CODE),
		IM= (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 17 AND T.ROW_CODE = T64.ROW_CODE),
		OT= (SELECT TOP 1 LTRIM(RTRIM(STR_VAL)) FROM #TAB64 T WHERE T.COL = 18 AND T.ROW_CODE = T64.ROW_CODE),
		k_PER_EDT1 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 19 AND T.ROW_CODE = T64.ROW_CODE ),
		k_YEAR_EDT1 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 20 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR1 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 21 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR_1 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 22 AND T.ROW_CODE = T64.ROW_CODE ),
		k_GAIN1 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 23 AND T.ROW_CODE = T64.ROW_CODE),
		
		k_PER_EDT2= (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 24 AND T.ROW_CODE = T64.ROW_CODE ),
		k_YEAR_EDT2 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA)))FROM #TAB64 T WHERE T.COL = 25 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR2 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 26 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR_2 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 27 AND T.ROW_CODE = T64.ROW_CODE ),
		k_GAIN2 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 28 AND T.ROW_CODE = T64.ROW_CODE),
		k_PER_EDT3 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 29 AND T.ROW_CODE = T64.ROW_CODE ),
		k_YEAR_EDT3 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 30 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR3 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 31 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR_3 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 32 AND T.ROW_CODE = T64.ROW_CODE ),
		k_GAIN3 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 33 AND T.ROW_CODE = T64.ROW_CODE),
		k_PER_EDT4 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 34 AND T.ROW_CODE = T64.ROW_CODE ),
		k_YEAR_EDT4 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 35 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR4 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 36 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR_4 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 37 AND T.ROW_CODE = T64.ROW_CODE ),
		k_GAIN4 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 38 AND T.ROW_CODE = T64.ROW_CODE),
		k_PER_EDT5 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 39 AND T.ROW_CODE = T64.ROW_CODE ),
		k_YEAR_EDT5 = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 40 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR5 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 41 AND T.ROW_CODE = T64.ROW_CODE),
		k_INSUR_5 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 42 AND T.ROW_CODE = T64.ROW_CODE ),
		k_GAIN5 = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 43 AND T.ROW_CODE = T64.ROW_CODE),
		SUM_VZNOS = (SELECT TOP 1 SUMMA2 FROM #TAB64 T WHERE T.COL = 44 AND T.ROW_CODE = T64.ROW_CODE),
		UVOL = (SELECT TOP 1 LTRIM(RTRIM(STR(SUMMA))) FROM #TAB64 T WHERE T.COL = 45 AND T.ROW_CODE = T64.ROW_CODE)
		
	FROM
	#TAB64 T64	
		) T	



--exec SA_RSV1_EXPORT_0700_2014     42276

	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)
																						 and PER_EDT  = p.PER_EDT)
	FROM #P_64 p

																


--DELETE FROM #P_64 WHERE ISNULL(INSUR,0) = 0

	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),UVOL CHAR(1))
	
	INSERT INTO #PACHKA_64 (LINK , [TYPE], NOM_PP,SNILS,CODE_STR,CODE_KAT,INSUR,B_BEF, GB_BEF, B_AFT,
							PER,YEAR_BEGIN,PER_EDT,YEAR_EDT,FM,IM,OT,
							k_PER_EDT1,k_YEAR_EDT1,k_INSUR1,k_INSUR_1,k_GAIN1,k_PER_EDT2,k_YEAR_EDT2,k_INSUR2,k_INSUR_2,k_GAIN2,
							k_PER_EDT3,k_YEAR_EDT3,k_INSUR3,k_INSUR_3,k_GAIN3,k_PER_EDT4,k_YEAR_EDT4,k_INSUR4,k_INSUR_4,k_GAIN4,
							k_PER_EDT5,k_YEAR_EDT5,k_INSUR5,k_INSUR_5,k_GAIN5,SUM_VZNOS,UVOL)

	SELECT
				LINK,
				[TYPE],
				NOM_PP = ROW_NUMBER() OVER (PARTITION BY SNILS, [TYPE],PER_EDT ORDER BY  PER_EDT,CODE_STR),
				SNILS,CODE_STR,CODE_KAT,INSUR,B_BEF, GB_BEF, B_AFT,
				PER,YEAR_BEGIN,PER_EDT,YEAR_EDT,FM,IM,OT,
				k_PER_EDT1,k_YEAR_EDT1,k_INSUR1,k_INSUR_1,k_GAIN1,k_PER_EDT2,k_YEAR_EDT2,k_INSUR2,k_INSUR_2,k_GAIN2,
				k_PER_EDT3,k_YEAR_EDT3,k_INSUR3,k_INSUR_3,k_GAIN3,k_PER_EDT4,k_YEAR_EDT4,k_INSUR4,k_INSUR_4,k_GAIN4,
				k_PER_EDT5,k_YEAR_EDT5,k_INSUR5,k_INSUR_5,k_GAIN5,SUM_VZNOS,UVOL		
	FROM
	(
		SELECT DISTINCT LINK , [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, UVOL
		FROM
		#P_64 T64	
	) T	


--exec SA_RSV1_EXPORT_0700_2014    2191
DROP TABLE #P_64
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(30), 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(30), 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(30), 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(30), 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

-------------------------
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,  t2.UVOL
	INTO #RES
	FROM #TAB61 t1 inner join #PACHKA_64 t2
	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
	(	
		ISNULL(t2.INSUR,0) <> 0
		OR EXISTS (
			SELECT *
			FROM
				dbo.SA_SZV4_SVEDENIA s INNER JOIN  dbo.SA_SZV4_STAZH st ON S.link1 = ST.link
			WHERE
				s.link = (SELECT TOP 1 SUMMA FROM DBO.SA_SAVED_REPORT_VIEW (@link, 8, DEFAULT, 11))
				AND T1.NGROUP = S.PACHKA
				AND  s.FM = t2.FM and s.IM = t2.IM  and s.OT = t2.OT AND  s.PF_NUM= t2.SNILS
		)
	)
	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, @UVOL CHAR(1)

UPDATE s
	SET PER = (SELECT TOP 1  per  from #OPIS WHERE TYPE = 1  )
FROM #OPIS s WHERE TYPE = 2

/*СКОРРЕКТИРУЕМ ДАТУ ПО ДАТЕ СОЗДАНИЯ ОТЧЕТА рсв-1*/
UPDATE #TAB61 SET DOC_DATE = CONVERT(VARCHAR(10),@modify_date,104)
UPDATE #OPIS SET DATE_DOC = CONVERT(VARCHAR(10),@modify_date,104)
UPDATE #RES SET DOC_DATE = CONVERT(VARCHAR(10),@modify_date,104)

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  = CASE [TYPE] when 2 then (CASE per WHEN 3 THEN 1 WHEN 6 THEN 2 WHEN 9 THEN 3 ELSE 4 end) else PER end,
	YEAR_BEGIN ,
	PER_EDT = CASE [TYPE] when 2 then (CASE PER_EDT WHEN 3 THEN 1 WHEN 6 THEN 2 WHEN 9 THEN 3 ELSE 0 end) else PER_EDT end,
	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 (@TYP_D = 'ИСХОДНАЯ' AND (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)
					OR
					(@TYP_D = 'КОРРЕКТИРУЮЩАЯ' AND (SELECT COUNT (*) FROM #RES WHERE LTRIM(RTRIM([TYPE])) = LTRIM(RTRIM(@TYP_D))
										--AND  LTRIM(RTRIM(PER)) = LTRIM(RTRIM(ISNULL(@PER,'0')))
										AND  LTRIM(RTRIM(YEAR_BEGIN)) = LTRIM(RTRIM(ISNULL(@YEAR_BEGIN,'0')))
										and LTRIM(RTRIM(PER_EDT)) =  LTRIM(RTRIM(ISNULL(@PER_EDT,'0'))) and LTRIM(RTRIM(YEAR_EDT)) =  LTRIM(RTRIM(ISNULL(@YEAR_EDT,'0')))
										and  LTRIM(RTRIM(DOC_DATE)) = LTRIM(RTRIM(@DATE_DOC)) and LTRIM(RTRIM(FNAME)) = LTRIM(RTRIM(@lcFNAME)) and LTRIM(RTRIM(NGROUP)) = LTRIM(RTRIM(@NGROUP))) > 0)
										
				BEGIN

					SET @PERS_CNT  = (select distinct COUNT (*) FROM
					(select distinct link , ngroup, snils from #RES WHERE LTRIM(RTRIM([TYPE])) = LTRIM(RTRIM(@TYP_D)) /*and LTRIM(RTRIM(PER)) = LTRIM(RTRIM(ISNULL(@PER,'0')))*/ and LTRIM(RTRIM(YEAR_BEGIN)) = LTRIM(RTRIM(ISNULL(@YEAR_BEGIN,'0')))
										and LTRIM(RTRIM(PER_EDT)) =  LTRIM(RTRIM(ISNULL(@PER_EDT,'0'))) and LTRIM(RTRIM(YEAR_EDT)) =  LTRIM(RTRIM(ISNULL(@YEAR_EDT,'0')))
										and  LTRIM(RTRIM(DOC_DATE)) = LTRIM(RTRIM(@DATE_DOC)) and LTRIM(RTRIM(FNAME)) = LTRIM(RTRIM(@lcFNAME)) and LTRIM(RTRIM(NGROUP)) = LTRIM(RTRIM(@NGROUP))
										GROUP BY link , ngroup , SNILS) s)
				
						
				DECLARE @NUM_PACH_PP INT
				SET @NUM_PACH_PP = 1
				
				--exec SA_RSV1_EXPORT_0700_2014    2191
	
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				 SELECT @lcFNAME, 'OEM' --Имя файла
				 UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="Windows-1251" ?>'
				 UNION ALL SELECT @lcFNAME, SPACE(0) + '<ФайлПФР>'
					UNION ALL SELECT @lcFNAME, SPACE(1) + '<ИмяФайла>' + RTRIM(LTRIM(@lcFNAME)) + '</ИмяФайла>'
					UNION ALL SELECT @lcFNAME, SPACE(1) + '<ЗаголовокФайла>'
					 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ВерсияФормата>07.00</ВерсияФормата>'
					 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ТипФайла>ВНЕШНИЙ</ТипФайла>'
					 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ПрограммаПодготовкиДанных>'
						UNION ALL SELECT @lcFNAME, SPACE(3) + '<НазваниеПрограммы>' + @NAME_PROG + '</НазваниеПрограммы>'
						UNION ALL SELECT @lcFNAME, SPACE(3) + '<Версия>' + @VERS_PROG + '</Версия>'
					 UNION ALL SELECT @lcFNAME, SPACE(2) + '</ПрограммаПодготовкиДанных>'
					 UNION ALL SELECT @lcFNAME, SPACE(2) + '<ИсточникДанных>СТРАХОВАТЕЛЬ</ИсточникДанных> '
					UNION ALL SELECT @lcFNAME, SPACE(1) + '</ЗаголовокФайла>'
					UNION ALL SELECT @lcFNAME, SPACE(1) + '<ПачкаВходящихДокументов Окружение="В составе файла" Стадия="До обработки">'
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
					SELECT @lcFNAME, SPACE(2) + '<СВЕДЕНИЯ_ПО_ПАЧКЕ_ДОКУМЕНТОВ_РАЗДЕЛА_6>'


				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
					SELECT @lcFNAME, SPACE(3) + '<НомерВпачке>'+ RTRIM(LTRIM(STR(@NUM_PACH_PP)))+'</НомерВпачке>' + CHAR(10) +
						SPACE(3) + '<ТипВходящейОписи>ОПИСЬ ПАЧКИ</ТипВходящейОписи>' + CHAR(10) +
						SPACE(3) + '<СоставительПачки>' + CHAR(10) +
							SPACE(4) + '<НалоговыйНомер>' + CHAR(10) +
								SPACE(5) + '<ИНН>' + LTRIM(RTRIM(ISNULL((select TOP 1 INN1 FROM #DEP_DATA),'')))+ '</ИНН>' + CHAR(10) +
								SPACE(5) + '<КПП>' + LTRIM(RTRIM(ISNULL((SELECT TOP 1 KPP1 FROM #DEP_DATA),''))) + '</КПП>' + CHAR(10) +
							SPACE(4) + '</НалоговыйНомер>' + CHAR(10) +
							SPACE(4) + '<НаименованиеОрганизации>' + LTRIM(RTRIM(ISNULL((SELECT TOP 1 CONVERT(varchar(50),FULL_NAME) FROM #DEP_DATA),'')))+ '</НаименованиеОрганизации>' + CHAR(10) +
							SPACE(4) + '<НаименованиеКраткое>' + LTRIM(RTRIM(ISNULL( (SELECT TOP 1 ORGNAME FROM #DEP_DATA),''))) + '</НаименованиеКраткое>' + CHAR(10) +
							SPACE(4) + '<РегистрационныйНомер>' + LTRIM(RTRIM(ISNULL( (SELECT TOP 1 PFNUMBER FROM #DEP_DATA),''))) + '</РегистрационныйНомер>' + CHAR(10) +
						SPACE(3) + '</СоставительПачки>' + CHAR(10) +
						SPACE(3) + '<НомерПачки>' + CHAR(10) +
							SPACE(4) + '<Основной>'+LTRIM(RTRIM(@NGROUP))+'</Основной>' + CHAR(10) + 	
						SPACE(3) + '</НомерПачки>' + CHAR(10) + 	
						SPACE(3) + '<СоставДокументов>' + CHAR(10) + 	
							SPACE(4) + '<Количество>' + '1' /*@DOCCOUNT*/ + '</Количество>' + CHAR(10) + 	
							SPACE(4) + '<НаличиеДокументов>' + CHAR(10) + 	
								SPACE(5) + '<ТипДокумента>СВЕДЕНИЯ_О_СУММЕ_ВЫПЛАТ_И_СТРАХОВОМ_СТАЖЕ_ЗЛ</ТипДокумента>' + CHAR(10) + 	
								SPACE(5) + '<Количество>' + RTRIM(LTRIM(STR(@PERS_CNT)))+ '</Количество>' + CHAR(10) + 	
							SPACE(4) + '</НаличиеДокументов>' + CHAR(10) + 	
						SPACE(3) + '</СоставДокументов>' + CHAR(10) + 		

						SPACE(3) + '<ДатаСоставления>' + CONVERT(VARCHAR(10),@DATE_DOC,104)+ '</ДатаСоставления>' + CHAR(10) + 	
						SPACE(3) + '<ТипСведений>' + RTRIM(LTRIM(@TYP_D)) + '</ТипСведений>' + CHAR(10) + 	

						SPACE(3) + '<ОтчетныйПериод>'+ CHAR(10) + 	
							SPACE(4) + '<Квартал>' + CASE @PER WHEN '1' THEN '3'
															 WHEN '2' THEN '6'
															 WHEN '3' THEN '9'
															 ELSE '0'
													 END + '</Квартал>' + CHAR(10) + 	
							SPACE(4) + '<Год>' + @YEAR_BEGIN + '</Год>' + CHAR(10) + 	
							SPACE(4) + '<Название>'
										+	CASE @PER
													WHEN '1' THEN 'С 01.01.'+@YEAR_BEGIN+' ПО 31.03.'+@YEAR_BEGIN
													WHEN '2' THEN 'С 01.01.'+@YEAR_BEGIN+' ПО 30.06.'+@YEAR_BEGIN
													WHEN '3' THEN 'С 01.01.'+@YEAR_BEGIN+' ПО 30.09.'+@YEAR_BEGIN
													WHEN '4' THEN 'С 01.01.'+@YEAR_BEGIN+' ПО 31.12.'+@YEAR_BEGIN
													ELSE ''
											END									
											+ '</Название>' + CHAR(10) + 	
						SPACE(3) + '</ОтчетныйПериод>' + CHAR(10) +
											
						CASE WHEN @TYP_D = 'КОРРЕКТИРУЮЩАЯ' and @PER_EDT IS NOT NULL THEN ( SPACE(3) + '<КорректируемыйОтчетныйПериод>' + CHAR(10) +
																SPACE(4) + '<Квартал>' + CASE @PER_EDT  WHEN '1' THEN '3'
																									 WHEN '2' THEN '6'
																									 WHEN '3' THEN '9'	
																									 ELSE '0'
																						 END+ '</Квартал>' + CHAR(10) +
																SPACE(4) + '<Год>' + @YEAR_EDT + '</Год>' + CHAR(10) +
																SPACE(4) + '<Название>' +
																			CASE @PER_EDT
																					WHEN '1' THEN 'С 01.01.'+@YEAR_EDT+' ПО 31.03.'+@YEAR_EDT
																					WHEN '2' THEN 'С 01.01.'+@YEAR_EDT+' ПО 30.06.'+@YEAR_EDT
																					WHEN '3' THEN 'С 01.01.'+@YEAR_EDT+' ПО 30.09.'+@YEAR_EDT
																					WHEN '4' THEN 'С 01.01.'+@YEAR_EDT+' ПО 31.12.'+@YEAR_EDT
																					ELSE ''
																			END									
																			+ '</Название>' + CHAR(10) +
															SPACE(3) + '</КорректируемыйОтчетныйПериод>' ) ELSE '' END + CHAR(10) +
													SPACE(3) + '<БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + RTRIM(LTRIM(STR(COALESCE(@SUM_BASE,0),15,2))) + '</БазаДляНачисленияСтраховыхВзносовНеПревышающаяПредельную>' + CHAR(10) +
													SPACE(3) + '<СтраховыхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(@SUM_STR,0),15,2))) + '</СтраховыхВзносовОПС>'
				
						INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
						SELECT @lcFNAME,SPACE(2) + '</СВЕДЕНИЯ_ПО_ПАЧКЕ_ДОКУМЕНТОВ_РАЗДЕЛА_6>'									


						DECLARE @NUM_l INT, @num_old INT
						SET @NUM_l = 0
						SET @num_old = 0

						SET @Cur4 = CURSOR FORWARD_ONLY
						FOR
						SELECT LINK,[TYPE],SNILS,PER,YEAR_BEGIN,PER_EDT,YEAR_EDT,FM,IM,OT, DOC_DATE, MAX(UVOL)/*, 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]
							--exec SA_RSV1_EXPORT_0700_2014    42276	
						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, @UVOL /*, @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) + '</ФИО>' 	
									--
									IF @Period_Number !=1 AND @YEAR >='2015' 
									BEGIN 
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
											SELECT @lcFNAME, case when @UVOL = 1 THEN  (SPACE(3) + '<СведенияОбУвольнении>'+ 'УВОЛЕН'+  '</СведенияОбУвольнении>') ELSE '' end
									END 	
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)						
										SELECT @lcFNAME, SPACE(3) + '<ОтчетныйПериод>'
											UNION ALL SELECT @lcFNAME, SPACE(4) + '<Квартал>' + CASE @PER_r WHEN '1' THEN '3'
																										  WHEN '2' THEN '6'
																										  WHEN '3' THEN '9'
																										  ELSE '0'
																										  END
																				+ '</Квартал>' 	
											UNION ALL SELECT @lcFNAME, SPACE(4) + '<Год>' + @YEAR_BEGIN_r + '</Год>'	
											UNION ALL SELECT @lcFNAME, SPACE(4) + '<Название>' +	CASE @PER_R
																											WHEN '1' THEN 'С 01.01.'+@YEAR_BEGIN_R+' ПО 31.03.'+@YEAR_BEGIN_R
																											WHEN '2' THEN 'С 01.01.'+@YEAR_BEGIN_R+' ПО 30.06.'+@YEAR_BEGIN_R
																											WHEN '3' THEN 'С 01.01.'+@YEAR_BEGIN_R+' ПО 30.09.'+@YEAR_BEGIN_R
																											WHEN '4' THEN 'С 01.01.'+@YEAR_BEGIN_R+' ПО 31.12.'+@YEAR_BEGIN_R
																											ELSE ''
																									END									
																				+ '</Название>' 	
											UNION ALL SELECT @lcFNAME,SPACE(3) + '</ОтчетныйПериод>'
											
											IF UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'КОРРЕКТИРУЮЩАЯ'
												INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														 SELECT @lcFNAME, SPACE(3) + '<КорректируемыйОтчетныйПериод>' + CHAR(10) + CHAR(13) +
																				SPACE(4) + '<Квартал>' + CASE @PER_EDT_R WHEN '1' THEN '3'
																														 WHEN '2' THEN '6'
																														 WHEN '3' THEN '9'	
																														 ELSE '0'
																										END
																						+ '</Квартал>' + CHAR(10) + CHAR(13) +
																				SPACE(4) + '<Год>' + @YEAR_EDT_R + '</Год>' + CHAR(10) + CHAR(13) +
																				SPACE(4) + '<Название>' +
																							CASE @PER_EDT_R
																										WHEN '1' THEN 'С 01.01.'+@YEAR_EDT_R+' ПО 31.03.'+@YEAR_EDT_R
																										WHEN '2' THEN 'С 01.01.'+@YEAR_EDT_R+' ПО 30.06.'+@YEAR_EDT_R
																										WHEN '3' THEN 'С 01.01.'+@YEAR_EDT_R+' ПО 30.09.'+@YEAR_EDT_R
																										WHEN '4' THEN 'С 01.01.'+@YEAR_EDT_R+' ПО 31.12.'+@YEAR_EDT_R
																										ELSE ''
																							END									
																						+ '</Название>' + CHAR(10) + CHAR(13) +
																		SPACE(3) + '</КорректируемыйОтчетныйПериод>' + CHAR(10) + CHAR(13) +
																		SPACE(3) + '<РегистрационныйНомерКорректируемогоПериода>'+ LTRIM(RTRIM(ISNULL( (SELECT TOP 1 PFNUMBER FROM #DEP_DATA),''))) +'</РегистрационныйНомерКорректируемогоПериода>'
											
																					
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT @lcFNAME ,SPACE(3) + '<СведенияОсуммеВыплатИвознагражденийВпользуЗЛ>' + CHAR(10)+
																			 SPACE(4) + '<НомерСтроки>' + LTRIM(RTRIM(ISNULL( ( ROW_NUMBER() OVER (ORDER BY CODE_STR) ),''))) + '</НомерСтроки>' + CHAR(10)+
																			 SPACE(4) + '<ТипСтроки>' + LTRIM(RTRIM(ISNULL( (CASE WHEN CODE_STR = '400' OR CODE_STR = '410' OR CODE_STR = '420' THEN 'ИТОГ' ELSE 'МЕСЦ' END),''))) + '</ТипСтроки>' + CHAR(10)+
																			 SPACE(4) + (CASE WHEN CODE_STR = '400' OR CODE_STR ='410' OR CODE_STR ='420' THEN ''
																							  else  ( '<Месяц>' +	(CASE WHEN CODE_STR = '400' OR CODE_STR ='410' OR CODE_STR ='420' THEN ''
																							
																														  WHEN CODE_STR = '401' OR CODE_STR ='411' OR CODE_STR ='421' THEN
																														  						(CASE WHEN UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'ИСХОДНАЯ'
																														  							  THEN (CASE @PER_r WHEN '1' THEN '1'
																														  												WHEN '2' THEN '4'
																														  												WHEN '3' THEN '7'
																														  												ELSE '10' end)
																														  							  ELSE (CASE @PER_EDT_R WHEN '1' THEN '1'
																														  													WHEN '2' THEN '4'
																														  													WHEN '3' THEN '7'
																														  													ELSE '10' end)
																														  						END)
																																														
																														  WHEN CODE_STR = '402' OR CODE_STR ='412' OR CODE_STR ='422' THEN
																														  						(CASE WHEN UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'ИСХОДНАЯ'
																														  							  THEN (CASE @PER_r WHEN '1' THEN '2'
																														  												WHEN '2' THEN '5'
																														  												WHEN '3' THEN '8'
																														  												ELSE '11' end)
																														  							  ELSE (CASE @PER_EDT_R WHEN '1' THEN '2'
																														  													WHEN '2' THEN '5'
																														  													WHEN '3' THEN '8'
																														  													ELSE '11' end)
																														  						END)
																														
																														  ELSE 					(CASE WHEN UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'ИСХОДНАЯ'
																														  							  THEN (CASE @PER_r WHEN '1' THEN '3'
																														  												WHEN '2' THEN '6'
																														  												WHEN '3' THEN '9'
																														  												ELSE '12' end)
																														  							  ELSE (CASE @PER_EDT_R WHEN '1' THEN '3'
																														  													WHEN '2' THEN '6'
																														  													WHEN '3' THEN '9'
																														  													ELSE '12' end)
																														  						END)
																							                     	      end ) + '</Месяц>'  )
																							  END)   + CHAR(10)+
																									
																			 SPACE(4) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(CODE_STR,''))) + '</КодСтроки>' + CHAR(10)+
																			 SPACE(4) + '<КодКатегории>' + LTRIM(RTRIM(ISNULL(CODE_KAT,''))) + '</КодКатегории>' + CHAR(10)+
																			 SPACE(4) + '<СуммаВыплатИныхВознаграждений>' + RTRIM(LTRIM(STR(COALESCE(INSUR,0),15,2))) + '</СуммаВыплатИныхВознаграждений>' + CHAR(10)+
																			 SPACE(4) + '<НеПревышающиеВсего>' + RTRIM(LTRIM(STR(COALESCE(B_BEF,0),15,2))) + '</НеПревышающиеВсего>' + CHAR(10)+
																			 SPACE(4) + '<НеПревышающиеПоДоговорам>' + RTRIM(LTRIM(STR(COALESCE(GB_BEF,0),15,2))) + '</НеПревышающиеПоДоговорам>' + CHAR(10)+
																			 SPACE(4) + '<ПревышающиеПредельную>' + RTRIM(LTRIM(STR(COALESCE(B_AFT,0),15,2))) + '</ПревышающиеПредельную>' + CHAR(10)+
																	  SPACE(3) + '</СведенияОсуммеВыплатИвознагражденийВпользуЗЛ>'	
													FROM #RES
													WHERE
														link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R
															and OT = @OT_R /*AND PER = @PER_R*/ AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R
															AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R /*and FNAME = @FNAME_R */and LTRIM(RTRIM(NGROUP)) = LTRIM(RTRIM(@NGROUP))
															AND
																(
																CODE_STR LIKE '4[0,1,2]0'
																OR
																CODE_STR NOT LIKE '4[0,1,2]0' AND ISNULL(INSUR,0) <> 0
																)

										
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT @lcFNAME, SPACE(3) + '<СуммаВзносовНаОПС>' + RTRIM(LTRIM(STR(COALESCE(SUM(SUM_VZNOS),0),15,2))) + '</СуммаВзносовНаОПС>'
													FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R
																	and OT = @OT_R /*AND PER = @PER_R*/ AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R
																	AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R */and LTRIM(RTRIM(NGROUP)) = LTRIM(RTRIM(@NGROUP))
																	AND CODE_STR IN ('400','410','420')
						
											
											IF UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) IN ( 'ИСХОДНАЯ', 'КОРРЕКТИРУЮЩАЯ')
											BEGIN

												
												--exec SA_RSV1_EXPORT_0700_2014    2191
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT  @lcFNAME,
															(CASE WHEN (k_INSUR1 <> 0 or k_GAIN1 <> 0) AND  K_YEAR_EDT1 <> 0
															THEN
																	+ SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																				 SPACE(4) + '<НомерСтроки>' + '1' + '</НомерСтроки>' + CHAR(10)+
																				 SPACE(4) + '<ТипСтроки>'+'МЕСЦ'+'</ТипСтроки>' + CHAR(10)+
																				 SPACE(4) + '<Квартал>' +	CASE WHEN K_YEAR_EDT1 >= 2014
																													THEN (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 )
																													ELSE k_per_edt1  END + '</Квартал>' + CHAR(10)+
																				 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(K_YEAR_EDT1,''))) + '</Год>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR1,0),15,2))) + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR_1,0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(k_GAIN1,0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																		  SPACE(3) + '</СведенияОкорректировках>'	
															ELSE
																''																
															END	)
														FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R
																		and OT = @OT_R /*AND PER = @PER_R*/ AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R
																		AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																		AND CODE_STR = '400'
													
														
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT  @lcFNAME,
															(CASE WHEN (k_INSUR2 <> 0 OR k_GAIN2 <> 0) AND  K_YEAR_EDT2 <> 0
															THEN		
																+ SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																				 SPACE(4) + '<НомерСтроки>' + '2' + '</НомерСтроки>' + CHAR(10)+
																				 SPACE(4) + '<ТипСтроки>'+'МЕСЦ'+'</ТипСтроки>' + CHAR(10)+
																				 SPACE(4) + '<Квартал>' +	CASE WHEN K_YEAR_EDT2 >= 2014
																													THEN (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 )
																													ELSE k_per_edt2  END  + '</Квартал>' + CHAR(10)+
																				 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(K_YEAR_EDT2,''))) + '</Год>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR2,0),15,2))) + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR_2,0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(k_GAIN2,0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																		  SPACE(3) + '</СведенияОкорректировках>'	
															ELSE
																''
															END	)			
																		
														FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R
																		and OT = @OT_R /*AND PER = @PER_R*/ AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R
																		AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																		AND CODE_STR = '400'

												

													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT  @lcFNAME,
														    (CASE WHEN (k_INSUR3 <> 0 OR k_GAIN3 <> 0) AND  K_YEAR_EDT3 <> 0
																  THEN
																		+ SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																				 SPACE(4) + '<НомерСтроки>' + '3' + '</НомерСтроки>' + CHAR(10)+
																				 SPACE(4) + '<ТипСтроки>'+'МЕСЦ'+'</ТипСтроки>' + CHAR(10)+
																				 SPACE(4) + '<Квартал>' +	CASE WHEN K_YEAR_EDT3 >= 2014
																													THEN (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 )
																													ELSE k_per_edt3  END + '</Квартал>' + CHAR(10)+
																				 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(K_YEAR_EDT3,''))) + '</Год>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR3,0),15,2))) + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR_3,0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(k_GAIN3,0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																		  SPACE(3) + '</СведенияОкорректировках>'
																ELSE
																	''
																END	)			
																																			  	
														FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R
																		and OT = @OT_R /*AND PER = @PER_R*/ AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R
																		AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																		AND CODE_STR = '400'

												
														INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
															SELECT  @lcFNAME,
																			
																	(CASE WHEN (k_INSUR4 <> 0 OR k_GAIN4 <> 0) AND  K_YEAR_EDT4 <> 0
																		  THEN
																			+ SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																					 SPACE(4) + '<НомерСтроки>' + '4' + '</НомерСтроки>' + CHAR(10)+
																					 SPACE(4) + '<ТипСтроки>'+'МЕСЦ'+'</ТипСтроки>' + CHAR(10)+
																					 SPACE(4) + '<Квартал>' +	CASE WHEN K_YEAR_EDT4 >= 2014
																													THEN (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 )
																													ELSE k_per_edt4  END + '</Квартал>' + CHAR(10)+
																					 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(K_YEAR_EDT4,''))) + '</Год>' + CHAR(10)+
																					 SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR4,0),15,2))) + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																					 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR_4,0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																					 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(k_GAIN4,0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																			  SPACE(3) + '</СведенияОкорректировках>'	
																	  ELSE
																		''
																	  END	)			
																				
															FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R
																			and OT = @OT_R /*AND PER = @PER_R*/ AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R
																			AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																			AND CODE_STR = '400' 																															


													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
														SELECT  @lcFNAME,
																(CASE WHEN (k_INSUR5 <> 0 OR k_GAIN5 <> 0) AND  K_YEAR_EDT5 <> 0
																	  THEN
																		+	SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																				 SPACE(4) + '<НомерСтроки>' + '5' + '</НомерСтроки>' + CHAR(10)+
																				 SPACE(4) + '<ТипСтроки>'+'МЕСЦ'+'</ТипСтроки>' + CHAR(10)+
																				 SPACE(4) + '<Квартал>' +	CASE WHEN K_YEAR_EDT5 >= 2014
																													THEN (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 )
																													ELSE k_per_edt5  END + '</Квартал>' + CHAR(10)+
																				 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(K_YEAR_EDT5,''))) + '</Год>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR5,0),15,2))) + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE(k_INSUR_5,0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																				 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE(k_GAIN5,0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																		  SPACE(3) + '</СведенияОкорректировках>'	
																	  ELSE
																		''
																	  END	)
														FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R
																		and OT = @OT_R /*AND PER = @PER_R*/ AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R
																		AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																		AND CODE_STR = '400'

												
												INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT  @lcFNAME,
															(CASE WHEN (k_INSUR1<>0 or k_INSUR2 <> 0 OR k_INSUR3<>0 OR k_INSUR4<>0 OR k_INSUR5 <> 0) OR (k_INSUR_1<>0 or k_INSUR_2 <> 0 OR k_INSUR_3<>0 OR k_INSUR_4<>0 OR k_INSUR_5 <> 0)
																  THEN
																	+ SPACE(3) + '<СведенияОкорректировках>' + CHAR(10)+
																			 SPACE(4) + '<НомерСтроки>' + (CASE WHEN k_INSUR1<>0 OR k_INSUR_1<>0 and k_INSUR2 = 0 and k_INSUR3 = 0 and k_INSUR4 = 0 AND k_INSUR5 = 0 THEN '2'
																												WHEN k_INSUR2 <> 0 OR k_INSUR_2<>0 and k_INSUR3 = 0 and k_INSUR4 = 0 AND k_INSUR5 = 0 THEN '3'
																												WHEN k_INSUR3 <> 0 OR k_INSUR_3<>0 and k_INSUR4 = 0 AND k_INSUR5 = 0 THEN '4'
																												WHEN k_INSUR4 <> 0 OR k_INSUR_4<>0 AND k_INSUR5 = 0 THEN '5'
																												WHEN k_INSUR5 <> 0 OR k_INSUR_5<>0 THEN '6' ELSE '6' end) + '</НомерСтроки>' + CHAR(10)+
																			 SPACE(4) + '<ТипСтроки>'+'ИТОГ'+'</ТипСтроки>' + CHAR(10)+
																			/* SPACE(4) + '<Квартал>'  +	(CASE WHEN per_edt = '1' THEN '3'
																										WHEN per_edt = '2' THEN '6'
																										WHEN per_edt = '3' THEN '9'
																										ELSE '0'  end ) + '</Квартал>' + CHAR(10)+
																			 SPACE(4) + '<Год>' + LTRIM(RTRIM(ISNULL(YEAR_EDT,''))) + '</Год>' + CHAR(10)+
																			 */SPACE(4) + '<СуммаДоначисленныхВзносовОПС>' + CASE WHEN K_YEAR_EDT1 >=2014 or K_YEAR_EDT2 >=2014 or K_YEAR_EDT3 >=2014 or K_YEAR_EDT4 >=2014 or K_YEAR_EDT5 >=2014 then RTRIM(LTRIM(STR(COALESCE((k_INSUR1+k_INSUR2+k_INSUR3+k_INSUR4+k_INSUR5),0),15,2)))
																																		ELSE '0.00' end + '</СуммаДоначисленныхВзносовОПС>' + CHAR(10)+
																			 SPACE(4) + '<СуммаДоначисленныхВзносовНаСтраховую>' + RTRIM(LTRIM(STR(COALESCE((k_INSUR_1+k_INSUR_2+k_INSUR_3+k_INSUR_4+k_INSUR_5),0),15,2))) + '</СуммаДоначисленныхВзносовНаСтраховую>' + CHAR(10)+
																			 SPACE(4) + '<СуммаДоначисленныхВзносовНаНакопительную>' + RTRIM(LTRIM(STR(COALESCE((k_GAIN1+k_GAIN2+k_GAIN3+k_GAIN4+k_GAIN5),0),15,2))) + '</СуммаДоначисленныхВзносовНаНакопительную>' + CHAR(10)+
																	  SPACE(3) + '</СведенияОкорректировках>'
															ELSE
																''
															END		)	  	
													FROM #RES WHERE link = @LINK_R 	AND [TYPE] = @TYPE_R AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R
																	and OT = @OT_R /*AND PER = @PER_R*/ AND  YEAR_BEGIN = @YEAR_BEGIN_R AND PER_EDT = @PER_EDT_R
																	AND YEAR_EDT = @YEAR_EDT_R AND DOC_DATE = @DATE_DOC_R  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
																	AND CODE_STR = '400'
												
				
												
											END
											
											
											--IF (SELECT COUNT (*) FROM #RES1 WHERE [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R
											--						and OT = @OT_R AND DOC_DATE = @DATE_DOC_R ) > 1
											--BEGIN
											
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													SELECT  @lcFNAME, SPACE(3) + '<СведенияОсуммеВыплатИвознагражденийПоДопТарифу>' + CHAR(10)+
																			 SPACE(4) + '<НомерСтроки>' + LTRIM(RTRIM(ISNULL( NOM_PP,''))) + '</НомерСтроки>' + CHAR(10)+
																			 SPACE(4) + '<ТипСтроки>' + LTRIM(RTRIM(ISNULL( (CASE WHEN CODE_STR = '700' OR CODE_STR = '710' OR CODE_STR = '720' THEN 'ИТОГ' ELSE 'МЕСЦ' END),''))) + '</ТипСтроки>' + CHAR(10)+
																			 SPACE(4) + (CASE WHEN CODE_STR = '700' OR CODE_STR ='710' OR CODE_STR ='720' THEN ''
																							else ('<Месяц>' +	(CASE WHEN CODE_STR = '700' OR CODE_STR ='710' OR CODE_STR ='720' THEN ''
																									WHEN CODE_STR = '701' OR CODE_STR ='711' OR CODE_STR ='721' THEN
																										(CASE WHEN UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'ИСХОДНАЯ'
																											  THEN (CASE @PER_r WHEN '1' THEN '1'
																																WHEN '2' THEN '4'
																																WHEN '3' THEN '7'
																																ELSE '10' end)
						  																					  ELSE (CASE @PER_EDT_R WHEN '1' THEN '1'
						  																											WHEN '2' THEN '4'
						  																											WHEN '3' THEN '7'
						  																											ELSE '10' end)
						  																					  END)
																									WHEN CODE_STR = '702' OR CODE_STR ='712' OR CODE_STR ='722' THEN
																													(CASE WHEN UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'ИСХОДНАЯ'
						  																								  THEN (CASE @PER_r WHEN '1' THEN '2'
						  																													WHEN '2' THEN '5'
						  																													WHEN '3' THEN '8'
						  																													ELSE '11' end)
						  																								  ELSE (CASE @PER_EDT_R WHEN '1' THEN '2'
						  																														WHEN '2' THEN '5'
						  																														WHEN '3' THEN '8'
						  																														ELSE '11' end)
						  																								  END)
																									ELSE (CASE WHEN UPPER(LTRIM(RTRIM(ISNULL((@TYPE_R),'')))) = 'ИСХОДНАЯ'
						  																						  THEN (CASE @PER_r WHEN '1' THEN '3'
						  																											WHEN '2' THEN '6'
						  																											WHEN '3' THEN '9'
						  																											ELSE '12' end)
						  																						  ELSE (CASE @PER_EDT_R WHEN '1' THEN '3'
						  																												WHEN '2' THEN '6'
						  																												WHEN '3' THEN '9'
						  																												ELSE '12' end)
						  																					   END)
																							      end ) + '</Месяц>')
																							end)		+ CHAR(10)+

										
																			 SPACE(4) + '<КодСтроки>' + LTRIM(RTRIM(ISNULL(CODE_STR,''))) + '</КодСтроки>' + CHAR(10)+
																			 SPACE(4) + '<КодСпециальнойОценкиУсловийТруда>' + LTRIM(RTRIM(ISNULL(CODE_SPO,'пустое'))) + '</КодСпециальнойОценкиУсловийТруда>' + CHAR(10)+
																			 SPACE(4) + '<СуммаВыплатПоДопТарифу27-1>' + RTRIM(LTRIM(STR(COALESCE(INC_T1M,0),15,2))) + '</СуммаВыплатПоДопТарифу27-1>' + CHAR(10)+
																			 SPACE(4) + '<СуммаВыплатПоДопТарифу27-2-18>' + RTRIM(LTRIM(STR(COALESCE(INC_T2M,0),15,2))) + '</СуммаВыплатПоДопТарифу27-2-18>' + CHAR(10)+
																	  SPACE(3) + '</СведенияОсуммеВыплатИвознагражденийПоДопТарифу>'	
													FROM #RES1 WHERE link = @LINK_R 	AND [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R
																	and OT = @OT_R /* AND DOC_DATE = @DATE_DOC_R*/
																	AND ((SELECT top 1 isnull(INC_T1M,0) FROM #RES1 WHERE [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R
																	and OT = @OT_R /*AND DOC_DATE = @DATE_DOC_R*/ AND CODE_STR = '700' ) > 0 OR
																		 (SELECT top 1 isnull(INC_T2M,0) FROM #RES1 WHERE [TYPE] = (CASE @TYPE_R when 'ИСХОДНАЯ' THEN 1 WHEN 'КОРРЕКТИРУЮЩАЯ' THEN 2 ELSE 3 END) AND  SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R
																	and OT = @OT_R /*AND DOC_DATE = @DATE_DOC_R*/ AND CODE_STR = '700' ) > 0 )
																	  /*and FNAME = @FNAME_R and NGROUP = @NOM_PACH_R*/
											 --END	

															--exec SA_RSV1_EXPORT_0700_2014   280	
													CREATE TABLE #STAZH_TMP ( link INt, FM VARCHAR(100), IM VARCHAR(100), OT VARCHAR(100), SNILS VARCHAR(14), date1 VARCHAR(10), date2 VARCHAR(10),
																			  T_DOG int , [TU_CODE] VARCHAR (31) ,ter_koef NUMERIC(18,2),[OS_CODE] VARCHAR(94),[EX_CODE] VARCHAR (10),
																			  osob_spis VARCHAR(20), is_dop_m TINYINT,is_dop_d TINYINT , is_dop VARCHAR(20),
																			  [f_is_dop] VARCHAR(63),[P_CODE] VARCHAR(10),ud_dop_m INT,ud_dop_d INT  , ud_dop_k NUMERIC(18,2) , [f_ud_dop] VARCHAR(54))
													INSERT INTO #STAZH_TMP  (link , FM , IM, OT, SNILS, date1, date2,T_DOG, [TU_CODE],ter_koef, [OS_CODE],
																			  [EX_CODE], osob_spis, is_dop_m,is_dop_d, is_dop,[f_is_dop],[P_CODE],ud_dop_m,ud_dop_d, ud_dop_k, [f_ud_dop])
													SELECT	link = ROW_NUMBER() OVER (/*PARTITION */ ORDER BY ST.date1),--st.orders,
															FM = S.FM,
															IM = S.IM,
															OT = S.OT,
															SNILS = S.PF_NUM,
															date1 = convert(varchar(10),ST.date1, 104),
															date2 = convert(varchar(10),ST.date2, 104),
															T_DOG= s.forma,
															[TU_CODE] = st.f_ter_usl ,
															st.ter_koef,
															[OS_CODE] = st.f_osob_usl,
															[EX_CODE] = st.is_osnov,
															osob_spis = RTRIM(LTRIM(COALESCE(st.osob_k1,''))) + RTRIM(LTRIM(COALESCE(st.osob_k2,''))) + RTRIM(LTRIM(COALESCE(st.osob_k3,''))),
															is_dop_m = st.is_dop_m,
															is_dop_d = st.is_dop_d,
															is_dop = st.is_dop,
															[f_is_dop] = st.f_is_dop,
															[P_CODE] = st.ud_osnov,
															ud_dop_m = st.ud_dop_m,
															ud_dop_d = st.ud_dop_d,
															ud_dop_k = st.ud_dop_k,
															[f_ud_dop]
													FROM dbo.SA_SZV4_SVEDENIA s
													LEFT JOIN  dbo.SA_SZV4_STAZH st ON S.link1 = ST.link
													WHERE s.link = @LINK_DOC_OP AND  s.FM = @FM_R and s.IM = @IM_R  and s.OT = @OT_R
														AND  s.PF_NUM= @SNILS_R
														AND ((s.forma = 2  and NOT EXISTS (	select * FROM dbo.SA_SZV4_SVEDENIA s
																							LEFT JOIN  dbo.SA_SZV4_STAZH st ON S.link1 = ST.link
																							WHERE s.link = @LINK_DOC_OP AND  s.FM = @FM_R and s.IM = @IM_R  and s.OT = @OT_R
																								AND  s.PF_NUM= @SNILS_R  AND   s.forma = 1)
																				AND EXISTS (select * FROM dbo.SA_SZV4_SVEDENIA s
																							LEFT JOIN  dbo.SA_SZV4_STAZH st ON S.link1 = ST.link
																							WHERE s.link = @LINK_DOC_OP AND  s.FM = @FM_R and s.IM = @IM_R  and s.OT = @OT_R
																								AND  s.PF_NUM= @SNILS_R  AND   s.forma = 2))
															  or s.forma = 1  )
														
														
													ORDER BY  ST.date1, st.orders
														
													/*первая строка*/
													INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
													Select @lcFNAME,
													CASE WHEN @TYPE_R <> 'ОТМЕНЯЮЩАЯ' THEN	
													/*CASE WHEN  @TYPE <> 'ИСХОДНАЯ' AND  @YEAR_EDT < '2013' 	THEN	''
													ELSE*/	
														(CASE WHEN DATE1 <> '' THEN
														+	SPACE(3) + '<СтажевыйПериод>' + CHAR(10)
														+		SPACE(4) + '<НомерСтроки>' + ltrim(rtrim(CONVERT(VARCHAR(2),link))) + '</НомерСтроки>' + CHAR(10)
														+		SPACE(4) + '<ДатаНачалаПериода>' + CONVERT(VARCHAR(10),DATE1,104) + '</ДатаНачалаПериода>' + CHAR(10)
														+		SPACE(4) + '<ДатаКонцаПериода>' + CONVERT(VARCHAR(10),DATE2,104) + '</ДатаКонцаПериода>' + CHAR(10)
														+				CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE([OS_CODE],''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE,''))) <> '' THEN
														+		SPACE(4) + '<КоличествоЛьготныхСоставляющих>' + CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE(OS_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE(EX_CODE,''))) <> '' OR RTRIM(LTRIM(COALESCE(f_is_dop,''))) <> '' OR RTRIM(LTRIM(COALESCE(P_CODE,''))) <> '' THEN '1' ELSE '0' END + '</КоличествоЛьготныхСоставляющих>' + CHAR(10)		
														+		SPACE(4) + '<ЛьготныйСтаж>' + CHAR(10)
														+			SPACE(5) + '<НомерСтроки>1</НомерСтроки>' + CHAR(10)		
														+ 			SPACE(5) + '<ОсобенностиУчета>' + CHAR(10)
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE,''))) <> '' THEN
																			SPACE(7) + '<ТерриториальныеУсловия>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеТУ>' + RTRIM(LTRIM(COALESCE(TU_CODE,''))) + '</ОснованиеТУ>' + CHAR(10)
														+						CASE WHEN RTRIM(LTRIM(COALESCE(TU_CODE,''))) not in ('Ч31','Ч33','Ч34','Ч35','Ч36') then
																				(CASE WHEN RTRIM(LTRIM(COALESCE(STR(ter_koef,4,2),''))) <> '0.00' then SPACE(8) + '<Коэффициент>' + RTRIM(LTRIM(COALESCE(STR(ter_koef,4,2),''))) + '</Коэффициент>' + CHAR(10) else '' end)
																				else '' end
														+ 					SPACE(7) + '</ТерриториальныеУсловия>' + CHAR(10)
																			ELSE '' END
														+ 					
																			CASE WHEN RTRIM(LTRIM(COALESCE(OS_CODE,''))) <> '' AND CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE,'')))) > 0 THEN
														+					SPACE(7) + '<ОсобыеУсловияТруда>' + CHAR(10)
														+							SPACE(8) + '<ОснованиеОУТ>' + LEFT(RTRIM(LTRIM(COALESCE(OS_CODE,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE,'')))) -1 )  + '</ОснованиеОУТ>' + CHAR(10)
														+							CASE WHEN LEFT(RTRIM(LTRIM(COALESCE(OS_CODE,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE,'')))) -1 ) = '27-1' or LEFT(RTRIM(LTRIM(COALESCE(OS_CODE,''))), CHARINDEX ( ',' ,RTRIM(LTRIM(COALESCE(OS_CODE,'')))) -1 ) = '27-2' THEN
																						SPACE(8) + '<ПозицияСписка>' + UPPER(RTRIM(LTRIM(COALESCE(osob_spis,'')))) + '</ПозицияСписка>' + CHAR(10)
																					ELSE '' END
														+ 					SPACE(7) + '</ОсобыеУсловияТруда>' + CHAR(10)
																			ELSE '' END
																								
														+ 					CASE WHEN RTRIM(LTRIM(COALESCE(EX_CODE,''))) <> '' THEN
																			SPACE(7) + '<ИсчисляемыйСтаж>' + CHAR(10)
														+						SPACE(8) + '<ОснованиеИС>' + RTRIM(LTRIM(COALESCE(EX_CODE,''))) + '</ОснованиеИС>' + CHAR(10)
														+						CASE WHEN COALESCE(f_is_dop,'') LIKE '%Ч.%' OR COALESCE(f_is_dop,'') LIKE '%МИН.%' THEN
																				SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
														+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE(is_dop_m,0),3))) + '</Часы>' + CHAR(10)
														+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE(is_dop_d,0),3))) + '</Минуты>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																				ELSE '' END
														+						CASE WHEN COALESCE(f_is_dop,'') LIKE '%МЕС.%' OR COALESCE(f_is_dop,'') LIKE '%ДН.%' THEN
																				SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
														+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
														+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE(is_dop_m,0),3))) + '</ВсеМесяцы>' + CHAR(10)
														+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE(is_dop_d,0),3))) + '</ВсеДни>' + CHAR(10)
														+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																				ELSE '' END
														+ 					SPACE(7) + '</ИсчисляемыйСтаж>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE(is_dop,''))) <> '' THEN					
														+					SPACE(7) + '<ДекретДети>' + RTRIM(LTRIM(COALESCE(is_dop,''))) + '</ДекретДети>' + CHAR(10)
																			ELSE '' END
														+					CASE WHEN RTRIM(LTRIM(COALESCE(is_dop,''))) <> '' and RTRIM(LTRIM(COALESCE(is_dop,''))) <> 'НЕОПЛ'  THEN
															+ 					(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_m,0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_d,0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_m,0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_d,0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(ud_dop_k,0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_k,0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																				WHEN RTRIM(LTRIM(COALESCE(is_dop,''))) = '' THEN
																				(CASE WHEN RTRIM(LTRIM(COALESCE(P_CODE,''))) <> '' THEN
																				SPACE(7) + '<ВыслугаЛет>' + CHAR(10)
															+						SPACE(8) + '<ОснованиеВЛ>' + RTRIM(LTRIM(COALESCE(P_CODE,''))) + '</ОснованиеВЛ>' + CHAR(10)
															+						CASE WHEN COALESCE(f_ud_dop,'') LIKE '%Ч.%' OR COALESCE(f_ud_dop,'') LIKE '%МИН.%' THEN
																					SPACE(8) + '<ВыработкаВчасах>' + CHAR(10)
															+							SPACE(9) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_m,0),3))) + '</Часы>' + CHAR(10)
															+							SPACE(9) + '<Минуты>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_d,0),3))) + '</Минуты>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаВчасах>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(f_ud_dop,'') LIKE '%МЕС.%' OR COALESCE(f_ud_dop,'') LIKE '%ДН.%' THEN
																					SPACE(8) + '<ВыработкаКалендарная>' + CHAR(10)
															+							SPACE(9) + '<ВсеГоды>0</ВсеГоды>' + CHAR(10)
															+							SPACE(9) + '<ВсеМесяцы>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_m,0),3))) + '</ВсеМесяцы>' + CHAR(10)
															+							SPACE(9) + '<ВсеДни>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_d,0),3))) + '</ВсеДни>' + CHAR(10)
															+ 						SPACE(8) + '</ВыработкаКалендарная>' + CHAR(10)
																					ELSE '' END
															+						CASE WHEN COALESCE(ud_dop_k,0) <> 0 THEN
																						SPACE(8) + '<ДоляСтавки>' + RTRIM(LTRIM(STR(COALESCE(ud_dop_k,0),4,2))) + '</ДоляСтавки>' + CHAR(10)
																					ELSE '' END
															+ 					SPACE(7) + '</ВыслугаЛет>' + CHAR(10)
																				ELSE '' END)
																			ELSE '' END
														+			SPACE(5) + '</ОсобенностиУчета>' + CHAR(10)
														+		SPACE(4) + '</ЛьготныйСтаж>' + CHAR(10)
																	ELSE '' END
														+	SPACE(3) + '</СтажевыйПериод>'
														ELSE '' END)
													/*END*/
													ELSE '' END
													FROM #STAZH_TMP
													WHERE SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R and OT = @OT_R  AND
																( (T_DOG = 2 AND  NOT EXISTS (SELECT *  FROM #STAZH_TMP WHERE SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R and OT = @OT_R  AND T_DOG = 1)
																			AND  EXISTS (SELECT *  FROM #STAZH_TMP WHERE SNILS= @SNILS_R AND FM = @FM_R and IM = @IM_R and OT = @OT_R  AND T_DOG = 2))
																	OR  T_DOG = 1 	)	
													order by link , date1
																						

												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, @UVOL/*, @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.[RT_SELECTION_GET_KBK]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RT_SELECTION_GET_KBK]

GO

CREATE PROCEDURE [dbo].[RT_SELECTION_GET_KBK]
	@varKSnYEAR	int,
	@varKSnPERIODIC	int,
	@varKSnPeriod_Numeric int,
	@varKSnStatus int
AS

----ограничение диапазона сохранненых форм----
CREATE TABLE #sf (link_sf int,link_form int,period_type tinyint,period_number tinyint,begin_date datetime,link_organization int,btype varchar (250),link_type_svod int)

INSERT INTO #sf
SELECT DISTINCT rsf.link_saved_form AS link_sf,
	rsf.link_form, 
	rsf.period_type, 
	rsf.period_number,
	RSF.begin_date,
	rsf.link_organization,
	[btype] = (SELECT [name] FROM BI_DICTION_BUDG_TYPE WHERE link = rsf.link_type_svod),
    rsf.link_type_svod
    FROM   report_saved_forms RSF (nolock) 
    WHERE  RSF.link_form in --(select link_form from @kbk_tab)
		(SELECT rt2.link_form FROM BufferGetTableByID('ANGELS_WE_HAVE_HEARD_ON_HIGH') rl2 
         inner join report_coloumns rc2 (nolock) on rc2.link_col = rl2.link 
         inner join report_tables rt2 (nolock) on rt2.link_table = rc2.link_table)
	and year(RSF.begin_date)=@varKSnYEAR
	and RSF.period_type = @varKSnPERIODIC
	and RSF.period_number = @varKSnPeriod_Numeric
 	and RSF.version = (select  top 1 version
   		 from report_saved_forms as lrsf (nolock) 
   		 where lrsf.link_form = RSF.link_form
 		 and year(lrsf.begin_date) = @varKSnYEAR
 		 and lrsf.period_type = @varKSnPERIODIC
 		 and lrsf.period_number = @varKSnPeriod_Numeric
 		 and lrsf.link_organization = RSF.link_organization
 		 and isnull(lrsf.link_type_svod,-255) = isnull(RSF.link_type_svod,-255)
   		 order by  version desc)
	and rsf.IsSvod in (case when @varKSnStatus&0x10 = 0x10 then 1 else -1 end,
	     case when @varKSnStatus&0x20 = 0x20 then 0 else -1 end) --@varKSnSvod
	and rsf.IsRO in (case when @varKSnStatus&0x1 = 0x1 then 0 else -1 end,
		 case when @varKSnStatus&0x2 = 0x2 then 1 else -1 end,
		 case when @varKSnStatus&0x4 = 0x4 then 2 else -1 end,
		 case when @varKSnStatus&0x8 = 0x8 then 3 else -1 end)

--- далее создаётся таблица @kbk_tab в которой среди прочего будут link_col на столбцы с КБК
declare @kbk_tab table(code char(7),link_form int,name varchar(70),link_table int,link_col int,link_code_col int,Orders tinyint)
insert into @kbk_tab
select distinct rf.code, rf.link_form, rc.[name],rc.link_table, rc.link_col, rt.link_code_col, rt.Orders
from report_forms rf (nolock) inner join
	 report_tables rt (nolock) on rf.link_form = rt.link_form inner join 
	 report_coloumns rc (nolock) on rt.link_table = rc.link_table 
where exists(select * 
		from 
			BufferGetTableByID('ANGELS_WE_HAVE_HEARD_ON_HIGH') rl2 inner join
			report_coloumns rc2 (nolock) on rc2.link_col = rl2.link inner join
			report_tables rt2 (nolock) on rt2.link_table = rc2.link_table 
		where rt2.link_table = rt.link_table)
and (rc.name like '%БК%' or rc.name like '%КД%' or rc.name like '%ФКР%' or (rf.code = '0503074' and rc.name = 'Код строки') or
rc.name like '%КИВ%' or
rc.name = 'Код расхода')

declare @kbk_join table(link_sf int,code_form char(7),link_form int,link_table int,Orders tinyint,kbk_code char(30), kbk_name char(254))

insert into @kbk_join
select distinct sf.link_sf,kbk_tab.code,kbk_tab.link_form,kbk_tab.link_table,kbk_tab.Orders,(case when rep_str.str_val is NULL then rep_frm.formula else rep_str.str_val end) as kbk_code, '' from 
    #sf as sf 
        inner join 
    dbo.report_summa as rep_sum 
        on sf.link_sf = rep_sum.link_saved_form and rep_sum.summa <> 0.0
        left join
    dbo.report_string as rep_str
        on sf.link_sf = rep_str.link_saved_form and rep_sum.link_row = rep_str.link_row
        left join
    dbo.report_formula as rep_frm
        on rep_sum.link_row = rep_frm.link_row and rep_str.link_col is NULL and rep_frm.formula is not NULL
        inner join
    @kbk_tab as kbk_tab
        on (rep_str.link_col = kbk_tab.link_col) or (rep_frm.link_col = kbk_tab.link_col)
union
select distinct sf.link_sf,kbk_tab.code,kbk_tab.link_form,kbk_tab.link_table,kbk_tab.Orders,(case when kbk_tab.link_col<>rep_din.link_col then rep_din.Code_Row else rep_din.Str_Val end) as kbk_code, '' from 
    #sf as sf 
        inner join 
    dbo.report_dinamics as rep_din 
        on sf.link_sf = rep_din.link_sf
        inner join
    @kbk_tab as kbk_tab
        on kbk_tab.link_col = rep_din.link_col or ((kbk_tab.link_col = kbk_tab.link_code_col) and (kbk_tab.link_col = (select link_code_col from dbo.report_tables where link_table = (select link_table from dbo.report_coloumns where link_col = rep_din.link_col))))
    where rep_din.code_row in (
        select rep_din.code_row from 
            #sf as sf 
                inner join 
            dbo.report_dinamics as rep_din 
                on sf.link_sf = rep_din.link_sf
            group by rep_din.code_row
            having sum(abs(rep_din.Float_Val))<>0.0 
    )
-- теперь надо выянить какие таблицы "ползают по деревьям"        
declare @code_form char(7),
        @orders tinyint,
        @link_sf int,
        @link_form int,
        @link_table int,
        @code char(20),
        @code_tree char(20),
        @Link_Self int,
        @kbk char(30),
        @name char(254),
        @cTabCode varchar(14)
        

declare theCursor cursor dynamic for
select link_sf,code_form,link_form,link_table,Orders,kbk_code from @kbk_join

open theCursor
fetch next from theCursor into @link_sf,@code_form,@link_form,@link_table,@orders,@code
while @@fetch_status = 0 begin
    -- теперь надо проверить, ползает - ли пациент по дереву report_kbk?
    set @cTabCode = dbo.RT_IF_IT_PATIENT_OF_REPORT_KBK(@code_form,@orders) -- кодовое имя таблицы таблицы, если она прописана в дереве
    if @cTabCode <> '' begin
        set @code_tree = rtrim(@code)
        select @Link_Self = Link_Self from dbo.report_kbk where right(rtrim(code),17) = right(@code_tree,17) and Code_Form = @cTabCode
        while @Link_Self <> 0 begin
            insert into @kbk_join --(link_sf,code_form,link_form,link_table,Orders,kbk_code, kbk_link)
            select @link_sf, @code_form, @link_form, @link_table, @orders, code, [name] from dbo.report_kbk
            where link = @link_self
            select @link_self = link_self from dbo.report_kbk
            where link = @link_self
        end
        update @kbk_join set kbk_name = (select [name] from dbo.report_kbk where right(rtrim(code),17) = right(rtrim(@code),17) and Code_Form = @cTabCode) where current of theCursor
    end
    else begin 
        if @code_form = '0503074' begin -- ну может это 14 форма?
            set @code_tree = left(rtrim(@code),5)
            select @Link_Self = isnull(Link_Self,0) from dbo.REPORT_FORM14_RAZD where shifr = @code_tree
            while @Link_Self <> 0 begin
                set @kbk = NULL
                set @name = NULL
        		select @kbk = ltrim(
                    (case when len(rtrim(razd_code))=0 then '0000' else rtrim(razd_code) end)+
                    (case when len(rtrim(cel_st_code))=0 then '0000000' else rtrim(cel_st_code) end)+
                    (case when len(rtrim(vr_code))=0 then '000' else rtrim(vr_code) end)),
                    @name = [name], @Link_Self = isnull(link_self,0) from dbo.REPORT_FORM14_RAZD_NAME where link = @Link_Self
                if @kbk is not NULL begin  -- Чиж & C\О любви\Я позвонил Вам из телефона-автомата.mp3
                    insert into @kbk_join (link_sf,code_form,link_form,link_table,Orders,kbk_code,kbk_name)
                    values (@link_sf, @code_form, @link_form, @link_table, @orders, @kbk, @name)
                end
            end
            set @kbk = NULL
            set @name = NULL
    		select @kbk = ltrim(
                (case when len(rtrim(razd_code))=0 then '0000' else rtrim(razd_code) end)+
                (case when len(rtrim(cel_st_code))=0 then '0000000' else rtrim(cel_st_code) end)+
                (case when len(rtrim(vr_code))=0 then '000' else rtrim(vr_code) end)),
                @name = [name] from dbo.REPORT_FORM14_RAZD_NAME where shifr = @code_tree
            if @kbk is not NULL begin  -- Чиж & C\О любви\Я позвонил Вам из телефона-автомата.mp3
                update @kbk_join set kbk_code = @kbk ,kbk_name = @name  where current of theCursor
            end
        end
        else begin
            -- иначе просто ищем имя соответствующее коду КБК в таблице dbo.report_kl_kbk_sgu
            update @kbk_join set kbk_code = REPLICATE('0',20 - len(rtrim(ltrim(kbk_code))))+rtrim(ltrim(kbk_code)),kbk_name = (select top 1 [Name] from dbo.report_kl_kbk_sgu where right(rtrim(Code),17) = right(rtrim(@code),17)) where current of theCursor
        end
    end
    fetch next from theCursor into @link_sf,@code_form,@link_form,@link_table,@orders,@code
end

-- теперь банально выбираем нужные нам поля (вернее нужные ВАМ поля, потому что мне эти поля до фени. Я получаю зарплату не за содержимое, а за правильность алгоримов)

select distinct code_form as form, kbk_code as link, kbk_name as tab from @kbk_join -- псевдонимы туповаты, но сделано в соответствии с динамическим фильтром по боковику


GO


GRANT EXECUTE ON dbo.[RT_SELECTION_GET_KBK] TO PUBLIC

GO



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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE dbo.BK_REPORT_OSV_KAU1
	@varKSdDate1	DATETIME	,
	@varKSdDate2	DATETIME	,
	@nPrintKBK	INT	/* Код счета с КБК */,
	@nPrintSGU	INT	/* Код счета с КОСГУ */,
	@nPrintDEP	INT	/* Отчет в разрезе организаций */,
	@varKScVal1 char(1), @varKSnOtborLink1 int	,
	@cVal2 char(1), @nOtborLink2 int	/* Отбор КАУ */,
	@cVal_KBK char(1), @nOtborLinkKBK int	/* Отбор КБК */,
	@intSVOD_ZB INT,
	@cVal_DOP_CL char(1), @nOtborLinkDOP_CL int,	-- Отбор Доп. кл-ции --
	@intPRN_DOP_CL int = 0	-- Отчет в разрезе доп. кл-ции
AS
BEGIN
	DECLARE	@varKSDEP_LINK	INT,
		@varKSORGNAME	VARCHAR(254)

	/* --- ОТБОР СУБСЧЕТОВ С КАУ --- */
	DECLARE @ACCT  TABLE (LINK_ACCT [INT])	
	IF LEN (@varKScVal1) > 0
		INSERT INTO @ACCT
		SELECT RECORD
		FROM OBJECT_VAR_ACCT
		WHERE LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO @ACCT
		SELECT LINK
		FROM dbo.S_ACCOUNTS 
		WHERE AP_KAU = 1
			AND LINK IN (SELECT LINK FROM dbo.AccountsTableWithNoChild())
	
	--- ОТБОР КАУ --- 
	DECLARE @KAU TABLE (LINK_KAU [INT], KAU_CODE  [VARCHAR] (20), KAU_NAME [VARCHAR] (254))
	IF LEN(@cVal2)>0 BEGIN
		INSERT INTO @KAU
			SELECT OVR.RECORD, D.CODE, D.[NAME]
			FROM dbo.OBJECT_VAR_KAU OVR, dbo.DICTIONARY_ANALYTICAL_CODES D
			WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@nOtborLink2
	END
	ELSE
	BEGIN
		INSERT INTO @KAU
			SELECT D.LINK, D.CODE, D.[NAME] FROM DICTIONARY_ANALYTICAL_CODES D
		INSERT INTO @KAU VALUES (0, '', 'Не указан')
	END

	--- ОТБОР КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	--- ОТБОР ПО ДОП. КЛ-ЦИИ --- 
	DECLARE @TAB_DOP_CL TABLE (LINK_DOP INT, DOP_CODE VARCHAR (20))
	
	IF @intPRN_DOP_CL = 1
		IF LEN (@cVal_DOP_CL) > 0
			INSERT INTO @TAB_DOP_CL
			SELECT AP.LINK,
				AP.CODE
			FROM dbo.DOP_CLASSIF AP 
			INNER JOIN dbo.OBJECT_VAR_DOP_CLASSIF OVR ON (OVR.RECORD = AP.LINK)
			WHERE OVR.LINK_UP = @nOtborLinkDOP_CL
		ELSE
			INSERT INTO @TAB_DOP_CL
			SELECT LINK_AP, AP_CODE
			FROM dbo.BK_GetTableDictionByAP ('AP2')
	ELSE
		INSERT INTO @TAB_DOP_CL (LINK_DOP, DOP_CODE)
		VALUES (0, '')

--SELECT * FROM @TAB_DOP_CL

	-- Параметры организации -- 
	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)
	SET @varKSDEP_LINK = dbo.BK_GetDepZB ()

	IF @intSVOD_ZB = 1 OR @varKSDEP_LINK IS NULL
		SET @varKSDEP_LINK = dbo.GetOwnDepLink()

	SET @varKSORGNAME = dbo.BK_GET_PRINT_DEP_NAME (@varKSDEP_LINK)

	IF @intSVOD_ZB = 1
	BEGIN
		SET @varKSORGNAME = RTRIM (@varKSORGNAME) + ' (ЦБ)'
		SET @varKSDEP_LINK = NULL
	END

	SET @nPrintKBK = ISNULL (@nPrintKBK, 0)
	SET @nPrintSGU = ISNULL (@nPrintSGU, 0)

	/* --- ОСВ --- */
	DECLARE @TABLE1 TABLE (DEP [INT], ACCOUNT [INT], KAU [INT],
			KBK [INT], KOSGU [INT], DOP INT,
			D_SUMMA [NUMERIC] (20,2), K_SUMMA [NUMERIC] (20,2),
			IN_SUMMA [NUMERIC] (20,2), OUT_SUMMA [NUMERIC] (20,2))

	INSERT INTO @TABLE1
	SELECT
		CASE
			WHEN @nPrintDEP = 1 THEN T1.DEP
			ELSE 0
		END,
		T1.ACCOUNT,
		T1.KAU,
		CASE 
			WHEN @nPrintKBK = 1 THEN ISNULL (T1.KBK, 0)
			ELSE 0
		END,
		CASE 
			WHEN @nPrintSGU = 1 THEN ISNULL (T1.SGU, 0)
			ELSE 0
		END,
		CASE
			WHEN @intPRN_DOP_CL = 1 THEN ISNULL (T1.AP2, 0)
			ELSE 0
		END,
		SUM (T1.D_SUMMA),
		SUM (T1.K_SUMMA),
		SUM (T1.IN_SUMMA),
		SUM (T1.OUT_SUMMA)
	FROM dbo.BK_GetTableOSVByDate (@varKSdDate1, @varKSdDate2, @varKSDEP_LINK) T1
	INNER JOIN @ACCT AC ON (AC.LINK_ACCT = T1.ACCOUNT)
	INNER JOIN @TAB_KBK T2 ON (T2.LINK_KBK = T1.KBK)
	GROUP BY
		CASE
			WHEN @nPrintDEP = 1 THEN T1.DEP
			ELSE 0
		END,
		T1.ACCOUNT,
		T1.KAU,
		CASE 
			WHEN @nPrintKBK = 1 THEN ISNULL (T1.KBK, 0)
			ELSE 0
		END,
		CASE 
			WHEN @nPrintSGU = 1 THEN ISNULL (T1.SGU, 0)
			ELSE 0
		END,
		CASE
			WHEN @intPRN_DOP_CL = 1 THEN ISNULL (T1.AP2, 0)
			ELSE 0
		END

	DECLARE @RESULT TABLE  (DEP [INT], ACCOUNT [INT], KAU [INT],
			KBK [INT], KOSGU [INT], DOP INT, DOP_CODE VARCHAR (20),
			DEP_CODE [VARCHAR] (20), DEP_NAME [VARCHAR] (254),
			KAU_CODE [VARCHAR] (20), KAU_NAME [VARCHAR] (254),
			ACCT_GR [VARCHAR] (30), ACCT_CODE [VARCHAR] (60),
			IN_SUM_D [NUMERIC] (20,2), IN_SUM_K [NUMERIC] (20,2),
			D_SUM [NUMERIC] (20,2),	K_SUM [NUMERIC] (20,2),
			OUT_SUM_D [NUMERIC] (20,2), OUT_SUM_K [NUMERIC] (20,2),
			ORGNAME [VARCHAR] (254))

	INSERT INTO @RESULT
	SELECT OSV.DEP,
		OSV.ACCOUNT,
		OSV.KAU,
		OSV.KBK,
		OSV.KOSGU,
		OSV.DOP,
		DOP.DOP_CODE,
		ISNULL (DEP.CODE, ''),
		ISNULL (DEP.[NAME], 'Не указан'),
		KAU.KAU_CODE,
		KAU.KAU_NAME,
		SA.CODE,
		dbo.BK_GetAcctFullCode1 (OSV.ACCOUNT, OSV.KBK, OSV.KOSGU, @nPrintKBK, @nPrintSGU),
		CASE 
			WHEN SA.S_ACTIVE = 1 THEN OSV.IN_SUMMA
			ELSE 0	
		END,
		CASE 
			WHEN SA.S_PASSIVE = 1 THEN OSV.IN_SUMMA
			ELSE 0	
		END,
		OSV.D_SUMMA,
		OSV.K_SUMMA,
		CASE 
			WHEN SA.S_ACTIVE = 1 THEN OSV.OUT_SUMMA
			ELSE 0	
		END,
		CASE 
			WHEN SA.S_PASSIVE = 1 THEN OSV.OUT_SUMMA
			ELSE 0	
		END,
		@varKSORGNAME
	FROM @TABLE1 OSV
	INNER JOIN @KAU KAU ON (KAU.LINK_KAU = OSV.KAU)
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = OSV.ACCOUNT)
	INNER JOIN @TAB_DOP_CL DOP ON (DOP.LINK_DOP = OSV.DOP)
	LEFT OUTER JOIN dbo.DICTIONARY_DEPARTMENT DEP ON (DEP.LINK = OSV.DEP)
	WHERE (OSV.D_SUMMA <> 0)
		OR (OSV.K_SUMMA <> 0)
		OR (OSV.IN_SUMMA <> 0)
		OR (OSV.OUT_SUMMA <> 0)

	SELECT * FROM @RESULT ORDER BY DEP_CODE, KAU_CODE, ACCT_GR, ACCT_CODE, DOP_CODE
END



GO


GRANT EXECUTE ON dbo.[BK_REPORT_OSV_KAU1] TO PUBLIC

GO




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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE dbo.SD_N_RESERV_SAVE
	@varKSparLINK		int	OUTPUT,
	@varKSparNumber		varchar(15) = null,
	@varKSparDate		datetime = null,
	@varKSparPERIOD		datetime = null,
	@varKSparFlag		tinyint	= 0,
	@varKSparSumma	numeric(20,2) = 0.0,
	@LINK_DEP INT = NULL,
	@varKSparComm VARCHAR(50) = ''
	
AS
DECLARE @varKSERROR	tinyint, @varKSstrVALUE	varchar(7000), @varKStrancount	int, 	@varKSsoLink int, @varKSRowCount int

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

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

SELECT @varKSsoLink = LINK FROM s_objects  WHERE CODE = 'DOCUMENTS_ADD_RESERV'
EXECUTE @varKSERROR = SALARY_UPD_SDOC @varKSparLINK OUTPUT, @varKSsoLink, @varKSparNumber,@varKSparDate,@varKSparComm,0,@varKSparPERIOD,@varKSparSumma, @LINK_DEP
IF @varKSERROR <> 0
	RETURN @varKSERROR


IF not exists(select link_up from sdoc_reserv  where link_up =@varKSparLINK)
	BEGIN
		INSERT INTO sdoc_reserv WITH (ROWLOCK) (LINK_UP,DATE,PERIOD) 
			VALUES (@varKSparLINK,@varKSparDate,@varKSparPERIOD)
		SELECT @varKSERROR = @@ERROR
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
ELSE
	BEGIN
		UPDATE sdoc_reserv WITH (ROWLOCK) 
		SET 	DATE = @varKSparDate,
				PERIOD =@varKSparPERIOD 
		WHERE LINK_UP=@varKSparLINK
		SELECT @varKSERROR = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END


DELETE FROM SDOC_reserv_TABLE  WHERE LINK_UP = @varKSparLINK


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

RETURN 0




GO


GRANT EXECUTE ON dbo.[SD_N_RESERV_SAVE] TO PUBLIC

GO



GO

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

GO

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

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

	DECLARE	@TD_LINK INT

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


	IF @CODE = '2014' BEGIN

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

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

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


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

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


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

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

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

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


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

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

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

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

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

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

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

		-- УДАЛЕНИЕ ВСЕХ ПРАЗДНИКОВ 
/*Производственный график убран из установки фиксированных настроек , теперь ведется история*/
/*		---DELETE	FROM HOLIDAYS

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

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

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

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

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

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

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

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

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

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

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

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

	IF @CODE = '2015' BEGIN

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

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

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


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

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


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

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

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

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


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

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

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

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

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

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

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

/*Производственный график убран из установки фиксированных настроек , теперь ведется история*/
/*			-- УДАЛЕНИЕ ВСЕХ ПРАЗДНИКОВ 
		DELETE	FROM HOLIDAYS

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

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

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

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


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

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

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

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

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

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

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

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

	IF @CODE = '2016' BEGIN

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

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


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

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


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

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

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

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


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

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

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

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

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

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

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

/*Производственный график убран из установки фиксированных настроек , теперь ведется история*/
/*			-- УДАЛЕНИЕ ВСЕХ ПРАЗДНИКОВ 
		DELETE	FROM HOLIDAYS
	--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРАЗДНИЧНЫХ ДНЕЙ
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL)
			SELECT	'1 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 1, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'2 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 2, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'3 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 3, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'4 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 4, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'5 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 5, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'6 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 6, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'7 ЯНВАРЯ (РОЖДЕСТВО ХРИСТОВО)', 7, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'8 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 8, 1, @TD_LINK, 1
			UNION ALL
			SELECT	'23 ФЕВРАЛЯ (ДЕНЬ ЗАЩИТНИКА ОТЕЧЕСТВА)', 23, 2, @TD_LINK, 1
			UNION ALL
			SELECT	'8 МАРТА (МЕЖДУНАРОДНЫЙ ЖЕНСКИЙ ДЕНЬ)', 8, 3, @TD_LINK, 1
			UNION ALL
			SELECT	'1 МАЯ (ПРАЗДНИК ВЕСНЫ И ТРУДА)', 1, 5, @TD_LINK, 1
			UNION ALL
			SELECT	'9 МАЯ (ДЕНЬ ПОБЕДЫ)', 9, 5, @TD_LINK, 1
			UNION ALL
			SELECT	'12 ИЮНЯ (ДЕНЬ РОССИИ)', 12, 6, @TD_LINK, 1
			UNION ALL
			SELECT	'4 НОЯБРЯ (ДЕНЬ НАРОДНОГО ЕДИНСТВА)', 4, 11, @TD_LINK, 1

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

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

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

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

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

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

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

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

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

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

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

END

GO


GRANT EXECUTE ON dbo.[SA_SET_STATIC_NASTR] TO PUBLIC

GO

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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE      PROCEDURE dbo.SD_REPORT_FORMULA_AVANSE_ASSETS_PREPARE
	@varKSOUT_VAL NUMERIC(20) OUTPUT,
	@varKSstart_date DATETIME, 	
	@varKSEND_DATE DATETIME, 
	@varKSDepLink INT
AS BEGIN

	DECLARE @varKSSTART_YEAR DATETIME, @varKSDATE1 DATETIME, @varKOEFF NUMERIC(20,2)
	SET @varKSSTART_YEAR  = dbo.DateBeginOfYear(@varKSstart_date)
	SET @varKSDATE1 = @varKSSTART_YEAR

	EXEC dbo.BufferCLEAR

	DECLARE @varKSPART2 VARCHAR(100),
		@varKSPART21 VARCHAR(100),
		@varKSPART23 VARCHAR(100),
		
		@intCODE	INT,	
		@strCODE	VARCHAR (3)

	EXEC X_GET_TABLE_NAME @varKSPART2 OUTPUT

	SELECT @varKOEFF = [PERCENT] FROM AVANSE_ASSETS_OPTIONS
	IF @varKOEFF IS NULL OR @varKOEFF < 0
		SET @varKOEFF = 0

	CREATE TABLE #RES2 (CODE_STR VARCHAR(3),
				SM1 NUMERIC(20),
				SM2 NUMERIC(20),
				SM3 NUMERIC(20),
				SM4 NUMERIC(20))

	SELECT @intCODE  = 20,
		@varKSDATE1 = @varKSSTART_YEAR

	WHILE @intCODE <= 140
	BEGIN
		IF @intCODE = 140
			SET @varKSDATE1 = DATEADD (DAY, -1, @varKSDATE1)
	
		SET @strCODE = RIGHT ('000' + CONVERT (VARCHAR (3), @intCODE), 3)
		
		IF DATEADD (MONTH, 1, @varKSEND_DATE) >= @varKSDATE1
			INSERT INTO #RES2
			SELECT @strCODE,
				SUM(CASE WHEN NO_NALOG = 0 OR NO_NALOG = 1 THEN OST_SUM ELSE 0.00 END),
				SUM(CASE WHEN GRP_CODE LIKE '10[1, 3]_[1-3]' THEN OST_SUM ELSE 0 END),
				SUM(CASE WHEN NO_NALOG = 1 THEN OST_SUM ELSE 0.00 END),
				SUM(CASE WHEN NO_NALOG = 1 AND GRP_CODE LIKE '10[1, 3]_[1-3]' THEN OST_SUM ELSE 0.00 END)
			FROM dbo.CalcNalogBalanceOS(@varKSDATE1, @varKSDepLink)
		ELSE
			INSERT INTO #RES2
			SELECT @strCODE, 0, 0, 0, 0

		SELECT
			@intCODE = @intCODE + 10,
			@varKSDATE1 = DATEADD(MONTH, 1, @varKSDATE1)
	END

	-- На конец года стоимость недв. имущества --
	INSERT INTO #RES2
	SELECT '141',
		SM2,
		SM2,
		SM4,
		SM4
	FROM #RES2
	WHERE CODE_STR = '140'

	EXEC ('SELECT * INTO ' + @varKSPART2 + ' FROM #RES2 ORDER BY CODE_STR ')
	EXEC dbo.BufferPush -1, @varKSPART2

END

GO


GRANT EXECUTE ON dbo.[SD_REPORT_FORMULA_AVANSE_ASSETS_PREPARE] 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, @DATE_CALC	DATETIME, @DEP_LINK INT, @S_LAST NUMERIC (20)

	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
		SELECT
			@DATE_CALC	= CASE
								WHEN @q < 4 THEN @vardEnd
								ELSE DATEADD (DAY, 1, @vardEnd)
							END,	
			@DEP_LINK = LINK_ORGANIZATION
		FROM dbo.REPORT_SAVED_FORMS
		WHERE LINK_SAVED_FORM = @variLSF

		SELECT
			@S_LAST = SUM (OST_SUM)
		FROM dbo.CalcNalogBalanceOS (@DATE_CALC, @DEP_LINK)
		WHERE NO_NALOG BETWEEN 0 AND 2
		
		SET @cres = CONVERT (VARCHAR (20), @S_LAST)
	END	
	ELSE
	BEGIN	
		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)
	END


-- SELECT @cStr, @res, @lnDiv, @cres
	
GO


GRANT EXECUTE ON dbo.[RSD_REPORT_FORMULA_AVPAT3_P22_VALUE14] TO PUBLIC

GO


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


GO

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

GO
CREATE PROCEDURE [dbo].[SS_NDFL_REPORT]
	
	@YEAR  varchar (4) , /* Год */
	@MONTH INT	 /* месяц */

AS 
BEGIN

	DECLARE @DATE1 DATETIME,	/* Начало периода */
			@DATE2 DATETIME	/* Конец периода */

	-- Выборка линка организации 
	DECLARE @LINK_DEP INT
	EXEC DBO.XD_WHATS_ZB @LINK_DEP OUTPUT

	-- Дата начала периода
	set @DATE1 = dbo.ConvertDMY2Date(1,1,@YEAR)
	-- Дата окончания , по указанному месяцу 
	SET @DATE2 = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@MONTH,@YEAR))

	--Список физ лиц, по которым были начислены взносы
	CREATE TABLE #NACHISL0 (LINK INT, SUMMA NUMERIC(18,2))
	
	INSERT INTO #NACHISL0 (LINK, SUMMA)
	SELECT E.pers_link, SUMMA
	FROM 
		dbo.PAYS P
		INNER JOIN dbo.CALCULATE_JURNAL J ON J.LINK_PAYS = P.LINK
		INNER JOIN dbo.EMPL E ON J.LINK_EMPL = E.LINK
	WHERE
		P.[OBJECT] = 2 AND P.WAY_CALC in (4,5,6)
		AND
		J.LINK_DEP = @LINK_DEP
		AND 
		J.PERIOD_BEGIN BETWEEN @DATE1 AND @DATE2
		And
		LINK_EMPL IS NOT NULL	

	INSERT INTO #NACHISL0 (LINK, SUMMA)
	SELECT pers_link, SUMMA
	FROM 
		dbo.PAYS P
		INNER JOIN dbo.CALCULATE_JURNAL J ON J.LINK_PAYS = P.LINK
	WHERE
		P.[OBJECT] = 2 AND P.WAY_CALC in (4,5,6)
		AND
		J.LINK_DEP = @LINK_DEP
		AND 		
		J.PERIOD_BEGIN BETWEEN @DATE1 AND @DATE2
		And
		LINK_EMPL IS NULL AND pers_link IS NOT NULL		


	CREATE TABLE #NACHISL (LINK INT, SUMMA NUMERIC(18,2))
	
	INSERT INTO #NACHISL (LINK, SUMMA)
	
	SELECT LINK, SUM(SUMMA)
	FROM #NACHISL0
	GROUP BY LINK 	


	--Сведения о перечисленных суммах
	CREATE TABLE #PERECHISL (LINK INT, SUMMA NUMERIC(18,2))	

	INSERT INTO #PERECHISL (LINK)
	SELECT LINK
	FROM #NACHISL
	GROUP BY LINK	

	DECLARE @SUMMA_PLAT_ALL NUMERIC(18,2)
	DECLARE @SUMMA_NACH_ALL NUMERIC(18,2)
	EXEC dbo.SA_NDFL_PLAT @DATE1, @DATE2, @LINK_DEP, @SUMMA_PLAT_ALL OUT
	EXEC dbo.SA_NDFL_NACHISL @DATE1, @DATE2, @LINK_DEP, @SUMMA_NACH_ALL OUT

	update  #PERECHISL 
		set SUMMA = case when (CONVERT(NUMERIC(18,2), ISNULL( @SUMMA_PLAT_ALL * CASE WHEN @SUMMA_NACH_ALL > 0 THEN ( n.summa / @SUMMA_NACH_ALL) ELSE 0 END, 0))) > isnull(n.summa,0)
					then isnull(n.summa,0)
					else CONVERT(NUMERIC(18,2), ISNULL( @SUMMA_PLAT_ALL * CASE WHEN @SUMMA_NACH_ALL > 0 THEN ( n.summa / @SUMMA_NACH_ALL) ELSE 0 END, 0)) end
	FROM #NACHISL n where  #PERECHISL.link = n.link
	--Список физ лиц, по которым есть сведения о начисленных, либо перечисленных суммах
	CREATE TABLE #PERS(LINK INT)
	
	INSERT INTO #PERS (LINK)
	SELECT DISTINCT LINK FROM #NACHISL
	UNION
	SELECT DISTINCT LINK FROM #PERECHISL


	EXEC dbo.BufferClear
	EXEC dbo.BufferPushTable '#PERS', 'REP2NDFL', 'link'
--<-------------------------------------------------------------------------
--<-------------------------------------------------------------------------
	---- список физлиц за год со сведениями об общей сумме дохода , о наоговой базе, о сумме налогов исчисленной\удержанной\перечисленной 	
	CREATE TABLE #RES0 (
		ID INT IDENTITY,
		NOM_SPR INT,
		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_KPP VARCHAR(9),		

		ksv1 varchar(3), ssv1 numeric(11,2),
		ksv2 varchar(3), ssv2 numeric(11,2),
		ksv3 varchar(3), ssv3 numeric(11,2),
		ksv4 varchar(3), ssv4 numeric(11,2),
		ksv5 varchar(3), ssv5 numeric(11,2),
		ksv6 varchar(3), ssv6 numeric(11,2),
		ksv7 varchar(3), ssv7 numeric(11,2),
		ksv8 varchar(3), ssv8 numeric(11,2),
		ksv9 varchar(3), ssv9 numeric(11,2),
		ksv10 varchar(3), ssv10 numeric(11,2),
		ksv11 varchar(3), ssv11 numeric(11,2),
		ksv12 varchar(3), ssv12 numeric(11,2),
		ssv numeric(11,2), siv numeric(11,2),
		osd13 numeric(11,2), sdo13 numeric(11,2), 
		nalogn13 numeric(18), nalogu13 numeric(18),
		NALOG13S numeric(18), PERSCENT numeric(5,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(30), kbkcode2 varchar(30), kbkcode3 varchar(30), kbkcode4 varchar(30), 
		kbksum1 numeric(18,2), kbksum2 numeric(18,2),kbksum3 numeric(18,2),kbksum4 numeric(18,2),
		VIFNSPL numeric(18,2),
		ZSummPL numeric(18,2),
		UdSumPL numeric(18,2),
		VzkIFNS numeric(18,2)

	)	
	
	Declare @isPrevPreiod tinyint
		--Суммы начислений включать в базу расчета в том месяце, в котором он был начислен.                   
	Set @isPrevPreiod = dbo.sa_get_option_by_code('NDFL_OPT6')

	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 
		E.PERS_LINK, JC.PERS_LINK, JC.LINK_EMPL, P.LINK, link_vkr, ISNULL(JC.LINK_EKR,P.LINK_EKR), P.TYP_PER, P.OBJECT, summa, P.LINK_INC,
		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
	from 
		dbo.CALCULATE_JURNAL JC 
		INNER JOIN dbo.NDFL_GroupTax() T ON JC.LINK_PAYS=T.LINK_PAYS
		LEFT JOIN dbo.EMPL E ON JC.LINK_EMPL = E.LINK
		LEFT 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 ISNULL(d.code,'') <> 'DOCUMENTS_ADD_TABEL') and @Month >= month(JC.PERIOD_BEGIN) and @Year = year(JC.PERIOD_BEGIN)
				or 
				@isPrevPreiod = 1 and ISNULL(d.code,'') = 'DOCUMENTS_ADD_TABEL'
				and (@Month >= month(JC.DATE_BEGIN) or @Month >= month(JC.PERIOD_BEGIN) )
				and (@Year = year(JC.DATE_BEGIN) or @Year = year(JC.PERIOD_BEGIN) )

			)
		/*AND  
			(	-->>NEW
			E.PERS_LINK in (select LINK from #PERS )
			or
			JC.PERS_LINK in (select LINK from #PERS )
			)
		*/		
		AND JC.LINK_DEP = @LINK_DEP 
	union all --Удержания
	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_TYP_INCOMS DTI ON DTI.LINK = SJC.LINK_INC 
	where 
		SJC.LINK_DEP = @LINK_DEP
		/*and
		(
			SJC.LINK_FACE in (select LINK from #PERS )
			or
			SJC.PERS_LINK in (select LINK from #PERS )
		)*/
		and YEAR(SJC.PERIOD_BEGIN) = @Year
		and Month(SJC.PERIOD_BEGIN) <= @Month
		and TYP_OPER = 2

		-----------------------------------------------------------
		--Для обособленных подразделений
		DECLARE @DATE DATETIME
		SET @DATE = DBO.ConvertDMY2Date(1,@Month, @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_KPP VARCHAR(9))
		INSERT INTO #S_OBOSOB (SUBDIV_LINK, O_OKATO, O_KPP)
		SELECT SUBDIV_LINK, O_OKATO, O_KPP 
		FROM [dbo].SUBDIVISION(@DATE) 
		WHERE OBOSOB = 1

		CREATE TABLE #P_OBOSOB (PERS_LINK INT, O_OKATO VARCHAR(14), O_KPP VARCHAR(9))
		INSERT INTO #P_OBOSOB(PERS_LINK, O_OKATO, O_KPP)
		SELECT E.PERS_LINK, SO.O_OKATO, 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_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_KPP
	FROM 
		/*#PERS F 
		INNER JOIN */PERSON P /*ON P.LINK = F.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.NDFL_GET_ADDRESS() ADR ON P.LINK = ADR.LINK_FACE
		LEFT JOIN #P_OBOSOB PO ON PO.PERS_LINK = P.LINK
	ORDER BY 
		RTRIM(P.FM) + ',' + RTRIM(P.IM) + ',' + RTRIM(P.OT)

		
	select distinct LINK_FACE, Y = year(PERIOD_BEGIN), M = month(PERIOD_BEGIN),  LINK_INC, LINK_VKR  
	into #spr_pays_kbk
	from 	#S_J_C_SHORT where TYP_OPER = 1
	

	CREATE TABLE #PAYS_0_tmp
	(
		ID INT IDENTITY,
		LINK_FACE INT,
		mes int, 
		LINK_INC INT, CODE_INC VARCHAR(4), SUMMA_INC NUMERIC(13,2),
		LINK_DED INT, CODE_DED VARCHAR(3), SUMMA_DED NUMERIC(13,2)
	)

	CREATE TABLE #PAYS_0
	(
		ID INT IDENTITY,
		LINK_FACE INT, 
		mes int, 
		LINK_INC INT, CODE_INC VARCHAR(4), SUMMA_INC NUMERIC(13,2),
		LINK_DED INT, CODE_DED VARCHAR(3), SUMMA_DED NUMERIC(13,2)
	)

	INSERT INTO #PAYS_0_tmp
	(LINK_FACE, mes, 
	LINK_INC, CODE_INC, SUMMA_INC,
	LINK_DED, CODE_DED, SUMMA_DED)
	SELECT 
		SJC.LINK_FACE,
		mes = MONTH(SJC.PERIOD_BEGIN),
		LINK_INC, ISNULL(DTI.SNAME,'0000'),
		SUM(SUMMA) AS SUMMA_INC,
		DTI.REF_DEDUCT AS LINK_DED, DTI.COD_DED,
		CAST(0 AS NUMERIC(20,2)) AS SUMMA_DED
	FROM 
		#S_J_C_SHORT SJC 
		LEFT JOIN dbo.DICTIONARY_TYP_INCOMS DTI ON DTI.LINK = SJC.LINK_INC AND SJC.LINK_FACE IS NOT null
		/*LEFT JOIN #PERS F ON SJC.LINK_FACE = F.LINK*/
	WHERE 
		SJC.TYP_OPER = 1
		AND
		YEAR(SJC.PERIOD_BEGIN) = @Year
		and
		Month(SJC.PERIOD_BEGIN) <= @Month
		AND
		ISNULL(SJC.PERS_LINK,0) = 0
		AND
		SJC.LINK_DEP = @LINK_DEP 
	GROUP BY 
		SJC.LINK_FACE, SJC.TYP_PER, SJC.PERIOD_BEGIN, LINK_INC, DTI.REF_DEDUCT, ISNULL(DTI.SNAME,'0000'), DTI.COD_DED

	---<< Добавление информации по внештатникам	
	union all 

	SELECT 
		F.LINK,
		mes = MONTH(SJC.PERIOD_BEGIN),
		LINK_INC, ISNULL(DTI.SNAME,'0000'),
		SUM(SUMMA) AS SUMMA_INC,
		DTI.REF_DEDUCT AS LINK_DED, DTI.COD_DED,
		CAST(0 AS NUMERIC(20,2)) AS SUMMA_DED
	FROM #S_J_C_SHORT SJC 	
		LEFT JOIN dbo.DICTIONARY_TYP_INCOMS DTI ON DTI.LINK = SJC.LINK_INC AND SJC.PERS_LINK IS NOT NULL --AND DTI.SNAME <> '0000'
		LEFT outer JOIN #PERS F ON SJC.PERS_LINK = F.LINK
	WHERE 	SJC.TYP_OPER = 1
		AND
		YEAR(SJC.PERIOD_BEGIN) = @Year
		and
		Month(SJC.PERIOD_BEGIN) <= @Month
		AND
		ISNULL(SJC.LINK_FACE,0) = 0
		AND
		SJC.LINK_DEP = @LINK_DEP
	GROUP BY 
		F.LINK, SJC.TYP_PER, SJC.PERIOD_BEGIN, LINK_INC, DTI.REF_DEDUCT, ISNULL(DTI.SNAME,'0000'), DTI.COD_DED
	ORDER BY 
		1, ISNULL(DTI.SNAME,'0000'), COD_DED

	INSERT INTO #PAYS_0
	Select LINK_FACE, mes, LINK_INC, CODE_INC, sum(SUMMA_INC), LINK_DED, CODE_DED, sum(SUMMA_DED)
	from #PAYS_0_tmp
	group by LINK_FACE, mes, LINK_INC, CODE_INC, LINK_DED, CODE_DED
	having Sum(SUMMA_INC) <> 0

	drop table #PAYS_0_tmp	
	---->>
	--СКИДКИ
	SELECT D.LINK_FACE, D.mes, SUM(D.SUMMA) as SUMMA, D.REF_DED INTO #DED 
	FROM 
		dbo.SA_NDFL_MONTH_DED_ALL(@Year) D 
		inner join #spr_pays_kbk kbk on kbk.LINK_FACE = d.LINK_FACE and kbk.m = d.mes and kbk.link_inc = d.REF_INC and kbk.LINK_VKR = d.LINK_VKR
	where 
		kbk.y = @Year
		and kbk.m <= @Month
	GROUP BY 
		D.LINK_FACE, d.mes, d.REF_DED


	UPDATE #PAYS_0
	SET SUMMA_DED = 
		(SELECT SUM(SUMMA) FROM #DED D WHERE D.LINK_FACE = R.LINK_FACE AND D.REF_DED = R.LINK_DED AND D.mes = R.mes ) 
	FROM #PAYS_0 R 
	WHERE LINK_DED IS NOT NULL


	update #PAYS_0 
		Set CODE_DED = ''
		where ISNULL(SUMMA_DED,0) = 0	

	CREATE TABLE #P0 (LINK_FACE INT, ID1 INT)


	--- 1

	CREATE TABLE #PAYS1(LINK_FACE INT, SM NUMERIC(11,2), MONTH_NUM INT)
	INSERT INTO #PAYS1
	--SELECT LINK_FACE, SM, [MONTH]
	--FROM dbo.NDFL_BASE_SUM_TAX_MONTH_ALL(@Month, @Year)
	

	SELECT 
		SJC.LINK_FACE,
		SUM(SUMMA) AS SUMMA_INC,
		Month(SJC.PERIOD_BEGIN)
	FROM 
		#S_J_C_SHORT SJC 
		INNER JOIN dbo.DICTIONARY_TYP_INCOMS DTI ON DTI.LINK = SJC.LINK_INC
		LEFT JOIN #PERS F ON SJC.LINK_FACE = F.LINK
	WHERE 
		YEAR(SJC.PERIOD_BEGIN) = @Year
		and Month(SJC.PERIOD_BEGIN) <= @Month
		AND ISNULL(SJC.PERS_LINK,0) = 0
		AND SJC.LINK_DEP = @LINK_DEP 
	GROUP BY SJC.LINK_FACE, SJC.PERIOD_BEGIN


	---<< Добавление информации по внештатникам
	insert into #pays1

	SELECT 
		F.LINK,
		SUM(SUMMA) AS SUMMA_INC,
		Month(SJC.PERIOD_BEGIN)
	FROM 
		#S_J_C_SHORT SJC 
		INNER JOIN dbo.DICTIONARY_TYP_INCOMS DTI ON DTI.LINK = SJC.LINK_INC
		INNER JOIN #PERS F ON SJC.PERS_LINK = F.LINK
	WHERE 
		YEAR(SJC.PERIOD_BEGIN) = @Year
		and Month(SJC.PERIOD_BEGIN) <= @Month
		AND ISNULL(SJC.LINK_FACE,0) = 0
		AND SJC.LINK_DEP = @LINK_DEP 
	GROUP BY F.LINK, SJC.PERIOD_BEGIN

	---->>

	SELECT LINK_FACE, SUM(SM) AS SM
	INTO #PAYS_R
	FROM #PAYS1
	GROUP BY LINK_FACE

	INSERT INTO #PAYS1
	SELECT 
		EP.PERS_LINK, -SUM(SUMMA), MONTH(DATE_DED)
	FROM    
		dbo.empl EP 
		inner join SAL_DED_MONTH S ON (EP.LINK = S.LINK_EMPL AND YEAR(DATE_DED) = @Year and Month(DATE_DED) <= @Month AND [TYPE] = 2)
		left JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = EP.pers_link --Было: EP.LINK
	where 
		EP.DEP_LINK = @LINK_DEP	
	GROUP BY 
		EP.PERS_LINK, MONTH(DATE_DED)

	CREATE TABLE #PAYS3(ID INT IDENTITY, LINK_FACE INT, LINK_DED INT, CODE_DED VARCHAR(6), SUMMA NUMERIC(18,2), SUMMA_FAKT NUMERIC(18,2))
	--Стандартные и скидки на мат помощь
	--ПО СОТРУДНИКАМ
	INSERT INTO #PAYS3 (LINK_FACE, LINK_DED, CODE_DED, SUMMA, SUMMA_FAKT)
	SELECT 	
		EP.PERS_LINK, min(S.REF_DED), T.CODE, 
		CONVERT(NUMERIC(18,2), SUM((case when KOEF_VKR is not null then DTD.SUMMA * KOEF_VKR else DTD.SUMMA end) * ISNULL(S.KOL,0) )), 
		SUM(S.SUMMA) 
	FROM 
		dbo.empl EP 
		INNER JOIN SAL_DED_MONTH S ON (EP.LINK = S.LINK_EMPL AND YEAR(DATE_DED) = @Year and Month(DATE_DED) <= @Month AND TYPE = 1)
		INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION T ON T.LINK = S.REF_DED 
		INNER JOIN dbo.Salary_deductions(@DATE1) DTD on DTD.REF_PAY = S.REF_DED
		LEFT JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = EP.pers_link --Было: EP.LINK
	where 
		T.NUMBER IN (	1, --Стандартные
						6 --скидки на мат помощь 
						)
		AND			
		EP.DEP_LINK = @LINK_DEP	and S.SUMMA <> 0
	GROUP BY 
		EP.PERS_LINK, T.CODE

	--ПО ДОГОВОРНИКАМ
	INSERT INTO #PAYS3 (LINK_FACE, LINK_DED, CODE_DED, SUMMA, SUMMA_FAKT)
	SELECT 	
		EP.PERS_LINK, min(S.REF_DED), T.CODE, 
		CONVERT(NUMERIC(18,2), SUM((case when KOEF_VKR is not null then DTD.SUMMA * KOEF_VKR else DTD.SUMMA end) * ISNULL(S.KOL,0) )), 
		SUM(S.SUMMA) 
	FROM 
		dbo.REESTR_DGH EP 
		INNER JOIN SAL_DED_MONTH S ON (EP.LINK = S.LINK_DGH AND YEAR(DATE_DED) = @Year and Month(DATE_DED) <= @Month AND S.[TYPE] = 1)
		INNER JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = EP.pers_link --Было: EP.LINK
		INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION T ON T.LINK = S.REF_DED 
		INNER JOIN dbo.Salary_deductions(@DATE1) DTD on DTD.REF_PAY = S.REF_DED
	where 
		T.NUMBER IN (	1, --Стандартные
						6 --скидки на мат помощь 
						)
		AND			
		EP.DEP_LINK = @LINK_DEP	and S.SUMMA <> 0
	GROUP BY 
		EP.PERS_LINK, T.CODE

	--UPDATE #PAYS3
	--SET
	--	SUMMA = (Select sum(SUM_DED) from dbo.TAX_DEDUCTIONS TD where TD.LINK_DEP = @DEP_LINK AND TD.link_person = #PAYS3.LINK_FACE and TD.LINK_DICTION = #PAYS3.LINK_DED and TD.[YEAR] = @varKSnYear and TD.Month1 <= @nMonth)	
	--where
	--	exists (Select * from dbo.TAX_DEDUCTIONS TD where TD.LINK_DEP = @DEP_LINK AND TD.link_person = #PAYS3.LINK_FACE and TD.LINK_DICTION = #PAYS3.LINK_DED and TD.[YEAR] = @varKSnYear and TD.Month1 <= @nMonth)	

	UPDATE #PAYS3
	SET
		SUMMA = ISNULL(SUMMA_FAKT,0)
	where
		ISNULL(SUMMA,0) = 0

	--Прочие вычеты (имущественные, добровольное пенс страхование и пр.)
	INSERT INTO #PAYS3 (LINK_FACE, LINK_DED, CODE_DED, SUMMA, SUMMA_FAKT)
	SELECT 	
		EP.PERS_LINK, min(S.REF_DED), T.CODE, SUM(S.SUMMA), SUM(S.SUMMA) 
	FROM 
		dbo.EMPL EP 
		INNER JOIN SAL_DED_MONTH S ON (EP.LINK = S.LINK_EMPL AND YEAR(DATE_DED) = @Year and Month(DATE_DED) <= @Month AND TYPE = 1)
		INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION T ON T.LINK = S.REF_DED 
		LEFT JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = EP.pers_link --Было: EP.LINK
	where 
		T.NUMBER NOT IN (	1, --Стандартные
							6 --скидки на мат помощь 
							)
		AND			
		EP.DEP_LINK = @LINK_DEP	and S.SUMMA <> 0
	GROUP BY 
		EP.PERS_LINK, T.CODE
		

	-- Общая сумма имущ. вычетов
	update #RES0
	Set siv = ISNULL( (Select sum(P3.SUMMA_FAKT) from #PAYS3 P3 where R.LINK_FACE = P3.LINK_FACE and P3.LINK_DED IN (SELECT DISTINCT LINK_DICTION FROM TAX_DEDUCTIONS td WHERE TD.LINK_DEP = @LINK_DEP AND TD.[YEAR] = @Year and TD.Month1 <= @Month)),0),
		ssv = ISNULL( (Select sum(P3.SUMMA_FAKT) from #PAYS3 P3 where R.LINK_FACE = P3.LINK_FACE and P3.LINK_DED NOT IN (SELECT DISTINCT LINK_DICTION FROM TAX_DEDUCTIONS td WHERE TD.LINK_DEP = @LINK_DEP AND TD.[YEAR] = @Year and TD.Month1 <= @Month)),0)		

	from #RES0 R
	--
	DELETE FROM #P0

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV1 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV1 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV2 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV2 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV3 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV3 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R

		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV4 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV4 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R

		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV5 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV5 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R

		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV6 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV6 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R

		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV7 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV7 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R

		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV8 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV8 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV9 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV9 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV10 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV10 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV11 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV11 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV12 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV12 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END


	UPDATE #RES0 SET OSD13 = (SELECT top 1 SM FROM #PAYS_R PR WHERE PR.LINK_FACE = R.LINK_FACE) FROM #RES0 R

	----
	UPDATE #RES0 SET SDO13 = OSD13 - ISNULL(SK.SUM_SK, 0.00)
			- ISNULL(SSV1,0.00) - ISNULL(SSV2,0.00) - ISNULL(SSV3,0.00) - ISNULL(SSV4,0.00)
			- ISNULL(SSV5,0.00) - ISNULL(SSV6,0.00) - ISNULL(SSV7,0.00) - ISNULL(SSV8,0.00)
			- ISNULL(SSV9,0.00) - ISNULL(SSV10,0.00) - ISNULL(SSV11,0.00) - ISNULL(SSV12,0.00)
	from #RES0 R INNER JOIN #PERS p ON r.link_face = p.LINK
				 LEFT JOIN (Select LINK_FACE, SUM_SK= SUM(SUMMA_DED) from #PAYS_0 GROUP BY LINK_FACE) SK ON R.LINK_FACE = SK.LINK_FACE

	-----
	UPDATE #RES0 SET SDO13 = 0 WHERE SDO13 < 0


	CREATE TABLE #NDFL_TAX(LINK_TAX INT)
	INSERT INTO #NDFL_TAX
	SELECT LINK FROM PAYS P WHERE P.OBJECT = 2 AND P.WAY_CALC = 4

	Create table #NDLF13_tmp (LINK int, SUMMA numeric(18,2))
	Create table #NDLF13 (LINK int, SUMMA numeric(18,2))

	insert into  #NDLF13_tmp (LINK, SUMMA)
	SELECT SJC.LINK_FACE AS LINK, SUM(SUMMA) AS SUMMA
	FROM 
		#S_J_C_Short SJC 
		INNER JOIN #NDFL_TAX T ON SJC.LINK_PAYS = T.LINK_TAX  
		LEFT JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = SJC.LINK_FACE --Было: EP.LINK
	WHERE 
		YEAR(PERIOD_BEGIN) = @Year 
		and month(PERIOD_BEGIN) <= @Month
		and sjc.LINK_DEP = @LINK_DEP	
	GROUP BY 
		SJC.LINK_FACE
	---<< Добавление информации по внештатникам
	union all
	SELECT B.LINK AS LINK, SUM(SUMMA) AS SUMMA
	FROM #S_J_C_Short SJC 
		INNER JOIN #NDFL_TAX T ON SJC.LINK_PAYS = T.LINK_TAX  
		INNER JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = SJC.PERS_LINK --Было: EP.LINK
	WHERE YEAR(PERIOD_BEGIN) = @Year 
		and month(PERIOD_BEGIN) <= @Month
		and ISNULL(SJC.LINK_FACE,0) = 0
		and sjc.LINK_DEP = @LINK_DEP
	GROUP BY B.LINK

	insert into #NDLF13 (LINK, SUMMA)
	Select LINK, Sum(SUMMA) from #NDLF13_tmp group by LINK
	
	drop table #NDLF13_tmp
	--->>

	UPDATE #RES0 SET NALOGU13 = ISNULL((SELECT SUM(SUMMA) FROM #NDLF13 N WHERE N.LINK = R.LINK_FACE), 0) FROM #RES0 R
	UPDATE #RES0 SET NALOGN13 = SDO13 * (CASE WHEN STATUS = '1' THEN 
		( SELECT  top 1 [PERCENT] / 100 FROM DICTIONARY_RANGE R inner join #NDFL_TAX T on R.LINK_PAYS = T.LINK_TAX WHERE TARIF = 1)
								ELSE 0.30 END)
	UPDATE #RES0 SET PERSCENT = (CASE WHEN STATUS = '1' THEN 
									( SELECT  top 1 [PERCENT] FROM DICTIONARY_RANGE R inner join #NDFL_TAX T on R.LINK_PAYS = T.LINK_TAX WHERE TARIF = 1)
								ELSE 30 END)							

	--Перечисленная сумма по всем за период
	DECLARE @nSumm_For_Check numeric(18,2)
	set @nSumm_For_Check = 1
	DECLARE @SUMMA_PLAT_ALL1 NUMERIC(18,2)
		
	EXEC dbo.SA_NDFL_PLAT @DATE1, @DATE2, @LINK_DEP, @SUMMA_PLAT_ALL1 OUT
 
	--Начисленная сумма по всем за период
	DECLARE @SUMMA_NACH_ALL1 NUMERIC(18,2)
	EXEC dbo.SA_NDFL_NACHISL @DATE1, @DATE2, @LINK_DEP, @SUMMA_NACH_ALL1 OUT
	
	
	--Перечисленная за сотрудника	
	UPDATE #RES0 SET NALOG13S = CONVERT(NUMERIC(18,0), ISNULL( @SUMMA_PLAT_ALL1 * CASE WHEN @SUMMA_NACH_ALL1 > 0 THEN (NALOGU13	/ @SUMMA_NACH_ALL1) ELSE 0 END, 0))
	UPDATE #RES0 SET NALOG13S = CASE WHEN NALOG13S > NALOGU13 THEN NALOGU13 ELSE NALOG13S END

	--UPDATE #RES0 SET NOM_SPR = ID + @varKSnFirstNum - 1
	
	---Учет переплаты/недоплаты НДФЛ из остатков с прошлого года
	UPDATE A SET 
		S_5_6 = (CASE WHEN R.NDFL > 0 THEN R.NDFL ELSE 0 END),
		S_5_7 = (CASE WHEN R.NDFL <= 0 THEN - R.NDFL ELSE 0 END)
	FROM
		#RES0 A INNER JOIN 
		(SELECT E.PERS_LINK, NDFL = SUM(SR.NDFL) FROM dbo.SAL_REMAIN SR INNER JOIN dbo.EMPL E ON E.LINK = SR.LINK_EMPL WHERE SR.YEAR_SAL = @Year GROUP BY E.PERS_LINK) R 
			ON R.PERS_LINK = A.LINK_FACE
	--	
	UPDATE #RES0 SET DOLG_NP = CASE WHEN NALOGN13 - NALOGU13 > 0 THEN NALOGN13 - NALOGU13 ELSE 0 END - ISNULL(S_5_6,0)
	UPDATE #RES0 SET DOLG_NA = CASE WHEN NALOGU13 - NALOGN13 > 0 THEN NALOGU13 - NALOGN13 ELSE 0 END - ISNULL(S_5_7,0)

	--^^^^^^^^^Распределение налога по КБК^^^^^^^^^^
	create table  #PAYS_NDFL (ID INT IDENTITY, LINK_FACE int, LINK_PAYS int, kbk_code varchar(30), SUMMA numeric(18,2))

	INSERT INTO #PAYS_NDFL (LINK_FACE, LINK_PAYS, kbk_code, SUMMA)
	SELECT LINK_FACE, SJC.LINK_PAYS, left(kbk.CODE,30), sum(SJC.SUMMA)
	FROM #S_J_C_SHORT SJC inner join dbo.SAL_SFIN kbk on SJC.LINK_VKR = kbk.LINK
	WHERE 
			YEAR(CASE WHEN SJC.TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN SJC.TYP_PER = 2 THEN SJC.DATE1 END) = @Year
		and
			month(CASE WHEN SJC.TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN SJC.TYP_PER = 2 THEN SJC.DATE1 END) <= @Month
		AND	ISNULL(SJC.PERS_LINK,0) = 0
		AND	SJC.LINK_PAYS IN (Select LINK_TAX from #NDFL_TAX)
	GROUP BY 
		LINK_FACE, LINK_PAYS, kbk.CODE

	union all ---<< Добавление информации по внештатникам	

	SELECT  PERS_LINK, SJC.LINK_PAYS, left(kbk.CODE,30), sum(SJC.SUMMA)
	FROM #S_J_C_SHORT SJC inner join dbo.SAL_SFIN kbk on SJC.LINK_VKR = kbk.LINK
	WHERE 
			YEAR(CASE WHEN SJC.TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN SJC.TYP_PER = 2 THEN SJC.DATE1 END) = @Year
		and
			month(CASE WHEN SJC.TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN SJC.TYP_PER = 2 THEN SJC.DATE1 END) <= @Month
		AND	ISNULL(SJC.LINK_FACE,0) = 0
		AND	SJC.LINK_PAYS IN (Select LINK_TAX from #NDFL_TAX)

	GROUP BY 
		PERS_LINK, LINK_PAYS, kbk.CODE
	ORDER BY 
		1, 2, 3
		
		
	DELETE FROM #P0

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS_NDFL GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET kbkcode1 = (SELECT top 1 P00.kbk_code FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET kbksum1 = (SELECT top 1 P00.SUMMA FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS_NDFL WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS_NDFL GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET kbkcode2 = (SELECT top 1 P00.kbk_code FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET kbksum2 = (SELECT top 1 P00.SUMMA FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS_NDFL WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS_NDFL GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET kbkcode3 = (SELECT top 1 P00.kbk_code FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET kbksum3 = (SELECT top 1 P00.SUMMA FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS_NDFL WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS_NDFL GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET kbkcode4 = (SELECT top 1 P00.kbk_code FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET kbksum4 = (SELECT top 1 P00.SUMMA FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS_NDFL WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END
	
	DELETE FROM #RES0 WHERE isnull(OSD13,0) = 0
---------------------------------------
----------------------------------------
------ 

	SELECT 
		FIO = RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.',
		P.INN as inn,
--		AGE_TYPE = CASE WHEN YEAR(P.BIRTHDATE) <= 1966 THEN 1 ELSE 2 END,
		NS.SUMMA as s_nach,
		PS.SUMMA as S_PER,
		R.osd13 , 
		R.sdo13 , 
		R.NALOGN13 , 
		R.NALOGU13 ,
		R.NALOG13S ,
		R.[PERSCENT], 
		DATE_B = @DATE1,
		DATE_E = @DATE2
	FROM
		dbo.PERSON P 
		INNER JOIN #RES0 R on R.LINK_FACE = P.LINK
		left  join #PERS F  on P.LINK = F.LINK
		LEFT JOIN #NACHISL NS ON NS.LINK = F.LINK
		LEFT JOIN #PERECHISL PS ON PS.LINK = F.LINK
		
	ORDER BY FIO
		
EXEC dbo.BufferClear

DROP TABLE	#P0
DROP TABLE	#RES0
DROP TABLE #PAYS_NDFL
DROP TABLE #S_J_C_SHORT
DROP TABLE #NDFL_TAX
DROP TABLE #PAYS3 
DROP TABLE #PAYS1 
DROP TABLE #PAYS_R 
DROP TABLE #PAYS_0 
DROP TABLE #spr_pays_kbk
DROP TABLE #E_SUBDIV
DROP TABLE #S_OBOSOB
DROP TABLE #P_OBOSOB
DROP TABLE #NACHISL
--DROP TABLE #PACHKI
DROP TABLE #PERECHISL
DROP TABLE #PERS

END












GO


GRANT EXECUTE ON dbo.[SS_NDFL_REPORT] TO PUBLIC

GO



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

GO



/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE [dbo].BK_REPORT_OSV_EKR1
	@varKSdDate1	DATETIME	,
	@varKSdDate2	DATETIME	,
	@nPrintKBK	INT,	-- Код счета с КБК --
	@nPrintSGU	INT,	-- Код счета с КОСГУ --
	@nPrintDEP	INT,	-- Отчет в разрезе организаций --
	@varKScVal1 char(1), @varKSnOtborLink1 int	,
	@cVal2 char(1), @nOtborLink2 int,	-- Отбор ЕКР --
	@cVal_KBK char(1), @nOtborLinkKBK int,	-- Отбор КБК --
	@cVal_DEP char(1), @nOtborLinkDEP int,	-- Отбор учреждений --
	@intSVOD_ZB INT
AS
BEGIN
	DECLARE	@varKSDEP_LINK	INT,
		@varKSORGNAME	VARCHAR(254)

	--- Отбор субсчетов --- 
	DECLARE @ACCT  TABLE (LINK_ACCT [INT])	
	IF LEN (@varKScVal1) > 0
		INSERT INTO @ACCT
		SELECT RECORD
		FROM dbo.OBJECT_VAR_ACCT
		WHERE LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO @ACCT
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode (DEFAULT, DEFAULT, DEFAULT, DEFAULT) ACCT

	--- Отбор ЭКР --- 
	DECLARE @EKR TABLE (LINK_EKR [INT], EKR_CODE  [VARCHAR] (20), EKR_NAME [VARCHAR] (254))
	IF LEN(@cVal2)>0 BEGIN
		INSERT INTO @EKR
			SELECT OVR.RECORD, D.CODE, D.[NAME]
			FROM dbo.OBJECT_VAR_KOSGU OVR, dbo.KOSGU D
			WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@nOtborLink2
	END
	ELSE
	BEGIN
		INSERT INTO @EKR
			SELECT D.LINK, D.CODE, D.[NAME] FROM dbo.KOSGU D -- FROM DICTIONARY_ITEM D
		INSERT INTO @EKR VALUES (0, '', 'Не указан')
	END

	--- ОТБОР КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	--- Отбор учреждений --- 
	DECLARE @DEP TABLE (LINK_DEP INT, DEP_CODE  VARCHAR(20), DEP_NAME VARCHAR(254) )
	IF LEN(@cVal_DEP)>0 BEGIN
		INSERT INTO @DEP
			SELECT OVR.RECORD, D.CODE, D.[NAME]
			FROM dbo.OBJECT_VAR_DEPARTMENT OVR, dbo.DICTIONARY_DEPARTMENT D
			WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@nOtborLinkDEP
	END
	ELSE
	BEGIN
		INSERT INTO @DEP
			SELECT D.LINK, D.CODE, D.[NAME] FROM dbo.DICTIONARY_DEPARTMENT D
		INSERT INTO @DEP VALUES (0, '', 'Не указан')
	END

	SET @nPrintKBK = ISNULL (@nPrintKBK, 0)
	SET @nPrintSGU = ISNULL (@nPrintSGU, 0)
	SET @nPrintDEP = ISNULL (@nPrintDEP, 0)

	/* -- Параметры организации -- */
	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)
	SET @varKSDEP_LINK = dbo.BK_GetDepZB ()

	IF @intSVOD_ZB = 1 OR @varKSDEP_LINK IS NULL
		SET @varKSDEP_LINK = dbo.GetOwnDepLink()

	SELECT @varKSORGNAME = dbo.BK_GET_PRINT_DEP_NAME (@varKSDEP_LINK)

	IF @intSVOD_ZB = 1
	BEGIN
		SET @varKSORGNAME = RTRIM (@varKSORGNAME) + ' (ЦБ)'
		SET @varKSDEP_LINK = NULL
	END

	/* --- ОСВ --- */
	DECLARE @TABLE1 TABLE (DEP [INT], ACCOUNT [INT], EKR [INT],
			KBK [INT], KOSGU [INT],
			D_SUMMA [NUMERIC] (20,2), K_SUMMA [NUMERIC] (20,2),
			IN_SUMMA [NUMERIC] (20,2), OUT_SUMMA [NUMERIC] (20,2))

	INSERT INTO @TABLE1
	SELECT
		CASE
			WHEN @nPrintDEP = 1 THEN T1.DEP
			ELSE 0
		END,
		T1.ACCOUNT,
		T1.EKR,
		CASE 
			WHEN @nPrintKBK = 1 THEN ISNULL (T1.KBK, 0)
			ELSE 0
		END,
		CASE 
			WHEN @nPrintSGU = 1 THEN ISNULL (T1.SGU, 0)
			ELSE 0
		END,
		SUM (T1.D_SUMMA),
		SUM (T1.K_SUMMA),
		SUM (T1.IN_SUMMA),
		SUM (T1.OUT_SUMMA)
	FROM dbo.BK_GetTableOSVByDate (@varKSdDate1, @varKSdDate2, @varKSDEP_LINK) T1
	INNER JOIN @ACCT AC ON (AC.LINK_ACCT = T1.ACCOUNT)
	INNER JOIN @TAB_KBK T2 ON (T2.LINK_KBK = T1.KBK)
	INNER JOIN @DEP D1 ON (D1.LINK_DEP = T1.DEP)
	GROUP BY
		CASE
			WHEN @nPrintDEP = 1 THEN T1.DEP
			ELSE 0
		END,
		T1.ACCOUNT,
		T1.EKR,
		CASE 
			WHEN @nPrintKBK = 1 THEN ISNULL (T1.KBK, 0)
			ELSE 0
		END,
		CASE 
			WHEN @nPrintSGU = 1 THEN ISNULL (T1.SGU, 0)
			ELSE 0
		END

	DECLARE @RESULT TABLE  (DEP [INT], ACCOUNT [INT], EKR [INT],
			KBK [INT], KOSGU [INT],
			DEP_CODE [VARCHAR] (20), DEP_NAME [VARCHAR] (254),
			EKR_CODE [VARCHAR] (20), EKR_NAME [VARCHAR] (254),
			ACCT_GR [VARCHAR] (30), ACCT_CODE [VARCHAR] (60),
			IN_SUM_D [NUMERIC] (20,2), IN_SUM_K [NUMERIC] (20,2),
			D_SUM [NUMERIC] (20,2),	K_SUM [NUMERIC] (20,2),
			OUT_SUM_D [NUMERIC] (20,2), OUT_SUM_K [NUMERIC] (20,2),
			ORGNAME [VARCHAR] (254))

	INSERT INTO @RESULT
	SELECT OSV.DEP,
		OSV.ACCOUNT,
		OSV.EKR,
		OSV.KBK,
		OSV.KOSGU,
		ISNULL (DEP.CODE, ''),
		ISNULL (DEP.[NAME], 'Не указан'),
		EKR.EKR_CODE,
		EKR.EKR_NAME,
		SA.CODE,
		dbo.BK_GetAcctFullCode1 (OSV.ACCOUNT, OSV.KBK, OSV.KOSGU, @nPrintKBK, @nPrintSGU),
		CASE 
			WHEN SA.S_ACTIVE = 1 THEN OSV.IN_SUMMA
			ELSE 0	
		END,
		CASE 
			WHEN SA.S_PASSIVE = 1 THEN OSV.IN_SUMMA
			ELSE 0	
		END,
		OSV.D_SUMMA,
		OSV.K_SUMMA,
		CASE 
			WHEN SA.S_ACTIVE = 1 THEN OSV.OUT_SUMMA
			ELSE 0	
		END,
		CASE 
			WHEN SA.S_PASSIVE = 1 THEN OSV.OUT_SUMMA
			ELSE 0	
		END,
		@varKSORGNAME
	FROM @TABLE1 OSV
	INNER JOIN @EKR EKR ON (EKR.LINK_EKR = OSV.EKR)
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = OSV.ACCOUNT)
	LEFT OUTER JOIN dbo.DICTIONARY_DEPARTMENT DEP ON (DEP.LINK = OSV.DEP)
	WHERE (OSV.D_SUMMA <> 0)
		OR (OSV.K_SUMMA <> 0)
		OR (OSV.IN_SUMMA <> 0)
		OR (OSV.OUT_SUMMA <> 0)

	SELECT * FROM @RESULT ORDER BY DEP_CODE, EKR_CODE, ACCT_GR, ACCT_CODE
END



GO


GRANT EXECUTE ON dbo.[BK_REPORT_OSV_EKR1] TO PUBLIC

GO


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, 
		DataP = P.DATE_PROV, 
		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


GRANT EXECUTE ON dbo.[BB_PRINT_PP] TO PUBLIC

GO



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

GO

CREATE PROCEDURE dbo.BK_REPORT_LIST_TAX_ON_OS1
	@intMonth1 int		/* Расчетный месяц */,
	@cYear1 VARCHAR(4)	/* Год */,
	@iGR_TAX int		= 0 /* Группировать по налоговым ставкам */,
	@intSVOD_ZB	INT,
	@cValTAX	CHAR (1), @nOtborTax	INT
AS
BEGIN
	DECLARE
		@dDATE_END_MONTH	DATETIME,
		@dDATE_CALC_REST	DATETIME,
		@intDEP_LINK		INT,
		@varKSORGNAME		VARCHAR (254),
		@strINN			VARCHAR (30),
		@intNoTAX int		/* Вывести ОС, не включенные в налогооблагаемую базу */

	SET @dDATE_CALC_REST = dbo.ConvertDMY2Date (1, @intMonth1, CONVERT (INT, @cYear1))

	SET @iGR_TAX = ISNULL (@iGR_TAX, 0)

	--- Параметры организации --- 
	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)	-- Сводный отчет по ЦБ -- 
	
	SET @intDEP_LINK = dbo.BK_GetDepZB ()

	IF @intSVOD_ZB = 1 OR @intDEP_LINK IS NULL 	
		SET @intDEP_LINK = dbo.GetOwnDepLink ()

	SELECT
		@varKSORGNAME = dbo.BK_GET_PRINT_DEP_NAME (@intDEP_LINK),
		@strINN = RTRIM (INN) + CASE
									WHEN ISNULL (INN_DOP, '') = '' THEN ''
									ELSE '/' + INN_DOP
								END
	FROM dbo.DEPARTMENTS
	WHERE LINK = @intDEP_LINK

	IF @intSVOD_ZB = 1
		SELECT
			@varKSORGNAME = RTRIM (@varKSORGNAME) + ' (ЦБ)',
			@intDEP_LINK = NULL

	-- Отбор ставок --
	IF LEN (@cValTAX) > 0
		SET @nOtborTax = ISNULL (@nOtborTax, 0)
	ELSE
		SET @nOtborTax = 0	
		
	DECLARE @T_TAX_RATE TABLE (LINK INT)
	
	INSERT INTO @T_TAX_RATE
	SELECT RECORD
	FROM dbo.OBJECT_VAR_OTHER_REC
	WHERE LINK_UP = @nOtborTax

	DECLARE @T_NALOG TABLE
		(INV INT, 
		ACCOUNT	INT,
		BALANS NUMERIC (28,4), AMORT NUMERIC (28,4), OST_SUM NUMERIC (28,4),
		LINK_TAX	INT)

	DECLARE @RET_TABLE TABLE
		(INV INT, INV_CODE VARCHAR (20), INV_NAME VARCHAR (254),
		ACCT_CODE VARCHAR (60),
		BALANSE NUMERIC (28,4), AMORT NUMERIC (28,4), SUM_LAST NUMERIC (28,4),
		ORGNAME VARCHAR (254), ORG_INN VARCHAR (30),
		ORD_FIELD VARCHAR (50),
		TAX_RATE	VARCHAR (10))
/*
-- NO_NALOG = 0 Включается в базу по налогу на имущество  
-- NO_NALOG = 1 Не включается в базу по налогу на имущество (льготируемое имущесвто)  
-- NO_NALOG = 2 Включается в базу по налогу на имущество ставка налога = 0   
SELECT * FROM DIC_IMU_TAX_RATE    
*/

	INSERT INTO @T_NALOG 
		(INV, ACCOUNT,
		BALANS, AMORT, OST_SUM,
		LINK_TAX)
	SELECT
		T1.INV,
		T1.ACCOUNT,
		SUM (T1.BALANS),
		SUM (T1.AMORT),
		SUM (T1.OST_SUM),
		CASE
			WHEN NO_NALOG = 0 THEN 2
			WHEN NO_NALOG = 1 THEN 3
			WHEN NO_NALOG = 2 THEN 1
			ELSE 0
		END
	FROM dbo.CalcNalogBalanceOS (@dDATE_CALC_REST, @intDEP_LINK) T1
	GROUP BY
		T1.INV,
		T1.ACCOUNT,
		CASE
			WHEN NO_NALOG = 0 THEN 2
			WHEN NO_NALOG = 1 THEN 3
			WHEN NO_NALOG = 2 THEN 1
			ELSE 0
		END
	HAVING
		SUM (T1.BALANS) <> 0

--SELECT * FROM @T_NALOG

	INSERT INTO @RET_TABLE
	SELECT
		T1.INV,
		INV.CODE,
		INV.[NAME],
		SA.CODE,
		T1.BALANS,
		T1.AMORT,
		T1.OST_SUM,
		@varKSORGNAME,
		@strINN,
		RIGHT ('00000000000000000000' + RTRIM (LTRIM (ISNULL (INV.CODE, ''))), 20),
		CASE WHEN @iGR_TAX = 0 THEN '' ELSE ISNULL (TR.CODE, '') END
	FROM @T_NALOG T1
	INNER JOIN dbo.INVENTORY INV ON (INV.LINK = T1.INV)
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = T1.ACCOUNT)
	LEFT JOIN (
			SELECT
				TTT.LINK,
				CODE = CASE
							WHEN TTT.CODE = '-' THEN 'ЛЬГОТА'
							ELSE CONVERT (VARCHAR (10), TTT.CODE)
						END
			FROM dbo.DIC_IMU_TAX_RATE TTT
			) AS TR ON (TR.LINK = T1.LINK_TAX)
	WHERE @nOtborTax = 0 
		OR @nOtborTax > 0 AND EXISTS (SELECT * FROM @T_TAX_RATE TTT WHERE TTT.LINK = T1.LINK_TAX) 

	SELECT
		*,
		GR_TAX = @iGR_TAX
	FROM @RET_TABLE RT
	ORDER BY 
		TAX_RATE,
		ACCT_CODE,
		ORD_FIELD
	
END

GO

GRANT EXECUTE ON dbo.[BK_REPORT_LIST_TAX_ON_OS1] TO PUBLIC

GO


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


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

GO


/*
© Кейсистемс (Keysystems), 2006
*/
CREATE PROCEDURE dbo.BK_REPORT_OSV_DOP_CLASSIF
	@varKSdDate1	DATETIME	,
	@varKSdDate2	DATETIME	,
	@nPrintKBK	INT		, -- Код счета с КБК --
	@nPrintSGU	INT		, -- Код счета с КОСГУ --
	@strAP_CODE	VARCHAR (60) = '',	
	@varKScVal1 char(1), @varKSnOtborLink1 int	,
	@cVal2 char(1), @nOtborLink2 int	, -- Отбор ДОП. КЛАССИФИКАЦИИ --
	@cVal3 char(1), @nOtborLink3 int	, -- Отбор Учреждений --
	@cVal_KBK char(1), @nOtborLinkKBK int	, -- Отбор КБК -- 
	@cVal_Emp char(1), @nOtborLinkEMP int	, -- Отбор Учреждений --
	@intSVOD_ZB INT
AS
BEGIN
	DECLARE	@varKSDEP_LINK	INT,
		@varKSORGNAME	VARCHAR(254),
		@strDIC_TITLE	VARCHAR (20)

	--- ОТБОР СУБСЧЕТОВ --- 
	DECLARE @ACCT  TABLE (LINK_ACCT [INT])	
	IF LEN (@varKScVal1) > 0
		INSERT INTO @ACCT
		SELECT RECORD
		FROM OBJECT_VAR_ACCT
		WHERE LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO @ACCT
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode (DEFAULT, DEFAULT, DEFAULT, DEFAULT) ACCT

	--- ОТБОР ПОКАЗАТЕЛЕЙ ---
	DECLARE @TABLE_AP0 TABLE (LINK_AP0 [INT], AP0_CODE  [VARCHAR] (20), AP0_NAME [VARCHAR] (254))

		--- Отбор учреждений --- 
	IF @strAP_CODE = 'DEP'
		IF LEN(@cVal3)>0
			INSERT INTO @TABLE_AP0
			SELECT OVR.RECORD, D.CODE, D.[NAME]
			FROM dbo.OBJECT_VAR_DEPARTMENT OVR, dbo.DICTIONARY_DEPARTMENT D
			WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@nOtborLink3
		ELSE
			INSERT INTO @TABLE_AP0
			SELECT LINK_AP, AP_CODE, AP_NAME
			FROM dbo.BK_GetTableDictionByAP (@strAP_CODE)	

	--- Отбор сотрудников --- 
	IF @strAP_CODE = 'EMP'
		IF LEN (@cVal_Emp) > 0 
			INSERT INTO @TABLE_AP0
			SELECT OVR.RECORD, D.TAB, D.NAME_EMPL
			FROM dbo.OBJECT_VAR_EMPL OVR, dbo.KU_EMPL_PLACING D
			WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@nOtborLinkEMP
		ELSE
			INSERT INTO @TABLE_AP0
			SELECT LINK_AP, AP_CODE, AP_NAME
			FROM dbo.BK_GetTableDictionByAP (@strAP_CODE)	

	--- Заглушка, если не выбран показатель --- 
	IF ISNULL (@strAP_CODE, '') NOT IN ('DEP', 'EMP')
		INSERT INTO @TABLE_AP0
		VALUES (0, '', '')

	--- ОТБОР ДОП. КЛАССИФИКАЦИИ --- 
	DECLARE @TABLE_AP2 TABLE (LINK_AP [INT], AP_CODE  [VARCHAR] (20), AP_NAME [VARCHAR] (254))
	IF LEN(@cVal2)>0 BEGIN
		INSERT INTO @TABLE_AP2
			SELECT OVR.RECORD, D.CODE, D.[NAME]
			FROM dbo.OBJECT_VAR_DOP_CLASSIF OVR, dbo.BD_DOP_CLASSIF D
			WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@nOtborLink2
	END
	ELSE
	BEGIN
		INSERT INTO @TABLE_AP2
		SELECT LINK_AP, AP_CODE, AP_NAME
		FROM dbo.BK_GetTableDictionByAP ('AP2')	
	END

	--- ОТБОР КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	-- Параметры организации -- 
	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)
	SET @varKSDEP_LINK = dbo.BK_GetDepZB ()

	IF @intSVOD_ZB = 1 OR @varKSDEP_LINK IS NULL
		SET @varKSDEP_LINK = dbo.GetOwnDepLink()

	SELECT @varKSORGNAME = dbo.BK_GET_PRINT_DEP_NAME (@varKSDEP_LINK)

	IF @intSVOD_ZB = 1
	BEGIN
		SET @varKSORGNAME = RTRIM (@varKSORGNAME) + ' (ЦБ)'
		SET @varKSDEP_LINK = NULL
	END

	SET @nPrintKBK = ISNULL (@nPrintKBK, 0)
	SET @nPrintSGU = ISNULL (@nPrintSGU, 0)

	--- ОСВ --- 
	DECLARE @TABLE1 TABLE (AP0 [INT], ACCOUNT [INT], AP [INT],
			KBK [INT], KOSGU [INT],
			D_SUMMA [NUMERIC] (20,2), K_SUMMA [NUMERIC] (20,2),
			IN_SUMMA [NUMERIC] (20,2), OUT_SUMMA [NUMERIC] (20,2))

	INSERT INTO @TABLE1
	SELECT
		CASE
			WHEN @strAP_CODE = 'EMP' THEN T1.EMP
			WHEN @strAP_CODE = 'DEP' THEN T1.DEP
			ELSE 0
		END,
		T1.ACCOUNT,
		T1.AP2,
		CASE 
			WHEN @nPrintKBK = 1 THEN ISNULL (T1.KBK, 0)
			ELSE 0
		END,
		CASE 
			WHEN @nPrintSGU = 1 THEN ISNULL (T1.SGU, 0)
			ELSE 0
		END,
		SUM (T1.D_SUMMA),
		SUM (T1.K_SUMMA),
		SUM (T1.IN_SUMMA),
		SUM (T1.OUT_SUMMA)
	FROM dbo.BK_GetTableOSVByDate (@varKSdDate1, @varKSdDate2, @varKSDEP_LINK) T1
	INNER JOIN @ACCT AC ON (AC.LINK_ACCT = T1.ACCOUNT)
	INNER JOIN @TAB_KBK T2 ON (T2.LINK_KBK = T1.KBK)
	GROUP BY
		CASE
			WHEN @strAP_CODE = 'EMP' THEN T1.EMP
			WHEN @strAP_CODE = 'DEP' THEN T1.DEP
			ELSE 0
		END,
		T1.ACCOUNT,
		T1.AP2,
		CASE 
			WHEN @nPrintKBK = 1 THEN ISNULL (T1.KBK, 0)
			ELSE 0
		END,
		CASE 
			WHEN @nPrintSGU = 1 THEN ISNULL (T1.SGU, 0)
			ELSE 0
		END

	DECLARE @RESULT TABLE  (AP0 [INT], ACCOUNT [INT], AP [INT],
			KBK [INT], KOSGU [INT],
			AP0_CODE [VARCHAR] (20), AP0_NAME [VARCHAR] (254),
			AP_CODE [VARCHAR] (20), AP_NAME [VARCHAR] (254),
			ACCT_GR [VARCHAR] (30), ACCT_CODE [VARCHAR] (60),
			IN_SUM_D [NUMERIC] (20,2), IN_SUM_K [NUMERIC] (20,2),
			D_SUM [NUMERIC] (20,2),	K_SUM [NUMERIC] (20,2),
			OUT_SUM_D [NUMERIC] (20,2), OUT_SUM_K [NUMERIC] (20,2),
			ORGNAME [VARCHAR] (254))

	INSERT INTO @RESULT
	SELECT OSV.AP0,
		OSV.ACCOUNT,
		OSV.AP,
		OSV.KBK,
		OSV.KOSGU,
		ISNULL (AP0.AP0_CODE, ''),
		ISNULL (AP0.AP0_NAME, 'Не указан'),
		AP.AP_CODE,
		AP.AP_NAME,
		SA.CODE,
		dbo.BK_GetAcctFullCode1 (OSV.ACCOUNT, OSV.KBK, OSV.KOSGU, @nPrintKBK, @nPrintSGU),
		CASE 
			WHEN SA.S_ACTIVE = 1 THEN OSV.IN_SUMMA
			ELSE 0	
		END,
		CASE 
			WHEN SA.S_PASSIVE = 1 THEN OSV.IN_SUMMA
			ELSE 0	
		END,
		OSV.D_SUMMA,
		OSV.K_SUMMA,
		CASE 
			WHEN SA.S_ACTIVE = 1 THEN OSV.OUT_SUMMA
			ELSE 0	
		END,
		CASE 
			WHEN SA.S_PASSIVE = 1 THEN OSV.OUT_SUMMA
			ELSE 0	
		END,
		@varKSORGNAME
	FROM @TABLE1 OSV
	INNER JOIN @TABLE_AP2 AP ON (AP.LINK_AP = OSV.AP)
	INNER JOIN @TABLE_AP0 AP0 ON (AP0.LINK_AP0 = OSV.AP0)
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = OSV.ACCOUNT)
	WHERE (OSV.D_SUMMA <> 0)
		OR (OSV.K_SUMMA <> 0)
		OR (OSV.IN_SUMMA <> 0)
		OR (OSV.OUT_SUMMA <> 0)

	SET @strDIC_TITLE = ISNULL ((SELECT TOP 1 S_TITLE FROM dbo.ANALIT WHERE CODE_AP = @strAP_CODE), '')

	SELECT 
		@strDIC_TITLE AS D_TITLE,
		@strAP_CODE AS D_CODE,
		*
	FROM @RESULT ORDER BY AP0_CODE, AP_CODE, ACCT_GR, ACCT_CODE
END


GO


GRANT EXECUTE ON dbo.[BK_REPORT_OSV_DOP_CLASSIF] TO PUBLIC

GO



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

GO

CREATE	PROCEDURE [dbo].BV_UPDATE_BSO_OPER
	@varKSpLINK		INT	OUTPUT,	
	@varKSpLINK_DOC	INT,		
	@varKSpRANGE_BEGIN	NUMERIC(10,0),		
	@varKSpRANGE_END	NUMERIC(10,0),		
	@varKSpTYPE_BSO	INT,		
	@varKSpDEP		INT,		
	@varKSpDB_KT		SMALLINT,	
	@varKSpQUANTITY	SMALLINT,	
	@varKSpEMP		INT,
	@varPRICE	NUMERIC(18,4),
	@varNOTICE	varchar(254)  = '',
	@varDATE_END DATETIME = null		
AS
DECLARE
	@varKSSQLError INT,
	@varKSRowCount INT,
	@varKStrancount INT
SET @varKStrancount = @@TRANCOUNT

SET IMPLICIT_TRANSACTIONS ON
	BEGIN TRAN
	COMMIT TRAN

	IF @varKSpRANGE_BEGIN > @varKSpRANGE_END
	BEGIN
		ROLLBACK
		RETURN 1001
	END

	SELECT @varKSpLINK_DOC = LINK FROM G_PROV WITH (UPDLOCK) WHERE LINK = @varKSpLINK_DOC
	SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
	IF @varKSSQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
	IF @varKSRowCount = 0
	BEGIN
		ROLLBACK 
		RETURN 3
	END

	SELECT @varKSpTYPE_BSO = LINK FROM NOMENCLATURE WITH (UPDLOCK) WHERE LINK = @varKSpTYPE_BSO
	SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
	IF @varKSSQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END

	SELECT @varKSpDEP = LINK FROM DEPARTMENTS WITH (UPDLOCK) WHERE LINK = @varKSpDEP
	SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
	IF @varKSSQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
	
	SELECT @varKSpEMP = LINK FROM EMPL WITH (UPDLOCK) WHERE LINK = @varKSpEMP
	SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
	IF @varKSSQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
	
	IF @varKSpLINK IS NOT NULL AND @varKSpLINK > 0
	BEGIN
		UPDATE BSO_OPER
		SET	LINK_DOC	= @varKSpLINK_DOC,
			RANGE_BEGIN	= @varKSpRANGE_BEGIN,
			RANGE_END	= @varKSpRANGE_END,
			TYPE_BSO	= @varKSpTYPE_BSO,
			DEP		= @varKSpDEP,
			DB_KT		= @varKSpDB_KT,
			QUANTITY	= @varKSpQUANTITY,
			EMP		= @varKSpEMP, 
			PRICE		= @varPRICE,
			NOTICE      = @varNOTICE,
			DATE_END    = @varDate_END
		WHERE 	(LINK	= @varKSpLINK)

		SELECT @varKSSQLError = @@ERROR, @varKSRowCount = @@ROWCOUNT
		IF @varKSSQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @varKSRowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
	END	
	ELSE
	BEGIN
		INSERT BSO_OPER (LINK_DOC, RANGE_BEGIN, RANGE_END,
			TYPE_BSO, DEP, DB_KT, QUANTITY, EMP, PRICE,NOTICE,DATE_END)
		VALUES (@varKSpLINK_DOC, @varKSpRANGE_BEGIN, @varKSpRANGE_END,
			@varKSpTYPE_BSO, @varKSpDEP, @varKSpDB_KT, @varKSpQUANTITY, @varKSpEMP, @varPRICE,@varNOTICE,@varDate_END)

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

	IF @@TRANCOUNT > @varKStrancount
		COMMIT TRAN
	RETURN 0

GO

GRANT EXECUTE ON dbo.[BV_UPDATE_BSO_OPER] TO PUBLIC

GO



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

GO


/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE [dbo].BK_REPORT_OSV_SUBDIV1
	@varKSdDate1	DATETIME	,
	@varKSdDate2	DATETIME	,
	@nPrintKBK	INT	/* Код счета с КБК */,
	@nPrintSGU	INT	/* Код счета с КОСГУ */,
	@nPrintDEP	INT	/* Отчет в разрезе организаций */,
	@intPrintNULL	INT	/* Включить с пустыми подразделения */,
	@varKScVal1 char(1), @varKSnOtborLink1 int	,
	@cVal2 char(1), @nOtborLink2 int	/* Отбор подразделений */,
	@cVal_KBK char(1), @nOtborLinkKBK int	/* Отбор КБК */,
	@intSVOD_ZB INT
AS
BEGIN
	DECLARE	@varKSDEP_LINK	INT,
		@varKSORGNAME	VARCHAR(254)

	/* --- ОТБОР СУБСЧЕТОВ --- */
	DECLARE @ACCT  TABLE (LINK_ACCT [INT])	
	IF LEN (@varKScVal1) > 0
		INSERT INTO @ACCT
		SELECT RECORD
		FROM dbo.OBJECT_VAR_ACCT
		WHERE LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO @ACCT
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode (DEFAULT, DEFAULT, DEFAULT, DEFAULT) ACCT

	/* --- ОТБОР ПОДРАЗДЕЛЕНИЙ --- */
	DECLARE @AP_TABLE TABLE (LINK_AP [INT], AP_CODE  [VARCHAR] (20), AP_NAME [VARCHAR] (254))
	IF LEN(@cVal2)>0 BEGIN
		INSERT INTO @AP_TABLE
			SELECT OVR.RECORD, D.CODE, D.[NAME]
			FROM dbo.OBJECT_VAR_SUBDIV_HEAD OVR, dbo.SUBDIVISION (@varKSdDate2) D
			WHERE D.LINK =OVR.RECORD AND OVR.LINK_UP=@nOtborLink2
	END
	ELSE
	BEGIN
		INSERT INTO @AP_TABLE
			SELECT D.LINK, D.CODE, D.[NAME] FROM dbo.SUBDIVISION (@varKSdDate2) D 
		IF ISNULL (@intPrintNULL, 0) = 1
			INSERT INTO @AP_TABLE VALUES (0, '', 'Не указан')
	END

	--- ОТБОР КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	/* -- Параметры организации -- */
	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)
	SET @varKSDEP_LINK = dbo.BK_GetDepZB ()

	IF @intSVOD_ZB = 1 OR @varKSDEP_LINK IS NULL
		SET @varKSDEP_LINK = dbo.GetOwnDepLink()

	SET @varKSORGNAME = dbo.BK_GET_PRINT_DEP_NAME (@varKSDEP_LINK)

	IF @intSVOD_ZB = 1
	BEGIN
		SET @varKSORGNAME = RTRIM (@varKSORGNAME) + ' (ЦБ)'
		SET @varKSDEP_LINK = NULL
	END

	SET @nPrintKBK = ISNULL (@nPrintKBK, 0)
	SET @nPrintSGU = ISNULL (@nPrintSGU, 0)
	SET @nPrintDEP = ISNULL (@nPrintDEP, 0)

	DECLARE @TABLE1 TABLE (DEP [INT], ACCOUNT [INT], AP [INT],
			KBK [INT], KOSGU [INT],
			D_SUMMA [NUMERIC] (20,2), K_SUMMA [NUMERIC] (20,2),
			IN_SUMMA [NUMERIC] (20,2), OUT_SUMMA [NUMERIC] (20,2))

	INSERT INTO @TABLE1
	SELECT
		CASE
			WHEN @nPrintDEP = 1 THEN T1.DEP
			ELSE 0
		END,
		T1.ACCOUNT,
		T1.SUB,
		CASE 
			WHEN @nPrintKBK = 1 THEN ISNULL (T1.KBK, 0)
			ELSE 0
		END,
		CASE 
			WHEN @nPrintSGU = 1 THEN ISNULL (T1.SGU, 0)
			ELSE 0
		END,
		SUM (T1.D_SUMMA),
		SUM (T1.K_SUMMA),
		SUM (T1.IN_SUMMA),
		SUM (T1.OUT_SUMMA)
	FROM dbo.BK_GetTableOSVByDate (@varKSdDate1, @varKSdDate2, @varKSDEP_LINK) T1
	INNER JOIN @ACCT AC ON (AC.LINK_ACCT = T1.ACCOUNT)
	INNER JOIN @TAB_KBK T2 ON (T2.LINK_KBK = T1.KBK)
	GROUP BY
		CASE
			WHEN @nPrintDEP = 1 THEN T1.DEP
			ELSE 0
		END,
		T1.ACCOUNT,
		T1.SUB,
		CASE 
			WHEN @nPrintKBK = 1 THEN ISNULL (T1.KBK, 0)
			ELSE 0
		END,
		CASE 
			WHEN @nPrintSGU = 1 THEN ISNULL (T1.SGU, 0)
			ELSE 0
		END

	DECLARE @RESULT TABLE  (DEP [INT], ACCOUNT [INT], AP [INT],
			KBK [INT], KOSGU [INT],
			DEP_CODE [VARCHAR] (20), DEP_NAME [VARCHAR] (254),
			AP_CODE [VARCHAR] (20), AP_NAME [VARCHAR] (254),
			ACCT_GR [VARCHAR] (30), ACCT_CODE [VARCHAR] (60),
			IN_SUM_D [NUMERIC] (20,2), IN_SUM_K [NUMERIC] (20,2),
			D_SUM [NUMERIC] (20,2),	K_SUM [NUMERIC] (20,2),
			OUT_SUM_D [NUMERIC] (20,2), OUT_SUM_K [NUMERIC] (20,2),
			ORGNAME [VARCHAR] (254))

	INSERT INTO @RESULT
	SELECT OSV.DEP,
		OSV.ACCOUNT,
		OSV.AP,
		OSV.KBK,
		OSV.KOSGU,
		ISNULL (DEP.CODE, ''),
		ISNULL (DEP.[NAME], 'Не указан'),
		AP.AP_CODE,
		AP.AP_NAME,
		SA.CODE,
		dbo.BK_GetAcctFullCode1 (OSV.ACCOUNT, OSV.KBK, OSV.KOSGU, @nPrintKBK, @nPrintSGU),
		CASE 
			WHEN SA.S_ACTIVE = 1 THEN OSV.IN_SUMMA
			ELSE 0	
		END,
		CASE 
			WHEN SA.S_PASSIVE = 1 THEN OSV.IN_SUMMA
			ELSE 0	
		END,
		OSV.D_SUMMA,
		OSV.K_SUMMA,
		CASE 
			WHEN SA.S_ACTIVE = 1 THEN OSV.OUT_SUMMA
			ELSE 0	
		END,
		CASE 
			WHEN SA.S_PASSIVE = 1 THEN OSV.OUT_SUMMA
			ELSE 0	
		END,
		@varKSORGNAME
	FROM @TABLE1 OSV
	INNER JOIN @AP_TABLE AP ON (AP.LINK_AP = OSV.AP)
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = OSV.ACCOUNT)
	LEFT OUTER JOIN dbo.DICTIONARY_DEPARTMENT DEP ON (DEP.LINK = OSV.DEP)
	WHERE (OSV.D_SUMMA <> 0)
		OR (OSV.K_SUMMA <> 0)
		OR (OSV.IN_SUMMA <> 0)
		OR (OSV.OUT_SUMMA <> 0)

	SELECT *
	FROM @RESULT
	ORDER BY DEP_CODE, RIGHT ('00000000000000000000' + AP_CODE, 20), 
		ACCT_GR, ACCT_CODE

END

GO


GRANT EXECUTE ON dbo.[BK_REPORT_OSV_SUBDIV1] TO PUBLIC

GO



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

GO


CREATE PROCEDURE [dbo].[RO_CALC_NASTR]
	@intIS_NOT_CALC	TINYINT OUTPUT,
	@varKSiLSF		INT,
	@varKSiLT		INT = NULL,
	@varKSiOrderCol	INT = 0, -- внутренний порядок
	@varKScCodeRow	varchar(50) = '',
	@varKSfValue	float = 0 output 
AS

DECLARE @ldEnd		  DATETIME,
		@ldBegin      DATETIME,
		@liYear       INT,
		@ADM_CODE	  CHAR(3),
		@dCALC_DATE	  DATETIME,
		@iDEP_LINK	  INT,
		@LF		int, @LT int,
		@execStr		varchar(8000),
		@LC			int,
		@bid		varchar(100),
		@nabor_filter varchar(100),
		@orderCol	int,
		@iLinkCalcForm int,
		@lbKBK_FILTER int,
		@iForm737 tinyint

SET @intIS_NOT_CALC = 0

if exists(select * from dbo.REPORT_FORMS RF 
					inner join dbo.REPORT_SAVED_FORMS RSF on RF.Link_Form = RSF.Link_Form and RSF.Link_Saved_Form = @varKSiLSF
					where left(RF.CODE,7) = '0503737')
	set @iForm737 = 1
else	
	set @iForm737 = 0
	
declare @temp_nastr1 table (link int, [Link_Col] int NOT NULL, [Code_Row] varchar(50) NOT NULL,
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL, dt_z int, kt_z int, dt_mask varchar(1000), kt_mask varchar(1000), 
	dt_ekr varchar(1000), kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint, oper varchar(1000))


declare @temp_nastr table (link int, [Link_Col] int NOT NULL, [Code_Row] varchar(50) NOT NULL,
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL, link_dt int, link_kt int, dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint)
declare @temp_nastr_xor table (	link int, [Link_Col] int NOT NULL , [Code_Row] varchar(50) NOT NULL,
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_dt int, link_kt int, dt_ekr varchar(1000),
	kt_ekr varchar(1000), [type] tinyint, type_kbk tinyint, dt_kt tinyint)
declare @temp_nastr_rest table (	link int, [Link_Col] int NOT NULL , [Code_Row] varchar(50) NOT NULL,
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000),
	[type] tinyint, type_kbk tinyint, mask_kbk varchar(100), dt_kt tinyint, oper varchar(1000))
declare @temp_nastr_rest_xor table (link int, [Link_Col] int NOT NULL , [Code_Row] varchar(50) NOT NULL,
	[Calc_Order] int NOT NULL , [Sign] tinyint NOT NULL , link_account int, ekr varchar(1000),
	[type] tinyint, type_kbk tinyint, dt_kt tinyint)

declare @filter_kbk table (kbk varchar(30))

CREATE TABLE #tTemp  (KBK varchar(50), Link_Col int, SUMMA FLOAT, Calc_Order int)
declare @t_Col table (Link_Col int, orderCol int)

-------- ЧИТАЕМ ДАННЫЕ ОТЧЕТА
select @LF = RSF.Link_Form, 
		@iDEP_LINK 	= Link_Organization, 
		@ldEnd		= Begin_Date + 1,
		@dCALC_DATE	= Begin_Date, 
		@liYear		= YEAR(Begin_Date),
		@ldBegin	= dbo.DateBeginOfYear(Begin_Date)
from report_saved_forms RSF  where RSF.link_saved_form = @varKSiLSF

--- Поиск расчета по заданным атрибутам ---
/*
set @iLinkCalcForm = (select top 1 CF.LINK
			from dbo.REPORT_ATRIBUT_VALUES RA
			inner join dbo.REPORT_CALC_ATRIBUTE CA on RA.code_atr = CA.code_atr
			inner join dbo.REPORT_CALC_FORMS CF on CA.LINK_CALC_FORM = CF.LINK and CF.LINK_FORM = @LF
			where RA.LINK_SAVED_FORM = @varKSiLSF and CF.USED = 1 
			order by CF.[ORDER] desc)

--- Если нет расчета с заданными атрибутами, то поиск расчета без атрибутов ---
IF @iLinkCalcForm is null 
	set @iLinkCalcForm = (select top 1 CF.LINK
				from dbo.REPORT_CALC_FORMS CF 
				where CF.LINK_FORM = @LF and CF.USED = 1 
				order by CF.[ORDER] desc)

*/
SET @iLinkCalcForm = dbo.RK_GET_NASTR_CALC_REPORT (@varKSiLSF, 0)

if @iLinkCalcForm is null 
BEGIN
	SET @intIS_NOT_CALC = 1
	RETURN 0
END

--- Удаление старых записей ---
if @varKSiLT is NULL or isnull(@varKSiOrderCol,0) = 0
BEGIN
	insert @t_Col (Link_Col, orderCol)
	select Link_Col, Export_Order
	from report_coloumns RC
	join report_tables RT on RC.Link_Table = RT.Link_Table
	where RT.Link_Form = @LF

	DELETE FROM dbo.REPORT_DINAMICS WHERE LINK_SF = @varKSiLSF
END
ELSE
BEGIN
	SELECT @orderCol = Export_Order, @LC = Link_Col
	FROM dbo.REPORT_COLOUMNS
	WHERE link_table = @varKSiLT and orders = @varKSiOrderCol
	INSERT @t_Col (Link_Col, orderCol)
	VALUES (@LC, @orderCol)
end

--select * from @t_Col where link_col = 57755

select @nabor_filter = dbo.rn_get_atr_value(@varKSiLSF,'REPORTS_FILTER_KBK')

select @nabor_filter = REPLACE (@nabor_filter, 'Не отобрано', '')

IF EXISTS(Select LINK FROM rn_get_filter(@varKSiLSF,'REPORTS_FILTER_KBK'))
	set @lbKBK_FILTER = 1
else
	set @lbKBK_FILTER = 0

-- Olga 2011.07.19
insert @filter_kbk (kbk)   
Select RTRIM(code) FROM rn_get_filter(@varKSiLSF,'REPORTS_FILTER_KBK')

SET @ADM_CODE = dbo.rn_get_atr_value(@varKSiLSF,'REPORTS_ATR_ADM')
IF isnull(@ADM_CODE, '') <> '' and isnull(@ADM_CODE, '') <> '000' 
BEGIN 
   insert @filter_kbk (kbk)   
   Select @ADM_CODE
   set @nabor_filter = 'REPORTS_ATR_ADM'
END 


insert @temp_nastr1
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign],
	DT_Z = case when charindex('.',CR.DT_Mask,charindex('.',DT_Mask) + 1) - charindex('.',DT_Mask) = 3 or len(DT_Mask) - charindex('.',DT_Mask) = 2 then 1 else 0 end, 
	KT_Z = case when charindex('.',CR.KT_Mask,charindex('.',KT_Mask) + 1) - charindex('.',KT_Mask) = 3 or len(KT_Mask) - charindex('.',KT_Mask) = 2 then 1 else 0 end,
	CR.DT_Mask , CR.KT_Mask, dt_ekr, kt_ekr,
	[type], type_kbk, mask_kbk, dt_kt, oper
from dbo.REPORT_CALC C 
INNER JOIN @t_Col RC on RC.Link_Col = C.Link_Col
INNER JOIN dbo.report_calc_rows CR on CR.Link_calc = C.link
WHERE C.LINK_UP = @iLinkCalcForm

--   
---------------------------------------------------------------------
----- ПОЛУЧАЕМ ВЫБОРКУ ИЗ ТАБЛИЦЫ НАСТРОЕК ----
insert @temp_nastr 
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign],
	DT.link , KT.link, dt_ekr, kt_ekr,
	[type], type_kbk, mask_kbk, dt_kt
from @temp_nastr1 C
left join dbo.s_accounts DT on DT.Code like case when C.DT_Mask = '%' or rtrim (C.DT_Mask) = '' then 'x' else rtrim (C.DT_Mask) + '%' end
left join dbo.s_accounts KT on	KT.Code like case when C.KT_Mask = '%' or rtrim (C.KT_Mask) = ''then 'x' else rtrim (C.KT_Mask) + '%' end
WHERE C.[sign] in (1,2) and C.[type] = 1 
	AND (rtrim (C.DT_Mask) = '' OR C.DT_Mask = '%' OR rtrim (C.DT_Mask) <> '' AND DT.LINK IS NOT NULL and DT.zabalans = C.DT_Z)
	AND (rtrim (C.KT_Mask) = '' OR C.KT_Mask = '%' OR rtrim (C.KT_Mask) <> '' AND KT.LINK IS NOT NULL and KT.zabalans = C.KT_Z)
--select * from @temp_nastr where link_col = 57755

/*
SELECT S1.CODE AS DT, S2.CODE AS KT
FROM @temp_nastr T
LEFT JOIN S_ACCOUNTS S1 ON S1.LINK = LINK_DT
LEFT JOIN S_ACCOUNTS S2 ON S2.LINK = LINK_KT
*/
/*	AND DT.cSOURCE = KT.cSOURCE
	AND DT.ZABALANS = KT.ZABALANS
*/
-- проводки, которые мы исключаем --
insert @temp_nastr_xor 
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign], DT.link , KT.link, dt_ekr, kt_ekr, [type], type_kbk, dt_kt
from @temp_nastr1 C
left join dbo.s_accounts DT on DT.Code like case when C.DT_Mask = '%' or rtrim (C.DT_Mask) = '' then 'x' else rtrim (C.DT_Mask) + '%' end
left join dbo.s_accounts KT on	KT.Code like case when C.KT_Mask = '%' or rtrim (C.KT_Mask) = ''then 'x' else rtrim (C.KT_Mask) + '%' end
where C.[sign] = 3 and C.[type] = 1
	AND (rtrim (C.DT_Mask) = '' OR C.DT_Mask = '%' OR rtrim (C.DT_Mask) <> '' AND DT.LINK IS NOT NULL and DT.zabalans = C.DT_Z)
	AND (rtrim (C.KT_Mask) = '' OR C.KT_Mask = '%' OR rtrim (C.KT_Mask) <> '' AND KT.LINK IS NOT NULL and KT.zabalans = C.KT_Z)
 

/*	AND DT.cSOURCE = KT.cSOURCE
	AND DT.ZABALANS = KT.ZABALANS
*/

--select t.* from @temp_nastr t 

/*
select t.* from @temp_nastr t
select t1.* from @temp_nastr_xor t1 -- on t1.link_col = t.link_col
*/
--- Удаление лишних корреспонденций ---
/*
DELETE T1
FROM @temp_nastr T1
INNER JOIN @temp_nastr_xor T2 ON (T2.LINK = T1.LINK
	AND T2.LINK_COL = T1.LINK_COL
	AND T2.CODE_ROW = T1.CODE_ROW
	AND T2.LINK_DT = T1.LINK_DT
	AND T2.LINK_KT = T1.LINK_KT)
*/
-- select * from @temp_nastr 

--- Выборка счетов для расчета остатков ---
insert @temp_nastr_rest 
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign],
	case
		when DT.link is NULL then KT.link
		else DT.link
	end,
	case
		when DT.link is NULL then kt_ekr
		else dt_ekr
	end, [type],
	type_kbk,
	mask_kbk,
	dt_kt,
	oper
from @temp_nastr1 C
left join dbo.s_accounts DT on DT.Code like case when C.DT_Mask = '%' or rtrim (C.DT_Mask) = '' then 'x' else rtrim (C.DT_Mask) + '%' end
left join dbo.s_accounts KT on	KT.Code like case when C.KT_Mask = '%' or rtrim (C.KT_Mask) = ''then 'x' else rtrim (C.KT_Mask) + '%' end
WHERE C.[type] in (2,3) and C.[sign] in (1,2) 
	AND (rtrim (C.DT_Mask) = '' OR C.DT_Mask = '%' OR rtrim (C.DT_Mask) <> '' AND DT.LINK IS NOT NULL and DT.zabalans = C.DT_Z)
	AND (rtrim (C.KT_Mask) = '' OR C.KT_Mask = '%' OR rtrim (C.KT_Mask) <> '' AND KT.LINK IS NOT NULL and KT.zabalans = C.KT_Z)

/*
select S1.CODE, * from @temp_nastr_rest T, S_ACCOUNTS S1 
WHERE S1.LINK = T.LINK_account
*/

--- Счета, которые исключаем для расчета остатков ---
insert @temp_nastr_rest_xor
select C.link, C.Link_Col, Code_Row, Calc_Order, [Sign],
	case
		when DT.link is NULL then KT.link
		else DT.link
	end,
	case
		when DT.link is NULL then kt_ekr
		else dt_ekr
	end,
	[type],
	type_kbk,
	dt_kt
from @temp_nastr1 C
left join dbo.s_accounts DT on DT.Code like case when C.DT_Mask = '%' or rtrim (C.DT_Mask) = '' then 'x' else rtrim (C.DT_Mask) + '%' end
left join dbo.s_accounts KT on	KT.Code like case when C.KT_Mask = '%' or rtrim (C.KT_Mask) = ''then 'x' else rtrim (C.KT_Mask) + '%' end
WHERE C.[type] in (2,3) and C.[sign] = 3 
	AND (rtrim (C.DT_Mask) = '' OR C.DT_Mask = '%' OR rtrim (C.DT_Mask) <> '' AND DT.LINK IS NOT NULL and DT.zabalans = C.DT_Z)
	AND (rtrim (C.KT_Mask) = '' OR C.KT_Mask = '%' OR rtrim (C.KT_Mask) <> '' AND KT.LINK IS NOT NULL and KT.zabalans = C.KT_Z)
--- Удаление лишних корреспонденций ---

----------------------------------------------------------------------
-- РАССЧИТЫВАЕМ
-- CREATE TABLE #tTemp  (KBK varchar(50), Link_Col int, SUMMA FLOAT, Calc_Order int)
---------------- проводки ----------------------------
insert #tTemp (KBK, Link_Col, SUMMA, Calc_Order)
SELECT 
CASE WHEN TMP.Code_Row <> '' THEN TMP.Code_Row
		ELSE
			 dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', TMP.Mask_KBK) = 0 THEN ''
						ELSE LEFT (TMP.Mask_KBK, CHARINDEX ('#', TMP.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(KBK.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6)
--			+ LEFT(ISNULL(REPLACE(CASE TMP.DT_KT when 0 THEN SAD.CODE ELSE SAK.CODE END,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(case dt_kt when 0 then DTS.CODE else KTS.CODE END, '000'), 3) 
			+ LEFT(ISNULL(case dt_kt when 0 then DTE.CODE else KTE.CODE END, '000'), 3), TMP.Mask_KBK)
		END,
	TMP.Link_Col,
	SUM(CASE [SIGN] WHEN 1 THEN G2.SUMMA WHEN 2 THEN -G2.SUMMA  ELSE 0 END), 
--CASE [SIGN] WHEN 1 THEN G2.SUMMA WHEN 2 THEN -G2.SUMMA  ELSE 0 END,
	TMP.Calc_Order

--g.*

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)


LEFT JOIN dbo.G_PROV_AP DT ON (DT.LINK_UP = G2.LINK
	AND DT.DB_KR = 0)
LEFT JOIN dbo.G_PROV_AP KT ON (KT.LINK_UP = G2.LINK
	AND KT.DB_KR = 1)

LEFT JOIN dbo.KOSGU DTS ON (DTS.Link = DT.SGU)
LEFT JOIN dbo.KOSGU DTE ON (DTE.Link = DT.EKR)
LEFT JOIN dbo.KOSGU KTS ON (KTS.Link = KT.SGU)
LEFT JOIN dbo.KOSGU KTE ON (KTE.Link = KT.EKR)

INNER JOIN @TEMP_NASTR TMP ON (TMP.LINK_DT = DT.ACCOUNT OR TMP.LINK_DT IS NULL)
		AND (TMP.LINK_KT = KT.ACCOUNT OR TMP.LINK_KT IS NULL)
	AND (@iForm737 = 0 and dbo.RO_LIKE_LIST(DTS.Code, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '' or @iForm737 = 1)
	AND (@iForm737 = 0 and dbo.RO_LIKE_LIST(KTS.Code, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '' or @iForm737 = 1)
	AND (@iForm737 = 1 and dbo.RO_LIKE_LIST(DTE.Code, TMP.DT_EKR) > 0 OR TMP.DT_EKR = '' or @iForm737 = 0)
	AND (@iForm737 = 1 and dbo.RO_LIKE_LIST(KTE.Code, TMP.KT_EKR) > 0 OR TMP.KT_EKR = '' or @iForm737 = 0)

LEFT JOIN dbo.S_ACCOUNTS SA ON (TMP.DT_KT = 0 AND SA.LINK = DT.ACCOUNT
	OR TMP.DT_KT = 1 AND SA.LINK = KT.ACCOUNT)

LEFT JOIN dbo.KL_KBK KBK ON (TMP.dt_kt = 0 AND KBK.LINK = DT.KBK
		OR TMP.DT_KT = 1 AND KBK.LINK = KT.KBK)
LEFT JOIN @filter_kbk F on KBK.Code LIKE F.kbk + '%' -- добавила Olga 2011.07.19 
WHERE G.DATE_PROV BETWEEN @ldBegin AND @dCALC_DATE
--and tmp.link_col = 57755
	--and tmp.Code_Row = '162'
	AND G.DEP = @iDEP_LINK
	AND (F.kbk IS NOT NULL
		OR isnull(@nabor_filter, '') = '')
	AND (TMP.TYPE_KBK = 0 
		OR (TMP.TYPE_KBK & KBK.[TYPE]) / KBK.[TYPE] = 1)
	AND not exists(select top 1 *
			from @temp_nastr_xor xor
			where xor.link = tmp.link
				and xor.link_dt = dt.account and xor.link_kt = kt.account
				AND (@iForm737 = 0 and dbo.RO_LIKE_LIST(DTS.Code, xor.DT_EKR) > 0 OR xor.DT_EKR = '' or @iForm737 = 1)
				AND (@iForm737 = 0 and dbo.RO_LIKE_LIST(KTS.Code, xor.KT_EKR) > 0 OR xor.KT_EKR = '' or @iForm737 = 1)
				AND (@iForm737 = 1 and dbo.RO_LIKE_LIST(DTE.Code, xor.DT_EKR) > 0 OR xor.DT_EKR = '' or @iForm737 = 0)
				AND (@iForm737 = 1 and dbo.RO_LIKE_LIST(KTE.Code, xor.KT_EKR) > 0 OR xor.KT_EKR = '' or @iForm737 = 0))

GROUP BY CASE WHEN TMP.Code_Row <> '' THEN TMP.Code_Row
		ELSE
			 dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', TMP.Mask_KBK) = 0 THEN ''
						ELSE LEFT (TMP.Mask_KBK, CHARINDEX ('#', TMP.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(KBK.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
--			+ LEFT(ISNULL(REPLACE(CASE TMP.DT_KT when 0 THEN SAD.CODE ELSE SAK.CODE END,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(case dt_kt when 0 then DTS.CODE else KTS.CODE END, '000'), 3) 
			+ LEFT(ISNULL(case dt_kt when 0 then DTE.CODE else KTE.CODE END, '000'), 3), TMP.Mask_KBK)
		END,
	TMP.Link_Col,
	TMP.Calc_Order

----------------- остатки ------------------------------
while exists(select top 1 * from @temp_nastr_rest)
begin
	select top 1 @LC = Link_Col from @temp_nastr_rest

	set @bid = 'calc_col_' + LTRIM(RTRIM(STR(@LC)))

	insert dbo.buffer(ID, Link)
	select @bid, link_account
	from @temp_nastr_rest
	where link_col = @LC

	-- остаток на начало периода
	INSERT #tTemp (KBK, Link_Col, SUMMA, Calc_Order)
	SELECT 
		CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'000'), 3) 
			+ LEFT(ISNULL(E.CODE,'000'), 3), R.Mask_KBK)
		END,
		@LC,
		CASE WHEN (SA.S_PASSIVE = 1 and [sign] = 1) OR (SA.S_ACTIVE = 1 and [sign] = 2) then 1 else - 1 end *
			CASE WHEN R.OPER like '%>0%' and case SA.S_PASSIVE when 1 then sum(k_summa - d_summa) else sum(d_summa - k_summa) end > 0
					or R.OPER like '%<0%' and case SA.S_PASSIVE when 1 then sum(k_summa - d_summa) else sum(d_summa - k_summa) end < 0
					or R.OPER = '' then sum(k_summa - d_summa) else 0 end,
		--sum(CASE WHEN (SA.S_PASSIVE = 1 and [sign] = 1) OR (SA.S_ACTIVE = 1 and [sign] = 2) then 1 else - 1 end *
		--	CASE WHEN R.OPER like '%>0%' and case SA.S_PASSIVE when 1 then k_summa - d_summa else d_summa - k_summa end > 0
		--			or R.OPER like '%<0%' and case SA.S_PASSIVE when 1 then k_summa - d_summa else d_summa - k_summa end < 0
		--			or R.OPER = '' then k_summa - d_summa else 0 end),
		R.Calc_Order
	FROM dbo.ARestTableByDateAccounts(@ldBegin, @bid) A
	INNER JOIN @temp_nastr_rest R on R.link_account = A.account and R.Link_Col = @LC and R.[Type] = 2
	LEFT JOIN dbo.KL_KBK K on K.Link = A.KBK
	--		and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end) > 0)
	LEFT JOIN @filter_kbk F on K.Code LIKE F.kbk + '%' -- добавила Olga 2011.07.19 
	left join dbo.KOSGU S on (S.Link = A.SGU) --and (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
	left join dbo.KOSGU E on E.Link = A.EKR
	left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	where dep_link = @iDEP_LINK
		AND (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
		and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and (dbo.RO_LIKE_LIST(S.Code, R1.ekr) > 0  or R1.ekr = '') and r1.link = r.link)
		AND (R.TYPE_KBK = 0 
			OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		AND (F.kbk IS NOT NULL
			OR isnull(@nabor_filter, '') = '')
	GROUP BY 
		CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'000'), 3) 
			+ LEFT(ISNULL(E.CODE,'000'), 3), R.Mask_KBK)
		END,
		R.Calc_Order,
		R.OPER, SA.S_PASSIVE, SA.S_ACTIVE, [sign],
		dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'000'), 3) 
			+ LEFT(ISNULL(E.CODE,'000'), 3), R.Mask_KBK)

	-- остаток на конец периода
	insert #tTemp(KBK, Link_Col, SUMMA, Calc_Order)
	select 
		CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'000'), 3) 
			+ LEFT(ISNULL(E.CODE,'000'), 3), R.Mask_KBK)
		END,
		@LC,
			CASE WHEN (SA.S_PASSIVE = 1 and [sign] = 1) OR (SA.S_ACTIVE = 1 and [sign] = 2) then 1 else - 1 end *
			CASE WHEN R.OPER like '%>0%' and case SA.S_PASSIVE when 1 then sum(k_summa - d_summa) else sum(d_summa - k_summa) end > 0
					or R.OPER like '%<0%' and case SA.S_PASSIVE when 1 then sum(k_summa - d_summa) else sum(d_summa - k_summa) end < 0
					or R.OPER = '' then sum(k_summa - d_summa) else 0 end,
			--sum(CASE WHEN (SA.S_PASSIVE = 1 and [sign] = 1) OR (SA.S_ACTIVE = 1 and [sign] = 2) then 1 else - 1 end *
			--CASE WHEN R.OPER like '%>0%' and case SA.S_PASSIVE when 1 then k_summa - d_summa else d_summa - k_summa end > 0
			--		or R.OPER like '%<0%' and case SA.S_PASSIVE when 1 then k_summa - d_summa else d_summa - k_summa end < 0
			--		or R.OPER = '' then k_summa - d_summa else 0 end),
		R.Calc_Order
	from dbo.ARestTableByDateAccounts(@ldEnd, @bid) A
	INNER JOIN @temp_nastr_rest R on R.link_account = account and R.Link_Col = @LC and R.[Type] = 3
	LEFT JOIN dbo.KL_KBK K on K.Link = A.KBK
	--		and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end) > 0)
	LEFT JOIN @filter_kbk F on K.Code LIKE F.kbk + '%' -- добавила Olga 2011.07.19  
	left join dbo.KOSGU S on (S.Link = A.SGU) --and (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
	left join dbo.KOSGU E on E.Link = A.EKR
	left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	where dep_link = @iDEP_LINK
		AND (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
			and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and (dbo.RO_LIKE_LIST(S.Code, R1.ekr) > 0  or R1.ekr = '') and r1.link = r.link)
		AND (R.TYPE_KBK = 0 
			OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		AND (F.kbk IS NOT NULL
			OR isnull(@nabor_filter, '') = '')

/*		join @temp_nastr_rest R on R.link_account = account and R.Link_Col = @LC and R.[Type] = 3
		left join dbo.KL_KBK K on K.Link = A.KBK and (R.TYPE_KBK & (case K.[TYPE] when 3 then 4 when 4 then 8 else K.[TYPE] end)>0)
		LEFT JOIN @filter_kbk F on F.kbk = K.Code 
		left join dbo.KOSGU S on (S.Link = A.EKR)  -- and (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
		left join dbo.KOSGU E on E.Link = A.EKR
		left join dbo.S_ACCOUNTS SA on SA.Link = A.ACCOUNT
	where dep_link = @iDEP_LINK
		and not exists(select top 1 * from @temp_nastr_rest_xor R1 where [type] = 2 and R1.link_account = A.account and (dbo.RO_LIKE_LIST(S.Code, R1.ekr) > 0 or R1.ekr =''))
		AND (dbo.RO_LIKE_LIST(S.Code, R.ekr) > 0 or R.ekr = '')
		AND (R.TYPE_KBK = 0 
			OR (R.TYPE_KBK & K.[TYPE]) / K.[TYPE] = 1)
		AND (F.kbk IS NOT NULL
			OR isnull(@nabor_filter, '') = '')
*/	group by 
		CASE
			WHEN R.Code_Row <> '' THEN R.Code_Row
			ELSE
			+ dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'000'), 3)
			+ LEFT(ISNULL(E.CODE,'000'), 3), R.Mask_KBK)
		END,
		/*R.Code_Row, */R.Calc_Order,
		R.OPER, SA.S_PASSIVE, SA.S_ACTIVE, [sign],
		dbo.RA_Mask(CASE 
						WHEN CHARINDEX ('#', R.Mask_KBK) = 0 THEN ''
						ELSE LEFT (R.Mask_KBK, CHARINDEX ('#', R.Mask_KBK))
					END 
			+ LEFT(ISNULL(LTRIM(REPLACE(K.CODE,'.','')),'') + '00000000000000000', 17)
			+ LEFT(ISNULL(REPLACE(SA.CODE,'.',''),'') + '000000', 6) 
			+ LEFT(ISNULL(S.CODE,'000'), 3) 
			+ LEFT(ISNULL(E.CODE,'000'), 3), R.Mask_KBK)

-- select * from #tTemp
	
	delete @temp_nastr_rest where Link_Col = @LC

	exec dbo.BufferClear @bid	
end

 --select * from #tTemp
---------------------------------------------------------------------
-- СОХРАНЯЕМ ДАННЫЕ В ОТЧЕТ
-- динамическая таблица
delete T -- удаляем ячейки с меньшим приоритетом
from #tTemp T
where exists(select top 1 * from #tTemp T1 where T.Link_Col = T1.Link_Col and T.KBK = T1.KBK and T.Calc_Order < T1.Calc_Order)

delete #tTemp where KBK <> @varKScCodeRow and isnull(@varKScCodeRow, '') <> ''
	OR SUMMA = 0

UPDATE #tTemp SET KBK = REPLACE (KBK, '#', '')

if isnull(@varKScCodeRow, '') <> ''
	select @varKSfValue = sum(SUMMA)
	from #tTemp

update dbo.report_dinamics
set float_val = SUMMA
from (select KBK, Link_Col, sum(SUMMA) as SUMMA from #tTemp group by KBK, Link_Col) T join report_coloumns RC on T.Link_Col = RC.Link_Col
	join report_tables RT on RC.Link_Table = RT.Link_Table
where Link_SF = @varKSiLSF and T.Link_Col = report_dinamics.Link_Col and Code_Row = KBK and RT.Val_Type = 1

insert dbo.report_dinamics(Link_SF, Link_Col, Code_Row, Float_Val, Str_Val)
select @varKSiLSF, T.Link_Col, KBK, sum(SUMMA), ''
from #tTemp T join report_coloumns RC on T.Link_Col = RC.Link_Col
	join report_tables RT on RC.Link_Table = RT.Link_Table and RT.Val_Type = 1
where not exists(select top 1 * from dbo.report_dinamics RD where RD.Link_SF = @varKSiLSF and RD.Link_Col = T.Link_Col and RD.Code_Row = T.KBK)
group by T.Link_Col, KBK

-- статическая таблица
update S
set SUMMA = T.SUMMA
-- select *
from dbo.report_summa S
join dbo.i_report_rows RR on S.Link_Row = RR.Link_Row and Link_Saved_Form = @varKSiLSF
join (select KBK, Link_Col, sum(SUMMA) as SUMMA from #tTemp group by KBK, Link_Col) T on T.Link_Col = S.Link_Col and T.KBK = RR.Code

insert dbo.report_summa(Link_Saved_Form, Link_Col, Link_Row, Summa)
select @varKSiLSF, T.Link_Col, RR.Link_Row, sum(SUMMA)
from #tTemp T
join dbo.report_coloumns RC on T.Link_Col = RC.Link_Col
join dbo.i_report_rows RR on RC.Link_Table = RR.Link_Table and T.KBK = RR.Code
where not exists(select top 1 * from dbo.report_summa S where S.Link_Saved_Form = @varKSiLSF and S.Link_Col = T.Link_Col and S.Link_Row = RR.Link_Row)
group by T.Link_Col, RR.Link_Row

-- SELECT * FROM #tTemp where link_col = 57755 order by kbk, link_col



drop table #tTemp

return 0


GO


GRANT EXECUTE ON dbo.[RO_CALC_NASTR] TO PUBLIC

GO


GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


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

CREATE           
PROCEDURE dbo.FB_EXPORT_RR @cBuffId varchar(30) = '', @cObjCode varchar(30) = '' 

AS
  DECLARE @iDepLink	int, 
	  @cUserFio 	varchar(50), 
	  @cUserDol 	varchar(50),
	  @cBuffIdOld	Varchar(30)


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

Select 	@cUserFio = EP.NAME_EMPL ,
   	@cUserDol = ep.post_name
FROM dbo.KU_EMPL_PLACING EP 
WHERE EP.LINK = dbo.GetCurrentEmpl()
if @cObjCode = 'FIN_REESTR_RR_104N'
begin
	set @cBuffIdOld = @cBuffId
	set @cBuffId = 'FB_RR'
	insert into dbo.BUFFER(ID,LINK)
	select @cBuffId, LINK_G_PROV 
	from dbo.FIN_RR 
	where LINK_REESTR in (select LINK from dbo.BufferGetTableByID(@cBuffIdOld))
end
	

-- Таблица 2 (FROM)
SELECT	KOD_TOFK	= '', 
		NAME_TOFK	= '',
		BUDG_LEVEL  = BUDG.CODE_EL,
		KOD_UBP 	= D.CODE_UBP,
		NAME_UBP	= D.FULL_NAME,
		0 as link,
		0 as link_up
from dbo.DEPARTMENTS D 
left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
where D.LINK = @iDepLink

-- Таблица 3 (TO)
SELECT	KOD_TOFK	= TOFK.CODE, 
	NAME_TOFK		= TOFK.FULL_NAME,
	BUDG_LEVEL  	= '',
	KOD_UBP 		= case BUDG.CODE_EL when '1' then D.CODE_UBP else '' end,
	NAME_UBP		= case BUDG.CODE_EL when '1' then D.FULL_NAME else '' end,
	0 as link,
	0 as link_up
from dbo.DEPARTMENTS D 
left join dbo.TREASURY TOFK on D.TOFK_LINK = TOFK.LINK
left join dbo.KL_ADMIN_BS VED WITH (NOLOCK) on VED.LINK = D.VED_LINK
left join dbo.KL_BUDG_TYPE BUDG WITH (NOLOCK) on VED.Link_Budg = BUDG.LINK
where D.LINK = @iDepLink

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

SELECT  LINK 		= RR.LINK,
	LINK_UP		= RR.LINK,
	GUID_FK_R	= '',
	NOM_R_RR	= RR.NUMBER,
	DATE_R_RR	= RR.DATE,
	KOD_UBP		= case when D.BUDG_LEVEL = '1' then D.CODE_UBP else '' end,
	NAME_UBP	= case when D.DEP_TYPE = 1 then D.DEP_FNAME else '' end,
	GLAVA_GRS	= D.GRBS_CODE,
	NAME_GRS	= D.GRBS_NAME,
	LS_UBP		= DA.CODE,
	KOD_TOFK	= D.TOFK_CODE,
	NAME_TOFK	= D.TOFK_NAME,
	NAME_BUD	= D.BUDG_NAME,
	NAME_FO		= D.FO_NAME,
	DOL_RUK		= B.POST_NAME,
	NAME_RUK	= B.SHORT_NAME,
	DOL_ISP		= @cUserDol,
	NAME_ISP	= @cUserFio,
	TEL_ISP		= GB.PHONE,
	DATA_POD_RR	= RR.DATE_POD,
	DATE_BU		= convert(datetime, null),
	DATE_UTV_R_R	= convert(datetime, null),
	DATA_POD_RR_ISP = RR.DATE_POD
FROM (select distinct NUMBER = case when RR.LINK_REESTR is null then '' else GR.NUMBER end, 
			DATE = case when RR.LINK_REESTR is null then NULL else GR.DATE end, 
			DATE_PROV = case when RR.LINK_REESTR is null then G.DATE_PROV else GR.DATE_PROV end, 
			DATE_POD = ISNUlL(G.DATE_PROV,GR.DATE_PROV), 
--			LINK = isnull(GR.LINK,G.LINK),
			G.LINK,
			G.ACC
	from dbo.FIN_RR RR 
	inner join G_PROV G on G.LINK = RR.LINK_G_PROV
	left join G_PROV GR on GR.LINK = RR.LINK_REESTR and @cObjCode = 'FIN_REESTR_RR_104N'
	where RR.LINK_G_PROV in (select LINK from dbo.BufferGetTableByID(@cBuffId))) RR
inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = RR.ACC 
inner join dbo.BB_DEP_ACC_DOP(NULL) D on D.ACC_LINK = DA.LINK
left join dbo.GetOtvFaceData(@iDepLink, 'Руководитель') B on DA.LINK_UP = B.LINK_DEP
left join dbo.GetOtvFaceData(@iDepLink, 'Главный бухгалтер') GB on DA.LINK_UP = GB.LINK_DEP

-- Таблица 5 (APRC)
SELECT  LINK 		= RR.LINK,
	--LINK_UP		= isnull(RR.LINK_REESTR,RR.LINK),
	LINK_UP		= RR.LINK,
	GUID_FK		= '',
	NOM_RR		= RR.NUMBER,
	DATE_FORM_RR	= RR.DATE,
	DATE_UTV_RR	= RR.DATE_PROV,
	RR.VID_RR, 
	KOD_UBP		= case when D.BUDG_LEVEL = '1' then D.CODE_UBP else '' end,
	NAME_UBP	= D.DEP_FNAME,
	LS_UBP		= RR.PACC_CODE,
	KOD_TOFK	= case when D.BUDG_LEVEL = '1' then D.TOFK_CODE else '' end,
	NAME_TOFK	= case when D.BUDG_LEVEL = '1' then D.TOFK_NAME else '' end,
	NOTE_RR		= RR.SPECIAL,
	NOTE_CODE	= RR.SPECIAL_CODE,
	--NOTE_CODE	= '',
	TYPE_KBK	= '10',
	SUM_BA_1Y	= RR.ASSIGN_Y1,
	SUM_BA_2Y	= RR.ASSIGN_Y2,
	SUM_BA_3Y	= RR.ASSIGN_Y3,
	SUM_LBO_1Y	= RR.LIMIT_Y1,
	SUM_LBO_2Y	= RR.LIMIT_Y2,
	SUM_LBO_3Y	= RR.LIMIT_Y3,
	SUM_POF_1Y	= RR.FIN_Y1,
	NOM_PP		= '',
	DATE_PP		= '',
	DATE_UTV_BA	= convert(datetime, null),
	DATE_UTV_LBO	= convert(datetime, null),
	DATE_UTV_POF	= convert(datetime, null)
FROM FIN_RR_104N RR
inner join dbo.BB_DEP_ACC_DOP(NULL) D on D.ACC_LINK = RR.PACC_LINK
where RR.LINK in (select LINK from dbo.BufferGetTableByID(@cBuffId))



-- Таблица 6 (APBASTR)
declare @tBlok table (	LINK		int, 
			LINK_UP		int, 
			KBK		varchar(20),
			ADD_KLASS	varchar(20),
			SUM_Y1		numeric(18,2), 
			SUM_Y2		numeric(18,2), 
			SUM_Y3		numeric(18,2), 
			NOTE_STR	varchar(254),
			TYPE		tinyint, 
			ORDERS		int identity)
insert into @tBlok(LINK, LINK_UP, KBK, ADD_KLASS, SUM_Y1, SUM_Y2, SUM_Y3, NOTE_STR, [TYPE])
SELECT  LINK		= T.LINK_UP,
	LINK_UP		= T.LINK_UP,
	--KBK	 	= REPLACE(rtrim(DV.CODE) + DE.CODE,'.',''),
	--ADD_KLASS	= DCL.CODE,
	KBK	 	= REPLACE(rtrim(DV.CODE),'.','') + case len(REPLACE(rtrim(DV.CODE),'.','')) when 17 then isnull(DE.CODE, '') else '' end,
	ADD_KLASS	= case len(REPLACE(rtrim(DV.CODE),'.','')) when 20 then isnull('(' + DE.CODE + ')', '') else '' end + isnull(DCL.CODE, ''),
	SUM_Y1		= T.SUMMA_Y1,
	SUM_Y2		= T.SUMMA_Y2,
	SUM_Y3		= T.SUMMA_Y3,
	NOTE_STR	= T.COMMENT,
	T.[TYPE]
FROM dbo.FINANSE_RR_TABLE T
LEFT JOIN dbo.BI_DICTION_KBK DV ON DV.LINK = T.KBK
LEFT JOIN dbo.KOSGU DE ON DE.LINK = T.EKR
LEFT JOIN dbo.DOP_CLASSIF DCL ON DCL.LINK = T.DOP_CL
where T.LINK_UP in (select LINK from dbo.BufferGetTableByID(@cBuffId))

update B
set LINK = - link
from @tBlok B
where ORDERS not in (select max(orders) from @tBlok where LINK_UP = B.LINK_UP  AND TYPE = B.TYPE group by LINK_UP, TYPE)

select 	LINK_UP,
	LINK,
	KBK,
	ADD_KLASS,
	SUM_BA_Y1 = SUM_Y1, 
	SUM_BA_Y2 = SUM_Y2,
	SUM_BA_Y3 = SUM_Y3,
	NOTE_BASTR = NOTE_STR
from @tBlok 
where TYPE = 1
order by LINK_UP, orders 

-- Таблица 7 (APLBOSTR)
select 	LINK_UP,
	LINK,
	KBK,
	ADD_KLASS,
	SUM_LBO_Y1 = SUM_Y1, 
	SUM_LBO_Y2 = SUM_Y2,
	SUM_LBO_Y3 = SUM_Y3,
	NOTE_LBOSTR = NOTE_STR
from @tBlok 
where TYPE = 2
order by LINK_UP, orders 

-- Таблица 8 (APPOFSTR)
select 	LINK_UP,
	LINK,
	KBK,
	ADD_KLASS,
	SUM_POF_Y1 = SUM_Y1, 
	NOTE_POFSTR = NOTE_STR
from @tBlok 
where TYPE = 3
order by LINK_UP, orders 

if @cObjCode = 'FIN_REESTR_RR_104N'
	exec dbo.BufferClear @cBuffId



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on dbo.FB_EXPORT_RR to public
GO


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

GO

CREATE   PROCEDURE dbo.SZV4_PACHKA_PROVERKA (@result int output, @link int, @mode tinyint)
AS

if @mode = 0 
BEGIN
	Select @result = proverka from dbo.SZV4_PACHKA where link = @link
	RETURN 0
END

if @mode = 1
BEGIN
	set @result = 0

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output

	DECLARE @varKSNOM_PF VARCHAR(20), @varKSname VARCHAR(254), @varKSDEP int,
		@varKSOKPO VARCHAR(40), @varKSINN VARCHAR(12), @varKSKPP VARCHAR(9)--, @varKSRESULT INT

	SELECT 
		@varKSDEP = D.link, @varKSNOM_PF = PFNUMBER, @varKSname = UPPER([NAME]),
		@varKSOKPO = OKPO, @varKSINN = INN, @varKSKPP = KPP
	FROM DICTIONARY_DEPARTMENT D 
	WHERE D.link = @DEP_LINK

	declare @year_begin int
	set @year_begin = (SELECT year_begin FROM dbo.SZV4_PACHKA WHERE LINK = @link)

--	EXEC SD_CHECK_INN @varKSINN, @varKSRESULT OUTPUT, 0

	SELECT pachka = 0, orders = 0, msg = 'Собственные реквизиты организации: ' + 
	(case when LEN(RTRIM(LTRIM(COALESCE(@varKSKPP,'')))) = 0 THEN 'Не указан КПП организации;' else '' end)
	WHERE LEN(RTRIM(LTRIM(COALESCE(@varKSKPP,'')))) = 0 
	UNION
	SELECT pachka = 0, orders = 0, msg = 'Собственные реквизиты организации: ' + 
	(case when LEN(RTRIM(LTRIM(COALESCE(@varKSOKPO,'')))) = 0 THEN 'Не указан ОКПО организации;' else '' end)
	WHERE LEN(RTRIM(LTRIM(COALESCE(@varKSOKPO,'')))) = 0 
	UNION
	SELECT pachka = 0, orders = 0, msg = 'Собственные реквизиты организации: ' + 
	(case when LEN(RTRIM(LTRIM(COALESCE(@varKSINN,'')))) = 0 THEN 'Не указан ИНН организации;' 
		else (case when LEN(RTRIM(LTRIM(COALESCE(@varKSINN,'')))) < 10  then 'Не верный ИНН организации ' + RTRIM(LTRIM(COALESCE(@varKSINN,''))) else '' end) end)
	WHERE LEN(RTRIM(LTRIM(COALESCE(@varKSINN,'')))) < 10  --or @varKSRESULT = -1
	UNION
	SELECT pachka = 0, orders = 0, msg = 'Собственные реквизиты организации: ' + 
	(case when LEN(RTRIM(LTRIM(COALESCE(@varKSNOM_PF,'')))) = 0 THEN 'Не указан номер регистрации организации в ПФР;' 
		else (case when LEN(RTRIM(LTRIM(COALESCE(@varKSNOM_PF,'')))) <> 14 then 'Не верный номер регистрации организации в ПФР ' + RTRIM(LTRIM(COALESCE(@varKSNOM_PF,''))) else '' end) end)
	WHERE LEN(RTRIM(LTRIM(COALESCE(@varKSNOM_PF,'')))) <> 14
	UNION
	Select pachka, orders, msg = 'Пачка ' + convert(varchar(10),pachka) + ' стр. ' + convert(varchar(10),orders) + ' не указан(ы) атрибут(ы):' + 
		(case when coalesce(FM,'') = '' then ' Фамилия;' else '' end) + 
		(case when coalesce(IM,'') = '' then ' Имя;' else '' end) + 
		--(case when coalesce(OT,'') = '' then ' Отчество;' else '' end) + 
		(case when coalesce(PF_NUM,'') = '' then ' Страховой номер ПФ;' else '' end) + 
		(case when len(coalesce(ADDRESS2,'')) <= 9 then ' Адрес' else '' end)
	from dbo.sa_szv4_svedenia
	where	
		link = @link
		and (
		coalesce(FM,'') = ''
		or coalesce(IM,'') = ''
		--or coalesce(OT,'') = ''
		or coalesce(PF_NUM,'') = ''
		or len(coalesce(ADDRESS2,'')) <= 9
		)
	UNION
	Select pachka, orders, msg = 'Пачка ' + convert(varchar(10),pachka) + ' стр. ' + convert(varchar(10),orders) + ' Ошибка:' + 
		+ (case when coalesce(dper_vn_m,0)>12 or coalesce(dper_oz_m,0)>12 then ' Кол-во месяцев не может быть больше 12;' else '' end)
		+ (case when coalesce(dper_vn_d,0)>=30 or coalesce(dper_oz_d,0)>=30 then ' Кол-во дней должно быть меньше 30;' else '' end)
		+ (case when (coalesce(dper_vn_m,0) + coalesce(dper_vn_d,0) / 30 + coalesce(dper_oz_m,0) + coalesce(dper_oz_d,0) / 30) > 12 then 
				' Сумма периодов по врем. нетрудосп. и отпуска без сохранения З/П не должна превышать 12 мес.;' else '' end)	

	from dbo.sa_szv4_svedenia
	where	
		link = @link
		and (
		coalesce(dper_vn_m,0)>12
		or coalesce(dper_vn_d,0)>=30
		or coalesce(dper_oz_m,0)>12
		or coalesce(dper_oz_d,0)>=30
		or (coalesce(dper_vn_m,0) + coalesce(dper_vn_d,0)/30 + coalesce(dper_oz_m,0) + coalesce(dper_oz_d,0)/30) > 12
		)

	UNION
	Select pachka, orders, msg = 'Пачка ' + convert(varchar(10),pachka) + ' стр. ' + convert(varchar(10),orders) + ' Ошибка:' + 
		+ ' Пересекающиеся периоды в стаже!'
	from dbo.sa_szv4_svedenia SV
	where	
		link = @link
		and exists (select * from dbo.SZV4_stazh S1 inner join dbo.SZV4_stazh S2 on S1.link_up = S2.link_up and  S1.link <> S2.link
		where S1.link_up = SV.link1 and (S1.date1 between S2.date1 and S2.date2 or S1.date2 between S2.date1 and S2.date2)) 
	UNION
	Select pachka = 0, orders = 0, msg = 'АДВ-11 Ошибка:' + 
		+ 'Задолженность на начало перирда за ' + convert(varchar(4),@year_begin-1) + ' может быть только положительной!'
	where
		(select sum(sum_str) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) < 0
		or
		(select sum(sum_nak) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) < 0
		or
		(select sum(sum_dop) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) < 0
	UNION
	Select pachka = 0, orders = 0, msg = 'АДВ-11 Ошибка:' + 
		+ 'Задолженность на начало перирда за ' + convert(varchar(4),@year_begin) + ' может быть только отрицательной!'
	where
		(select sum(sum_str) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin) > 0
		or
		(select sum(sum_nak) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin) > 0
		or
		(select sum(sum_dop) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin) > 0
	UNION
	Select pachka = 0, orders = 0, msg = 'АДВ-11 Ошибка:' + 
		+ 'Уплата за период ' + convert(varchar(4),@year_begin-1) + ' страховых взносов должна быть равной задолженности за этот период!'
	where
		(select sum(sum_str) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) <
					(select sum(sum_str) from dbo.SA_SZV4_PLAT where link = @link)
		AND
		(select sum(sum_str) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) >
					(select sum(sum_str) from dbo.SA_SZV4_PLAT where link = @link and [year] = @year_begin-1)
	UNION
	Select pachka = 0, orders = 0, msg = 'АДВ-11 Ошибка:' + 
		+ 'Уплата за период ' + convert(varchar(4),@year_begin-1) + ' накопительных взносов должна быть равной задолженности за этот период!'
	where
		(select sum(sum_nak) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) <
					(select sum(sum_nak) from dbo.SA_SZV4_PLAT where link = @link)
		AND
		(select sum(sum_nak) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) >
					(select sum(sum_nak) from dbo.SA_SZV4_PLAT where link = @link and [year] = @year_begin-1)
	UNION
	Select pachka = 0, orders = 0, msg = 'АДВ-11 Ошибка:' + 
		+ 'Уплата за период ' + convert(varchar(4),@year_begin-1) + ' взносов по доп.тарифу должна быть равной задолженности за этот период!'
	where
		(select sum(sum_dop) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) <
					(select sum(sum_dop) from dbo.SA_SZV4_PLAT where link = @link)
		AND
		(select sum(sum_dop) from dbo.SA_SZV4_DOLGI where link = @link and [year] = @year_begin-1) >
					(select sum(sum_dop) from dbo.SA_SZV4_PLAT where link = @link and [year] = @year_begin-1)
	UNION 
		/* не должно быть физлиц, по которым в данном периоде нет сумм и сведений о стаже */	
	Select pachka, orders, msg = 'Пачка ' + convert(varchar(10),pachka) + ' стр. ' + convert(varchar(10),orders) + ' , но могут появиться перечисленные суммы после распределения. Если после операции распределения у этого сотрудника не появятся перечисленные суммы, то удалите его из списка.'
	from dbo.sa_szv4_svedenia S inner join  dbo.szv4_pachka p on p.link = s.link
	WHERE s.link = @LINK AND s.sum_doh = 0 AND s.INSUR = 0 AND s.GAIN = 0 AND s.DOP = 0 and s.sum_uplata_dolga_str = 0 and s.sum_uplata_dolga_nak = 0 AND S.INCOME_M1 = 0
	and p.vid_kor != 3
	AND NOT EXISTS (SELECT * FROM dbo.SZV4_STAZH ST WHERE ST.LINK_UP = S.LINK1)
	Order by pachka, orders

	if @@ROWCOUNT = 0 
	BEGIN
		exec dbo.SZV4_NUMERATOR @link
		update dbo.szv4_pachka set proverka = 1 where link = @link
		set @result = 1
	END		


END

RETURN 0





GO


GRANT EXECUTE ON dbo.[SZV4_PACHKA_PROVERKA] TO PUBLIC

GO



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

GO
CREATE PROCEDURE dbo.XK_GET_NASTR_REPORT
	@strTABLE_DOC_NASTR	VARCHAR (100)	= '',	-- Таблица с дополнительными настройками --
	@intDEL_TABLE_DOC_NASTR	TINYINT	=	0	-- Удаление таблицы с дополнительными настройками --
AS
BEGIN
	--- Таблица настроек ---
	CREATE TABLE #TABLE_NASTR (NASTR VARCHAR (20), VALUE VARCHAR (1000))

	DECLARE @strLONGNAME	VARCHAR (254),
		@strORGNAME	VARCHAR (254),
		@strGLBUH	VARCHAR (254),
		@strGLBUH_POST	VARCHAR (254),
		@strCHIEF	VARCHAR (254),
		@strCHIEF_POST	VARCHAR (254),
		@strKASSIR	VARCHAR (254),
		@strKASSIR_POST	VARCHAR (254),
		@strRKADR	VARCHAR (254),
		@strOKPO	VARCHAR (40),
		@strSONO	VARCHAR (20),
		@strREGION	VARCHAR (254),
		@strUSER_POST	VARCHAR (254),
		@strCURR_USER	VARCHAR (254),
		@strPPP_CODE	VARCHAR (254),
		@strPPP_NAME	VARCHAR (254),
		@strOKVED	VARCHAR (20),
		@strOKVED1	VARCHAR (20),
		@strDEP_ADR	VARCHAR (254),
		@strUSER_PHONE	VARCHAR (20),
		@strWORK_DATE	VARCHAR (10),
		@strHEAD	VARCHAR (254),
		@strTOWN	VARCHAR (254),
		@strEXEC	VARCHAR (1000),
		@strPRN_DEP_NAME	CHAR (1)

	SELECT @strLONGNAME = LONGNAME,
		@strORGNAME = ORGNAME,
		@strGLBUH = GLBUH,
		@strGLBUH_POST = rtrim(GLBUH_POST),
		@strCHIEF = CHIEF,
		@strCHIEF_POST = CHIEF_POST,
		@strKASSIR = KASSIR,
		@strKASSIR_POST = KASS_POST,
		@strRKADR = RKADR,
		@strOKPO = OKPO, 
		@strSONO = SONO, 
		@strREGION = REGION,
		@strUSER_POST = USER_POST,
		@strCURR_USER = CURR_USER,
		@strPPP_CODE = PPP_CODE,
		@strPPP_NAME = PPP_NAME,
		@strOKVED = OKVED,
		@strOKVED1 = OKVED1,
		@strDEP_ADR = DEP_ADR,
		@strUSER_PHONE = USER_PHONE
	FROM dbo.PrintDoc_GetDepData()

	INSERT INTO #TABLE_NASTR VALUES('LONGNAME_OUR', ISNULL(LTRIM(@strLONGNAME), ''))
	INSERT INTO #TABLE_NASTR VALUES('ORGNAME_OUR', ISNULL(LTRIM(@strORGNAME), ''))
	INSERT INTO #TABLE_NASTR VALUES('GLBUH_OUR', ISNULL(LTRIM(@strGLBUH), ''))
	INSERT INTO #TABLE_NASTR VALUES('GLBUH_POST_OUR', ISNULL(LTRIM(@strGLBUH_POST), ''))
	INSERT INTO #TABLE_NASTR VALUES('chief_OUR', ISNULL(LTRIM(@strCHIEF), ''))
	INSERT INTO #TABLE_NASTR VALUES('CHIEF_POST_OUR', ISNULL(LTRIM(@strCHIEF_POST), ''))
	INSERT INTO #TABLE_NASTR VALUES('KASSIR_OUR', ISNULL(LTRIM(@strKASSIR), ''))
	INSERT INTO #TABLE_NASTR VALUES('KASSIR_POST_OUR', ISNULL(LTRIM(@strKASSIR_POST), ''))
	INSERT INTO #TABLE_NASTR VALUES('KADR_OUR', ISNULL(LTRIM(@strRKADR), ''))
	INSERT INTO #TABLE_NASTR VALUES('OKPO_OUR', '#' + ISNULL(LTRIM(@strOKPO), ''))
	INSERT INTO #TABLE_NASTR VALUES('SONO_OUR', '#' + ISNULL(LTRIM(@strSONO), ''))
	INSERT INTO #TABLE_NASTR VALUES('OUR_ADR', ISNULL(RTRIM(@strDEP_ADR), ''))
	INSERT INTO #TABLE_NASTR VALUES('REM_SONO', ISNULL(LTRIM(@strSONO), ''))

	INSERT INTO #TABLE_NASTR VALUES('REGION_OUR', ISNULL(LTRIM(@strREGION), ''))
	INSERT INTO #TABLE_NASTR VALUES('USER_POST', ISNULL(LTRIM(@strUSER_POST), ''))
	INSERT INTO #TABLE_NASTR VALUES('CURR_USER', ISNULL(LTRIM(@strCURR_USER), ''))
	INSERT INTO #TABLE_NASTR VALUES('USER_PHONE', ISNULL(LTRIM(@strUSER_PHONE), ''))


	INSERT INTO #TABLE_NASTR VALUES('PPP_CODE', ISNULL(LTRIM(@strPPP_CODE), ''))
	INSERT INTO #TABLE_NASTR VALUES('PPP_CODE1', '#' + ISNULL(LTRIM(@strPPP_CODE), ''))
	INSERT INTO #TABLE_NASTR VALUES('PPP_NAME', ISNULL(LTRIM(@strPPP_NAME), ''))
	
	INSERT INTO #TABLE_NASTR VALUES('OKVED', ISNULL(LTRIM(@strOKVED), ''))
	INSERT INTO #TABLE_NASTR VALUES('OKVED1', ISNULL(LTRIM(@strOKVED1), ''))


	SET @strPRN_DEP_NAME = CONVERT (VARCHAR (1),
				ISNULL (dbo.XK_GET_NASTR_INT ('NASTR_PRINT_FULL_DEP_NAME'), 0))

	INSERT INTO #TABLE_NASTR VALUES('NASTR_PRN_DEP_NAME', @strPRN_DEP_NAME)

	SELECT @strWORK_DATE = CONVERT (VARCHAR (10), WORKDATE, 104)
	FROM dbo.USER_INFO

	INSERT INTO #TABLE_NASTR VALUES('PERIOD_WORK', ISNULL(LTRIM(@strWORK_DATE), ''))

	SELECT @strHEAD	= ORD_HEAD,
		@strTOWN = TOWN
	FROM dbo.GET_KADR_ORDER_HEADER_DATA()

	INSERT INTO #TABLE_NASTR VALUES('HEAD', ISNULL(LTRIM(@strHEAD), ''))
	INSERT INTO #TABLE_NASTR VALUES('TOWN', ISNULL(LTRIM(@strTOWN), ''))

--- dbo.XK_GET_NASTR_REPORT
	--- Добавлем доп. настройки ---
	IF LEN (ISNULL (@strTABLE_DOC_NASTR, '')) > 0
		IF OBJECT_ID ('TEMPDB..' + @strTABLE_DOC_NASTR) IS NOT NULL
		BEGIN
--			SET @strEXEC = 'INSERT INTO #TABLE_NASTR SELECT NASTR, VALUE FROM ' + @strTABLE_DOC_NASTR
			EXECUTE ('INSERT INTO #TABLE_NASTR SELECT NASTR, VALUE FROM ' + @strTABLE_DOC_NASTR)

			IF @intDEL_TABLE_DOC_NASTR = 1
				EXECUTE ('DROP TABLE ' + @strTABLE_DOC_NASTR)
		END

	--- Вывод результата ---
	SELECT * FROM #TABLE_NASTR

	DROP TABLE #TABLE_NASTR
END


GO


GRANT EXECUTE ON dbo.[XK_GET_NASTR_REPORT] TO PUBLIC

GO


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

GO




CREATE PROCEDURE dbo.FB_HEAD_PRINT @iDocLink	int

as
declare @tCNastr table(NASTR varchar(20),VALUE varchar(1000))
declare @cDepName	varchar(254),
		@cDepOKPO	varchar(20),
		@cDepINN	varchar(12),
		@cDepKPP	varchar(9),
		@cDepOKTMO  VARCHAR(11),
		@cAccCode	varchar(20), 
		@iRBSLink	int,
		@cVedName	varchar(254),
		@cTitleDoc	varchar(1000),
		@cBudg		varchar(100),
		@iUm		int,
		@iF2		int,
		@iLim		int,
		@iCh		int,
		@iSvod		int,
		@iYear		int,
		@iFinLimPer	int,
		@iFinLimType	int,
		@iFinAssignPer	int,
		@cRBSName	varchar(254),
		@cRBSOKPO	varchar(20),
		@cRBSINN	varchar(12),
		@cRBSKPP	varchar(9),
		@cOsnov		varchar(1000),
		@cTitleCOL	varchar(35)
	
	
-- Настройки
EXEC dbo.X_ADMIN_GET_FINANSE_MODE 'FIN_LIM_PER', @iFinLimPer
EXEC dbo.X_ADMIN_GET_FINANSE_MODE 'FIN_LIM_TYPE', @iFinLimType
EXEC dbo.X_ADMIN_GET_FINANSE_MODE 'FIN_SMETA_PER', @iFinAssignPer
	

-- Линк Владельца документа
select @iRBSLink = DEP 
from dbo.G_PROV
where LINK = @iDocLink

-- Получатель документа
select @cDepName = isnull(DD.FULL_NAME,''), @cDepOKPO = isnull(DD.OKPO,''), @cDepINN = isnull(DD.INN,''), @cDepKPP = isnull(DD.KPP,''), @cDepOKTMO = isnull(DD.OKTMO,''), 
	   @cVedName = isnull(VED_NAME,''), @cAccCode = isnull(DA.CODE,'')
from dbo.FINANSE_HEAD FH
inner join dbo.DEPARTMENT_ACCOUNTS DA on DA.LINK = FH.ACCOUNT  
inner join dbo.DICTIONARY_DEPARTMENT DD on DD.LINK = DA.LINK_UP  
where FH.LINK = @iDocLink

-- Если владелец распорядитель , то его в поле распорядитель, иначе вышестоящую организацию
if dbo.FB_GetDepIS_RBS(@iRBSLink, 0) > 1
	select  @cRBSName = isnull(FULL_NAME,''),
			@cRBSOKPO = isnull(OKPO,''),
			@cRBSINN = isnull(INN,''),
			@cRBSKPP = isnull(KPP,'')
	from dbo.DICTIONARY_DEPARTMENT DD
	where LINK = @iRBSLink	
else
	select @cRBSName = isnull(HIGH_NAME,''),
		   @cRBSOKPO = isnull(OKPO,''),
		   @cRBSINN = isnull(INN,''),
		   @cRBSKPP = isnull(KPP,'')
	from dbo.DICTIONARY_DEPARTMENT DD
	where LINK = @iRBSLink  
if @cRBSName is null
	set @cRBSName = ''
if @cRBSOKPO is null
	set @cRBSOKPO = ''
if @cRBSINN is null
	set @cRBSINN = ''
if @cRBSKPP is null
	set @cRBSKPP = ''
	

insert into @tCNastr(NASTR,VALUE)
select 'RBS_NAME', @cRBSName  

insert into @tCNastr(NASTR,VALUE)
select 'RBS_OKPO', @cRBSOKPO  

insert into @tCNastr(NASTR,VALUE)
select 'RBS_INN', @cRBSINN  

insert into @tCNastr(NASTR,VALUE)
select 'RBS_KPP', @cRBSKPP  

insert into @tCNastr(NASTR,VALUE)
values ('ORGNAME',@cDepName)  

insert into @tCNastr(NASTR,VALUE)
values ('ORGOKPO',@cDepOKPO)  

insert into @tCNastr(NASTR,VALUE)
values ('ORGINN',@cDepINN)  

insert into @tCNastr(NASTR,VALUE)
values ('ORGKPP',@cDepKPP)  

insert into @tCNastr(NASTR,VALUE)
values ('ORGOKTMO',@cDepOKTMO)  

insert into @tCNastr(NASTR,VALUE)
values ('ORGACC','#' + @cAccCode)  

insert into @tCNastr(NASTR,VALUE)
values ('VED_OUR',@cVedName)  

-- Номер и дату
insert into @tCNastr(NASTR,VALUE)
select 'DOC_NUM', '#' + rtrim(NUMBER) 
from dbo.G_PROV
where LINK = @iDocLink

insert into @tCNastr(NASTR,VALUE)
select 'DOC_NUM1', rtrim(NUMBER) 
from dbo.G_PROV
where LINK = @iDocLink

insert into @tCNastr(NASTR,VALUE)
select 'DOC_DATE', convert(varchar(30),DATE,104) 
from dbo.G_PROV
where LINK = @iDocLink


-- Тип бюджета
select top 1 @cBudg = isnull(rtrim(BT.NAME),'')
from  KL_BUDG_TYPE BT
inner join KL_ADMIN_BS ADM on BT.LINK = ADM.LINK_BUDG
inner join dbo.KL_KBK KBK on KBK.LINK_ADM = ADM.Link  
inner join dbo.FINANSE F on F.VKR = KBK.LINK and F.LINK_UP = @iDocLink

insert into @tCNastr(NASTR,VALUE)
values ('BUDG',@cBudg)  

-- Название документа
select @cTitleDoc = case when (SO.CODE = 'FINANS_LIMIT'  or SO.CODE = 'FINANS_LIMIT_SVOD')  and ISNULL((FH.PARAM & 0x1) ,1) = 0 then 'о ЛИМИТАХ БЮДЖЕТНЫХ ОБЯЗАТЕЛЬСТВ '
			 when (SO.CODE = 'FINANS_ASSIGN' or SO.CODE = 'FINANS_ASSIGN_SVOD') and ISNULL((FH.PARAM & 0x1) ,1) = 0 then 'о БЮДЖЕТНЫХ АССИГНОВАНИЯХ '
			 when (SO.CODE = 'FINANS_LIMIT'  or SO.CODE = 'FINANS_LIMIT_SVOD')  and ISNULL((FH.PARAM & 0x1) ,1) = 1 then 'об изменении ЛИМИТОВ БЮДЖЕТНЫХ ОБЯЗАТЕЛЬСТВ '
			 when (SO.CODE = 'FINANS_ASSIGN' or SO.CODE = 'FINANS_ASSIGN_SVOD') and ISNULL((FH.PARAM & 0x1) ,1) = 1 then 'об изменении БЮДЖЕТНЫХ АССИГНОВАНИЙ '
			 when  SO.CODE = 'FB_SMETA_VNEB' then ''
			 when  SO.CODE = 'FB_PLAN_FHD' then ''
			 when  SO.CODE = 'FB_RESULT_FINANS' and ISNULL((FH.PARAM & 0x1) ,1) = 0 then 'о ФАКТИЧЕСКОМ ФИНАНСИРОВАНИЕ '
			 when  SO.CODE = 'FB_RESULT_FINANS' and ISNULL((FH.PARAM & 0x1) ,1) = 1 then 'об изменении ФАКТИЧЕСКОГО ФИНАНСИРОВАНИЯ ' end + ' на ' +
	    	 case when (SO.CODE = 'FINANS_LIMIT' or SO.CODE = 'FINANS_LIMIT_SVOD' or  SO.CODE = 'FB_SMETA_VNEB') and (@iFinLimPer = 1 or @iFinLimType = 0) or
				(SO.CODE = 'FINANS_ASSIGN' or SO.CODE = 'FINANS_ASSIGN_SVOD') and @iFinAssignPer = 1 or FH.PER_NUM = 0
				then cast(FH.FYEAR as CHAR(4)) + ' год' 
			 else (select PERIOD from PERIODS where ORD = FH.PER_NUM) + ' ' + cast(FH.FYEAR as CHAR(4)) + ' года' end + 
		    isnull(' (' + @cBudg + ')',''),
		    @iCh = ISNULL((FH.PARAM & 0x1) ,1),
			@iLim = case when (SO.CODE = 'FINANS_LIMIT'  or SO.CODE = 'FINANS_LIMIT_SVOD') then 1 else 0 end,
			@iSvod = case when (SO.CODE = 'FINANS_ASSIGN_SVOD'  or SO.CODE = 'FINANS_LIMIT_SVOD') then 1 else 0 end,
			@iF2 = ISNULL((PARAM & 0x8),0) / 8,
			@iYear = FH.FYEAR,
			@cTitleCOL	= case when (SO.CODE = 'FINANS_LIMIT'  or SO.CODE = 'FINANS_LIMIT_SVOD')  then 'Лимиты бюджетных обязательств'
							   when (SO.CODE = 'FINANS_ASSIGN' or SO.CODE = 'FINANS_ASSIGN_SVOD') then 'Бюджетные ассигнования'
						END 
from S_OBJECTS SO
inner join dbo.G_PROV GP on GP.OBJECT = SO.LINK
inner join dbo.FINANSE_HEAD FH on FH.LINK = GP.LINK and FH.LINK = @iDocLink


insert into @tCNastr(NASTR,VALUE)
values ('TITLE_DOC',@cTitleDoc)  

insert into @tCNastr(NASTR,VALUE)
select 'YEAR', isnull(@iYear,1)

insert into @tCNastr(NASTR,VALUE)
select 'F_2', isnull(@iF2,1)

insert into @tCNastr(NASTR,VALUE)
select 'LIM', isnull(@iLim,1)

insert into @tCNastr(NASTR,VALUE)
select 'CH', isnull(@iCh,1)

insert into @tCNastr(NASTR,VALUE)
select 'SVOD', isnull(@iSvod,1)

insert into @tCNastr(NASTR,VALUE)
values ('TITLE_COL', ISNULL (@cTitleCOL, ''))  
-- Единицы измерения
exec dbo.X_GET_OPTION 'FINANS_LIMIT_OPTIONS_UM', 0, @iUm

insert into @tCNastr(NASTR,VALUE)
select 'UM', isnull(@iUm,1)



select @cOsnov = cast(rtrim(O.COMMENT) as varchar(254)) + ' № ' + rtrim(O.NUMBER) + ' от ' + convert(varchar(20),O.[DATE],104)
from dbo.BD_OSNOV O
inner join dbo.FINANSE_HEAD FH ON FH.LINK_OSNOV = O.LINK and FH.LINK = @iDocLink
set @cOsnov = isnull(@cOsnov,'')

insert into @tCNastr(NASTR,VALUE)
values('OSNOV', @cOsnov)



select * from @tCNastr

RETURN 1





GO


GRANT EXECUTE ON dbo.[FB_HEAD_PRINT] TO PUBLIC

GO



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

GO
CREATE PROCEDURE dbo.BK_AVANCE_ACCEPT_GET_REST206
	@intDEP_LINK	INT,
	@dDOC_DATE DATETIME,
	@intSUP_DEP INT
AS
BEGIN
	DECLARE @intACCT_206	INT,
		@DATE_CALC	DATETIME
	
	SELECT @intACCT_206 = LINK
	FROM dbo.S_ACCOUNTS
	WHERE CODE = '206'
	
	SET @DATE_CALC = '20111201'
	
	SET @DATE_CALC = DATEADD (DAY, 1, @DATE_CALC)
	
	DECLARE @TABLE_REST TABLE (ACCOUNT INT,
		DEP INT,
		DEP_LINK INT,
		KBK INT,
		EKR INT,
		DOP INT,
		SUMMA NUMERIC (28,4))

	INSERT INTO @TABLE_REST
	SELECT ACCOUNT,
		DEP,
		DEP_LINK,
		KBK,
		EKR,
		AP2,
		SUM (D_SUMMA)
	FROM dbo.ARestTableByDate (@DATE_CALC, @intACCT_206)
	WHERE DEP_LINK = @intDEP_LINK
		AND DEP = @intSUP_DEP
		AND AP1 IS NULL
	GROUP BY ACCOUNT,
		DEP,
		DEP_LINK,
		KBK,
		EKR,
		AP2

	DECLARE @TABLE_RES TABLE (KBK INT,
		EKR INT,
		DOP INT,
		KBK_CODE VARCHAR (30),
		KBK_NAME VARCHAR (254),
		EKR_CODE VARCHAR (3),
		EKR_NAME VARCHAR (254),
		DOP_CODE VARCHAR (20),
		DOP_NAME VARCHAR (254),
		SUMMA NUMERIC (28,4),
		DT INT,
		KT INT,
		DT_CODE VARCHAR (20),
		KT_CODE VARCHAR (20))

	INSERT INTO @TABLE_RES 
	SELECT TR.KBK,
		TR.EKR,
		TR.DOP,
		KBK.CODE,
		KBK.[NAME],
		EKR.CODE,
		EKR.[NAME],
		DOP.CODE,
		DOP.[NAME],
		TR.SUMMA,
		SA_DT.LINK,
		TR.ACCOUNT,
		SA_DT.CODE,
		SA_R.CODE
	FROM @TABLE_REST TR
	INNER JOIN dbo.S_ACCOUNTS SA_R ON (SA_R.LINK = TR.ACCOUNT)
	LEFT JOIN dbo.KL_KBK KBK ON (KBK.LINK = TR.KBK)
	LEFT JOIN dbo.KOSGU EKR ON (EKR.LINK = TR.EKR)
	LEFT JOIN dbo.DOP_CLASSIF DOP ON (DOP.LINK = TR.DOP)

	LEFT JOIN dbo.S_ACCOUNTS SA_DT ON (SA_DT.LINK = dbo.BK_GetDBKTAccount (SA_R.LINK, '302', DEFAULT, DEFAULT))

	SELECT * FROM @TABLE_RES --ORDER BY 
END


GO


GRANT EXECUTE ON dbo.[BK_AVANCE_ACCEPT_GET_REST206] TO PUBLIC

GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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





/*
© Кейсистемс (Keysystems), 2015
Выгрузки Лимитов БО и Ассигнований 
*/




CREATE          PROCEDURE dbo.FB_EXPORT_BR_15
		@cBuffId	varchar(30) = '',
		@cObjCode	varchar(30) = ''
AS
DECLARE @iDepLink	int,
	@iPeriod	tinyint,
	@iPeriodType	tinyint


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


-- Блок FROM
SELECT	budg 	as KOD_BP, 
		name 	as NM_BP, 
		0 as link,
		0 as link_up
FROM DICTIONARY_DEPARTMENT 
WHERE  link = @iDepLink

-- Блок TO
SELECT '' as KOD_BP,
		'' as NM_BP,
		0 as link,
		0 as link_up
FROM dbo.DICTIONARY_DEPARTMENT 
WHERE  link = @iDepLink
	

if @cObjCode like '%LIMIT%'
	select  @iPeriod = MAX(FIN_LIM_PER) - 1, @iPeriodType = MAX(FIN_LIM_TYPE) from workmode 
else
begin	
	select  @iPeriod = FIN_SMETA_PER - 1 from workmode
	set @iPeriodType = 0
end

-- Блок RL

select 	PERIOD		= case @iPeriod when 2 then 'M' when 1 then 'Q' else 'Y' end,
	TYPE_RL 	= convert(varchar(1),case  when F.F2=1 then 2 else F.CHANGE end),
	VID_RL		= case  when F.SVOD = 1 then '0' else '1' end,
	NUMBER		= F.NUMBER,
	DATE		= F.DATE,
	DATE_EXEC	= F.DATE_PROV,
	KOD_RBS		= F.DEP_CODE,
	NAME_RBS	= F.DEP_NAME,
	ACC_NUM		= F.BUDG_ACC,
	ACC_SEND	= F.ACC_CODE,
	KOD_BP		= case F.SVOD when 0 then F.FDEP_CODE else '' end,
	NAME_BP		= case F.SVOD when 0 then F.FDEP_NAME else '' end,
	ACC_RCP		= case F.SVOD when 0 then F.FACC_CODE else '' end,
	ACC_SEND_KIND = '',
	ACC_RCP_KIND = '',
	IST		= '',
	S.SUM_YEAR01,
	S.SUM_YEAR02,
	S.SUM_YEAR03,
	PRIM		= '',
	VID_IZM		= '',
	NAME_BUD	= D.BUDG_NAME,
	DOP_UKAZ	= '',
	DATE_SIGN	= null,
	BOSS_DOL	= '',
	BOSS		= '',
	ISP_DOL		= '',
	ISP_FIO		= '',
	ISP_PHONE	= '',
	CORRECTION	= '',
	ANALITICS	= '',
	LINK		= F.LINK,
	LINK_UP		= F.LINK

from dbo.FINANS_LIMIT_AND_ASSIGN F
left join dbo.BB_DEP_ACC_DOP(null) D on D.ACC_LINK = F.FACC_LINK
inner join (select LINK_UP, SUM_YEAR01 = SUM(P1 + P2 + P3 + P4 + P5 + P6 + P7 + P8 + P9 + P10 + P11 + P12), SUM_YEAR02 = SUM(Y2),  SUM_YEAR03 = SUM(Y3) from FINANSE GROUP BY LINK_UP) S on S.LINK_UP = F.LINK
where F.link in (select LINK from BUFFER where ID = @cBuffId and SID = SUSER_SID())


select 	LINK		= F.LINK,
		LINK_UP		= F.LINK,
		NOM_OSNOV	= O.NUMBER,
		DATE_OSNOV	= O.DATE,
		OSNOV		= O.[TYPE],
		PRIM		= O.COMMENT
from dbo.FINANSE_HEAD F
inner join dbo.BD_OSNOV O on F.LINK_OSNOV = O.LINK
where exists (select * from dbo.BufferGetTableByID(@cBuffId) where LINK = F.link)


-- Блок RLST
select	TYPE_KBK = case KBK.TYPE when 1 then '10'
								 when 2 then '20'
								 when 4 then '31'
								 when 8 then '32'
								 else '' end,
		KBK = left(rtrim(replace(KBK.CODE,'.','')), 20),
		KBK_IST_RF = '',
		ADD_KLASS	= isnull('(' + rtrim(EKR.CODE) + ')', '') + isnull(DCL.CODE,''),
		[LOCAL]		= REG.CODE,
		[SERVICE] = '',
		PURPOSE = '',
		PROGRAM = '',

		SUM1		= case when @iPeriodType = 1 and FH.PER_NUM = 1 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					when @iPeriod = 1 and @iPeriodType = 0 then FT.P1 + FT.P2 + FT.P3
					when @iPeriod = 2 and @iPeriodType = 0 then FT.P1
					else 0 end,
		SUM2		= case  when @iPeriod = 1 and @iPeriodType = 0 then FT.P4 + FT.P5 + FT.P6
					when @iPeriod = 2 and @iPeriodType = 0 then FT.P2
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 2 or @iPeriod = 1 and @iPeriodType = 1 and FH.PER_NUM = 4 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM3		= case  when @iPeriod = 1 and @iPeriodType = 0 then FT.P7 + FT.P8 + FT.P9
					when @iPeriod = 2 and @iPeriodType = 0 then FT.P3
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 3 or @iPeriod = 1 and @iPeriodType = 1 and FH.PER_NUM = 7 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM4		= case  when @iPeriod = 1 and @iPeriodType = 0 then FT.P10 + FT.P11 + FT.P12
					when @iPeriod = 2 and @iPeriodType = 0 then FT.P4
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 4 or @iPeriod = 1 and @iPeriodType = 1 and FH.PER_NUM = 10 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM5		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P5 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 5 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM6		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P6 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 6 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM7		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P7 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 7 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM8		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P8 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 8 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM9		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P9 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 9 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM10		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P10 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 10 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM11		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P11
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 11 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM12		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P12 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 12 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM_YEAR01	= case @iPeriod when 0 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12 else 0 end,
		SUM_YEAR02	= FT.Y2,
		SUM_YEAR03	= FT.Y3,
		KOD_BP		= F.FDEP_CODE,
		NAME_BP		= F.FDEP_NAME,
		ACC_RCP		= F.FACC_CODE,
		ACC_RCP_KIND= '',
		SRO_CODE	= '',
		SRO_NAME	= '',
		STR_TYPE	= '',
		LINK		= FT.LINK,
		LINK_UP		= FT.LINK_UP
from dbo.FINANSE FT
inner join dbo.FINANS_LIMIT_AND_ASSIGN F on F.LINK = FT.LINK_UP
inner join dbo.FINANSE_HEAD FH on FH.LINK = FT.LINK_UP
left join dbo.BI_DICTION_VKR VKR on VKR.LINK_KBK = FT.VKR 
left join dbo.KL_KBK KBK on KBK.LINK = FT.VKR --and KBK.TYPE <> 1 
left join dbo.DOP_CLASSIF DCL on DCL.LINK = FT.DOP_CL 
left join dbo.KL_REG REG on REG.LINK = FT.REG 
left join dbo.KOSGU EKR on EKR.LINK = FT.EKR 
where FT.LINK_UP in (select LINK from BUFFER where ID = @cBuffId and SID = SUSER_SID())



GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

grant execute on FB_EXPORT_BR_15 to public
GO

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

GO

CREATE PROCEDURE dbo.SD_PAYS_EMPL_SAVE
 @LINK int OUTPUT,
 @LinkEmpl int,
 @LinkSovm int,
 @LinkPays int,
 @DateBegin datetime,
 @Summa numeric(15,4) = 0,
 @LINK_MP int = null,
 @LINK_KBK int = null,
 @NO_CALC TINYINT = 0
AS

DECLARE @varKSERROR	tinyint,
	@varKStrancount	int,
	@varKSRowCount int

IF @DateBegin > '20991231'
	SET @DateBegin = '20991231'

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

	IF @LinkPays IS NULL OR @LinkPays = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END

	IF @LinkEmpl IS NULL OR @LinkEmpl = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END
	
	IF (@LINK_KBK IS NULL OR @LINK_KBK = 0)
		SET @LINK_KBK = (SELECT TOP 1 LINK_KBK FROM DBO.SA_EMPLS_INFO(@DateBegin, @LinkEmpl))
	
	IF (@LINK_KBK IS NULL OR @LINK_KBK = 0) AND EXISTS (SELECT LINK FROM PAYS WHERE LINK = @LinkPays AND PROPORC = 0)
	BEGIN
		ROLLBACK
		RETURN 5
	END

	IF @LINK IS NULL OR @LINK = 0
		BEGIN
			IF EXISTS( Select * from dbo.PAYS_EMPL where LINK_EMPL = @LinkEmpl AND LINK_SOVM = @LinkSovm AND LINK_PAYS = @LinkPays AND [DATE] = @DateBegin)
			BEGIN
				ROLLBACK
				RETURN 8 --Не уникальная запись (вместо триггера)				
			END
		
			INSERT INTO PAYS_EMPL(LINK_PAYS,LINK_EMPL,LINK_SOVM,[DATE],SUMMA, LINK_MP, LINK_KBK, NO_CALC )
			VALUES(@LinkPays,@LinkEmpl,@LinkSovm,@DateBegin,@Summa, @LINK_MP, @LINK_KBK, @NO_CALC)

			SET @LINK = @@IDENTITY

			SELECT @varKSERROR = @@ERROR
			IF @varKSERROR <> 0
			BEGIN
				ROLLBACK
				RETURN 7
			END
		END
	ELSE
		BEGIN
			UPDATE dbo.PAYS_EMPL WITH (ROWLOCK) 
			SET 	[DATE] = @DateBegin, SUMMA=@Summa, LINK_KBK= @LINK_KBK, NO_CALC = @NO_CALC 
			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

	IF @varKSERROR <> 0
		RETURN @varKSERROR

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0







GO


GRANT EXECUTE ON dbo.[SD_PAYS_EMPL_SAVE] TO PUBLIC

GO



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

GO


CREATE  PROCEDURE [dbo].SD_CONTROL_HOLIDAYS
AS
CREATE TABLE #TempControlTable (OBJ_CODE varchar(30), OBJ_NAME varchar(50), FIELD_NAME varchar(30), LINK	int, COMMENTS varchar(254),Type int)

INSERT INTO #TempControlTable
SELECT 'KD_HOLIDAYS','Контроль праздничных дней','Тип дня', link,'Не заполнен тип дня',1 FROM KD_HOLIDAYS
WHERE TD_LINK IS NULL

INSERT INTO #TempControlTable
SELECT 'KD_HOLIDAYS','Контроль праздничных дней','Дата', link,'Не заполнена дата',1 FROM KD_HOLIDAYS
WHERE ISNULL([DAY],0) = 0 OR ISNULL([MONTH],0) = 0 OR ISNULL([YEAR],0) = 0

SELECT * FROM #TempControlTable order by 3

GO


GRANT EXECUTE ON dbo.[SD_CONTROL_HOLIDAYS] TO PUBLIC

GO



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

GO

/*EXEC dbo.BK_SELECT_EXPORT_FORMAT 2486*/
/*exec [dbo].SA_4FSS_EXPORT_v05       42251*/
CREATE      PROCEDURE [dbo].SA_4FSS_EXPORT_v07 ( @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 @LIKV VARCHAR(3), @nLIKV INT
SELECT @LIKV = ISNULL(dbo.RN_GET_ATR_VALUE(@LINK, 'REPORTS_ATR_LIKVID'),'00')
SET @nLIKV = CASE WHEN LTRIM(RTRIM(@LIKV)) = 'Да' THEN 1 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.7"?>'
UNION ALL SELECT @lcFNAME, SPACE(0) + '<F4REPORT xmlns="http://fz122.fss.ru" xmlns:xsd="http://www.w3.org/2001/XMLSchema-instance" xsd:schemaLocation="http://fz122.fss.ru/doc/f4form_2015.xsd">'

/** Титул **/

	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)),'') + '"'
		+ ' YEAR_NUM="' + CONVERT(VARCHAR(4),@YEAR) + '"'
		+ ' QUART_NUM="' + (CASE @Period_Number WHEN 1 THEN '03' WHEN 2 THEN '06' WHEN 3 THEN '09' ELSE '12' END) + '"'
		+ ' NAME="' + LTRIM(RTRIM(REPLACE(FULL_NAME,'"','&quot;'))) + '"'
		+ ' 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)) + '"'
		+ ' PHONE="' +(SELECT LTRIM(RTRIM(phone)) FROM DICTIONARY_OTV_FACE  WHERE Dep_LINK=dbo.GetOwnDepLink() and name = 'Главный бухгалтер') + '"'
		+ ' LIKV="' +LTRIM(RTRIM(CONVERT(VARCHAR(1),@nLIKV))) + '"'
		+ ' 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)))) + '"' --из них: работающих, занятых на работах с вредными и (или) опасными производственными факторами	
		+ ' CEO="' + LTRIM(RTRIM(CHIEF_FIO)) + '"'
		+ ' CRE_DATE="' + convert(varchar(10),@modify_date,120) + '"'
		--+ ' WRO="' + LEFT(FSS_REG_NUM,4) + '"'
		--+ ' CFO="' + LTRIM(RTRIM(GLBUH_FIO)) + '"'
		--+ ' AUTHOR="' + ISNULL(dbo.AdminGetUserFIO(default),'') + '"'
		+ '/>'
		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) + ' S3QCase5="' + 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) + ' S3R9C1="' + 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) + ' S3R9C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 3, 5) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase6="' + 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) + ' S3R10C1="' + 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) + ' S3R10C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 4, 5) WHERE SUMMA2 <> 0		


----------
		--Таблица 2 строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase4="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 5, 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, 5, 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, 5, 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, 5, 6) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3QCase3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 6, 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, 6, 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, 6, 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, 6, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 7
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R5C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 7, 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, 7, 5) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 8
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R6C1="' + 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) + ' S3R6C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 8, 5) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 9
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP7="' + 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) + ' S3R7C1="' + 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) + ' S3R7C2="' + 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) + ' S3R7C3="' + 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) + ' S3RCP71="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 10, 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, 10, 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, 10, 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, 10, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 11
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3RCP72="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 11, 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, 11, 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, 11, 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, 11, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 12
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R3C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 12, 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, 12, 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, 12, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 13
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R11C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 13, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R11C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 13, 6) WHERE SUMMA2 <> 0		
		--Таблица 2 строка 14
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R8C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 14, 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, 14, 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, 14, 6) WHERE SUMMA2 <> 0				
		--Таблица 2 строка 16
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R12C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 16, 5) WHERE SUMMA2 <> 0		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' S3R12C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 3, 16, 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) + ' 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, 5, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 6
		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, 6, DEFAULT) WHERE SUMMA2 <> 0 AND COL IN (3,4,5,6)
		--Таблица 3 строка 7
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S8' + 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)
		--Таблица 3 строка 8
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' S9' + 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, 8, 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 строка 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, 4) WHERE SUMMA2 <> 0	
		-- Таблица 4 строка 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, 4) WHERE SUMMA <> 0				
		-- Таблица 4 строка 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, 4) WHERE SUMMA <> 0				
		-- Таблица 4 строка 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, 5) 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, 6) WHERE ISNULL(STR_VAL,'') <> ''
	
		--Таблица 4.1 строка 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.1 строка 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.1 строка 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.1 строка 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.1 строка 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.1 строка 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 #INOST (
			LINK INT, FIO VARCHAR(254), INN VARCHAR(12), SNILS VARCHAR(14),
			GR VARCHAR(100), GR_CODE VARCHAR(5))

		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, 5, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

		INSERT INTO #INOST (FIO, INN, SNILS,GR)
		SELECT DISTINCT
			FIO = (SELECT TOP 1 REPLACE(STR_VAL,SPACE(1), ', ') FROM #TAB3 T WHERE T.COL = 2 AND T.ROW_CODE = T3.ROW_CODE),
			INN = (SELECT TOP 1 STR_VAL FROM #TAB3 T WHERE T.COL = 3 AND T.ROW_CODE = T3.ROW_CODE),
			SNILS = (SELECT TOP 1 STR_VAL FROM #TAB3 T WHERE T.COL = 4 AND T.ROW_CODE = T3.ROW_CODE),
			GR = (SELECT TOP 1 STR_VAL FROM #TAB3 T WHERE T.COL = 5 AND T.ROW_CODE = T3.ROW_CODE)
		FROM
			#TAB3 T3
		
		UPDATE i
			SET gr_code = (select code FROM citizenship WHERE NAME LIKE i.GR)
		FROM #INOST  i
		

		DROP TABLE #TAB3



		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME,
			SPACE(1) + ' <F4INOST'  +
				' LNAME="' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO,1,','),'')))) + '"' +
				' FNAME="' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO,2,','),'')))) + '"' +
				' MNAME="' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO,3,','),'')))) + '"' +
				' INN="' + LTRIM(RTRIM(ISNULL(INN,''))) + '"' +
				' SNILS="' + LTRIM(RTRIM(ISNULL(SNILS,''))) + '"' +
				' GR="' + LTRIM(RTRIM(ISNULL(GR_CODE,''))) + '"' +
			' />'
		FROM #INOST
		ORDER BY FIO

		DROP TABLE #INOST

		

	/*--Сведения об инвалидах
		CREATE TABLE #INVALID (
			LINK INT, FIO VARCHAR(254), FIO2 VARCHAR(254), NUM_SPR VARCHAR(30), DATE_SPR VARCHAR(10),
			GRP VARCHAR(25), GRP2 VARCHAR(25), PER_BEG VARCHAR(10), PER_END VARCHAR(10),
			SM_ALL 	NUMERIC(18,2), SM_QWART NUMERIC(18,2), SM1 NUMERIC(18,2), SM2 NUMERIC(18,2), SM3 NUMERIC(18,2) )

		CREATE TABLE #TAB5 (ROW_CODE VARCHAR(4), COL INT, SUMMA NUMERIC(18,2), STR_VAL VARCHAR(254))
		INSERT INTO #TAB5 (ROW_CODE, COL, SUMMA, STR_VAL)
		SELECT ROW_CODE, COL, SUMMA2, STR_VAL FROM DBO.SA_SAVED_REPORT_VIEW (@link, 5, DEFAULT, DEFAULT) T WHERE T.COL >= 2 ORDER BY T.COL

		INSERT INTO #INVALID (FIO2, DATE_SPR, PER_END, SM_ALL, SM1, SM2, SM3)
		SELECT DISTINCT
			FIO2 = (SELECT TOP 1 REPLACE(STR_VAL,SPACE(1), ', ') FROM #TAB5 T WHERE T.COL = 2 AND T.ROW_CODE = T5.ROW_CODE),
			DATE_SPR = (SELECT TOP 1 STR_VAL FROM #TAB5 T WHERE T.COL = 3 AND T.ROW_CODE = T5.ROW_CODE),
			PER_END = (SELECT TOP 1 STR_VAL FROM #TAB5 T WHERE T.COL = 4 AND T.ROW_CODE = T5.ROW_CODE),
			SM_ALL = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 5 AND T.ROW_CODE = T5.ROW_CODE),
			SM1 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 6 AND T.ROW_CODE = T5.ROW_CODE),
			SM2 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 7 AND T.ROW_CODE = T5.ROW_CODE),
			SM3 = (SELECT TOP 1 SUMMA FROM #TAB5 T WHERE T.COL = 8 AND T.ROW_CODE = T5.ROW_CODE)
		FROM
			#TAB5 T5

		DROP TABLE #TAB5

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME,
			SPACE(1) + ' <F4INVAL'  +
				' LNAME="' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,1,','),'')))) + '"' +
				' FNAME="' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,2,','),'')))) + '"' +
				' MNAME="' + UPPER(LTRIM(RTRIM(ISNULL(dbo.SA_GET_WORD_NUM(FIO2,3,','),'')))) + '"' +
				' MSEDATE="' + CASE LEN(LTRIM(RTRIM(ISNULL(DATE_SPR,''))))
									WHEN 10 THEN
										SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),7,4)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),4,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),1,2)
									WHEN 8 THEN
										'20' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),7,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),4,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(DATE_SPR,''))),1,2)								
									ELSE
										''
								END + '"' +
				CASE WHEN ISNULL(PER_END,'') <> ''
				THEN
					' MSEDATEF="'
								+ CASE LEN(LTRIM(RTRIM(ISNULL(PER_END,''))))
									WHEN 10 THEN
										SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),7,4)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),4,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),1,2)
									WHEN 8 THEN
										'20' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),7,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),4,2)
										+ '-' + SUBSTRING(LTRIM(RTRIM(ISNULL(PER_END,''))),1,2)								
									ELSE
									''
								END + '"'
				ELSE
					''	
				END +
				' S="' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM_ALL,0)))) + '"' +
				' S1="' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM1,0)))) + '"' +
				' S2="' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM2,0)))) + '"' +
				' S3="' + LTRIM(RTRIM(CONVERT(VARCHAR(20),ISNULL(SM3,0)))) + '"' +
			' />'
		FROM #INVALID
		ORDER BY FIO2

		DROP TABLE #INVALID

	*/	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '</F4INF1>'
		
/** Раздел II **/

		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(1)

	
		
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
		SELECT @lcFNAME, SPACE(0) + '<F4INFO '		
		--Таблица 5 Строка 1
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C8="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 12) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C18="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 13) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C7="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 14) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 17) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C12="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 18) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C22="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 19) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R1C11="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 1, 20) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 17) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C12="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 18) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C22="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 19) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R2C11="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 2, 20) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R3C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 3, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R3C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 3, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R3C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 3, 15) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R31C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 4, 17) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R32C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 5, 17) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C4="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 6) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C14="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 7) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 8) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C6="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 9) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C16="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 10) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C5="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 11) WHERE SUMMA2 <> 0				

		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C10="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 15) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C20="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 16) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R4C9="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 6, 17) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 7
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R5C="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 7, 3) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R5C1="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 7, 4) WHERE SUMMA2 <> 0				
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R5C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 7,5) WHERE SUMMA2 <> 0				

		--Таблица 5 Строка 8
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T5R6C2="' + CONVERT(VARCHAR(20),SUMMA2) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 12, 8, 5) WHERE SUMMA2 <> 0				



		--Таблица 6 Строка 1
		UNION ALL SELECT @lcFNAME, SPACE(1)		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' OKVED="' + LTRIM(RTRIM(OKVED)) + '"' FROM #DEP_DATA
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T1R3C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T1R5C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 5) WHERE SUMMA2 <> 0
		--Таблица 6 Строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 3, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' I1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 3, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 3, 5) WHERE SUMMA2 <> 0
		--Таблица 6 Строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 4, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' I2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 4, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 4, 5) WHERE SUMMA2 <> 0
		--Таблица 6 Строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' C3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 5, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' I3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 5, 4) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' NC3="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 5, 5) WHERE SUMMA2 <> 0
		--Таблица 6 графа 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RATE_MIS="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,1),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 6) WHERE SUMMA2 <> 0
		--Таблица 6 графа 7
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RATE_DEC="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 7) WHERE SUMMA2 <> 0
		--Таблица 6 графа 8
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' INC_DATE="'
					+ CASE LEN(LTRIM(RTRIM(LEFT(STR_VAL,10))))
						WHEN 10 THEN
							SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),7,4)
							+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),4,2)
							+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),1,2)
						WHEN 8 THEN
							'20' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),7,2)
							+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),4,2)
							+ '-' + SUBSTRING(LTRIM(RTRIM(LEFT(STR_VAL,10))),1,2)								
						ELSE
						''
					END + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 8) WHERE ISNULL(STR_VAL,'') <> ''

		--Таблица 6 графа 9
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' RATE_INC="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 13, 1, 9) WHERE SUMMA2 <> 0


		--Таблица 7 строка 1
		UNION ALL SELECT @lcFNAME, SPACE(1)		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R1C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 1, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R3C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 3, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R5C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 5, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R6C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 6, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R7C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 7, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R9C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 8, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R13C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 9, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R11C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 10, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R16C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 11, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 7
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R17C61="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 12, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 9
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R18C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 14, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 11
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R39C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 16, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 12
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R19C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 17, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 14
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R40C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 19, 3) WHERE SUMMA2 <> 0

		--Таблица 7 строка 15
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R21C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 21, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R23C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 23, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R24C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 24, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R25C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 25, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 16
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R27C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 27, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R29C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 29, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R30C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 30, 3) WHERE SUMMA2 <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R31C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 31, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 17
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R38C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 32, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 19
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R34C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14,34, 3) WHERE SUMMA2 <> 0
		--Таблица 7 строка 20
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T7R35C1="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 35, 3) WHERE SUMMA2 <> 0

		--Таблица 8 строка 1
		UNION ALL SELECT @lcFNAME, SPACE(1)		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R3C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 1, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R3C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 1, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R13C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 2, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R13C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 2, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 3
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R4C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 3, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R4C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 3, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 4
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R8C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 4, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R8C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 4, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 5
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R14C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 5, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R14C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 5, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 6
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R9C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 6, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R9C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 6, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 7
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R5C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 7, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R5C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 7, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 8
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R6C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 8, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R6C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 8, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 9
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R10C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15, 9, 4) WHERE SUMMA2 <> 0
		--Таблица 8 строка 11
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' T6R11C2="' + CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 15,11, 4) WHERE SUMMA2 <> 0


		--Таблица 9
		UNION ALL SELECT @lcFNAME, SPACE(1)
		UNION ALL SELECT @lcFNAME, SPACE(1) + ' M' + CONVERT(VARCHAR(2),ROW) + '="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 16, DEFAULT, 3) WHERE ROW IN (1,2,3,5) AND SUMMA <> 0

		--Таблица 10 строка 1
		UNION ALL SELECT @lcFNAME, SPACE(1)
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' ATT_C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 17, 1, 3) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' ATT_C2="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 17, 1, 4) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' ATT_CL3="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 17, 1, 6) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' ATT_CL4="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 17, 1, 7) WHERE SUMMA <> 0

		--Таблица 10 строка 2
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' MED_C1="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 17, 2, 8) WHERE SUMMA <> 0
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(1) + ' MED_C2="' + CONVERT(VARCHAR(20),SUMMA) + '"' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 17, 2, 9) WHERE SUMMA <> 0
		
		UNION ALL SELECT TOP 1 @lcFNAME, SPACE(0) + ' >'

		/*Раздел I Платежное поручение*/
		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 29, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@first_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 29, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 29, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 30, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@second_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 30, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 30, 4)

		IF EXISTS (SELECT * FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 31, 3) WHERE SUMMA2 > 0)
			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT TOP 1 @lcFNAME, SPACE(1) + ' <PAYM_ORDER NUM="' + STR_VAL + '" DT="' + convert(varchar(10),dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@third_month_of_quarter,@YEAR)),120) + '"' + ' SUM="' + (SELECT TOP 1 CONVERT(VARCHAR(20),CONVERT(NUMERIC(18,2),SUMMA2)) FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 31, 3)) + '"/>' FROM DBO.SA_SAVED_REPORT_VIEW (@link, 14, 31, 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_v07] TO PUBLIC

GO



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

GO

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

CREATE   PROCEDURE [dbo].KD_GRAPH_FILL
		  @LinkGrType int,
		  @Month int,
		  @Year int
AS		 
DECLARE @DateX datetime,
		  @Holiday tinyint,	
		  @DaysInWeek int,
		  @DaysInMonth int,
		  @FirstDay datetime,
		  @LastDay datetime,
		  @Day int,
		  @DayInGraph int,
		  @CurDay datetime,
		  --для вычисления дня недели с которого перенесли день
		  @CurDay2 datetime, 
		  ---
		  @DayInWeek int,
		  @HolidayType int,
		  @HolidaySymb	varchar(5),
		  @HolidayName	varchar(254),
		  @HolidayHour numeric(10,2),			
		  @HolType int,
		  @HolSymb	varchar(5),
		  @HolName	varchar(254),
		  @HolHour numeric(10,2)			


CREATE TABLE #TmpGraph(UPD int,DEL int,DAY int,HOUR numeric(10,2),TD_LINK int,TD_CODE varchar(5), TD_NAME varchar(254), PRIORITET int)
SET @Day = 1

SELECT @DateX = DATE_BEG,@Holiday = HOLIDAY FROM GRAPH_VID WHERE LINK = @LinkGrType


SELECT @DaysInWeek = COUNT(DISTINCT NUMBER) FROM GRAPH_VID_TABLE WHERE LINK_UP = @LinkGrType


SELECT * INTO #TmpDays FROM KD_GRAPH_VID_TABLE WHERE LINK = @LinkGrType


SELECT @FirstDay = CONVERT(DATETIME,'01.'+LTRIM(RTRIM(STR(@Month)))+'.'+LTRIM(RTRIM(STR(@Year))),104)

SELECT @LastDay = dbo.DateEndOfMonth(@FirstDay)

SELECT @DaysInMonth  = DATEDIFF(d,@FirstDay,@LastDay)+1

SELECT TOP 1 @HolidayType =  LINK,@HolidayHour = HOUR,@HolidaySymb = SYMB, @HolidayName = [Name] FROM KD_TYP_DAYS WHERE WORK_D = 11
IF @HolidayType IS NULL 
BEGIN	
	RAISERROR ('В справочнике типы дней неправильно заполнен тип дня - выходной !',11,1)
	RETURN 111
END
WHILE @Day <= @DaysInMonth
BEGIN

	SET @CurDay = DATEADD(d,@Day,@FirstDay)-1

	--Обработка ситуации, при которой день является перенесенным с другого числа
	SET @CurDay2 = (
							SELECT TOP 1 CONVERT(DATETIME,LTRIM(RTRIM(STR(DAY1)))+'.'+LTRIM(RTRIM(STR(MONTH1)))+'.'+LTRIM(RTRIM(STR(YEAR))),104) 
								FROM dbo.HOLIDAYS 
								WHERE 
									[year] = @Year
									AND ([MONTH] * 100 + [DAY]) <> ([MONTH1] * 100 + [DAY1]) 
									AND CONVERT(DATETIME,LTRIM(RTRIM(STR(DAY)))+'.'+LTRIM(RTRIM(STR(MONTH)))+'.'+LTRIM(RTRIM(STR(YEAR))),104) = @CurDay
						)		
	IF @DaysInWeek > 0
		IF ISNULL(@CurDay2,@CurDay) >= @DateX
			SELECT @DayInWeek = DATEDIFF(d,@DateX,ISNULL(@CurDay2,@CurDay))%@DaysInWeek+1		
		ELSE 
			SELECT @DayInWeek = (@DaysInWeek - DATEDIFF(d,ISNULL(@CurDay2,@CurDay),@DateX)%@DaysInWeek)%@DaysInWeek +1		
	ELSE
		SELECT @DayInWeek = 0		

	IF @CurDay IN (SELECT CONVERT(DATETIME,LTRIM(RTRIM(STR([DAY])))+'.'+LTRIM(RTRIM(STR([MONTH])))+'.'+LTRIM(RTRIM(STR([YEAR]))),104) 
					FROM KD_HOLIDAYS) 
			AND @Holiday = 1	
		BEGIN
			
			IF EXISTS(SELECT * FROM KD_HOLIDAYS WHERE TD_LINK IS NOT NULL AND TYPE_HOL IN (1,3) AND
				CONVERT(DATETIME,LTRIM(RTRIM(STR(DAY)))+'.'+LTRIM(RTRIM(STR(MONTH)))+'.'+LTRIM(RTRIM(STR(YEAR))),104) = @CurDay) 				
				BEGIN
					SELECT TOP 1 @HolType =  LINK,@HolHour = HOUR,@HolSymb = SYMB, @HolName = [Name]
					FROM KD_TYP_DAYS WHERE LINK = 
					(SELECT TOP 1 TD_LINK FROM KD_HOLIDAYS WHERE 
					CONVERT(DATETIME,LTRIM(RTRIM(STR(DAY)))+'.'+LTRIM(RTRIM(STR(MONTH)))+'.'+LTRIM(RTRIM(STR(YEAR))),104) = @CurDay)

					INSERT INTO #TmpGraph (UPD,DEL,DAY,HOUR,TD_LINK,TD_CODE,TD_NAME, PRIORITET)
					VALUES(0,0,@Day,@HolHour,@HolType,@HolSymb,@HolName,0)
				END
			ELSE

			IF EXISTS(SELECT * FROM KD_HOLIDAYS WHERE TD_LINK IS NOT NULL AND TYPE_HOL = 2 AND
				CONVERT(DATETIME,LTRIM(RTRIM(STR(DAY)))+'.'+LTRIM(RTRIM(STR(MONTH)))+'.'+LTRIM(RTRIM(STR(YEAR))),104) = @CurDay) 				
				BEGIN
					SELECT TOP 1 @HolType =  LINK, @HolSymb = SYMB, @HolName = [Name]
					FROM KD_TYP_DAYS WHERE LINK = 
					(SELECT TOP 1 TD_LINK FROM KD_HOLIDAYS WHERE 
					CONVERT(DATETIME,LTRIM(RTRIM(STR(DAY)))+'.'+LTRIM(RTRIM(STR(MONTH)))+'.'+LTRIM(RTRIM(STR(YEAR))),104) = @CurDay)

					INSERT INTO #TmpGraph (UPD,DEL,DAY,HOUR,TD_LINK,TD_CODE,TD_NAME,PRIORITET)
					SELECT 0 AS UPD,0 AS DEL, @Day AS DAY, (CASE WHEN (HOURS-1) >= 0 THEN (HOURS-1) ELSE 0 END) AS HOUR, @HolType, @HolSymb, @HolName, 0 as PRIORITET
					FROM #TmpDays  WHERE NUMBER = @DayInWeek
				END
				ELSE		
				BEGIN
					INSERT INTO #TmpGraph (UPD,DEL,DAY,HOUR,TD_LINK,TD_CODE,TD_NAME,PRIORITET)
					VALUES(0,0,@Day,@HolidayHour,@HolidayType,@HolidaySymb,@HolidayName,0)
				END
		END
	ELSE
		INSERT INTO #TmpGraph (UPD,DEL,DAY,HOUR,TD_LINK,TD_CODE,TD_NAME,PRIORITET)
		SELECT 0 AS UPD,0 AS DEL, @Day AS DAY, HOURS AS HOUR,TD_LINK, TD_CODE, TD_NAME, 0 as PRIORITET
		FROM #TmpDays  WHERE NUMBER = @DayInWeek
	SET @Day = @Day + 1
END

SELECT 0 as CHECKED,* FROM 	#TmpGraph 


GO


GRANT EXECUTE ON dbo.[KD_GRAPH_FILL] TO PUBLIC

GO

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

GO

CREATE PROCEDURE dbo.BK_PRINTDOC_OS1B
	@intLINK_DOC	INT
AS
BEGIN
	DECLARE @LINK_INV	INT,
		@dDOC_DATE	DATETIME,
		@dDATE_REST	DATETIME,
		@intDEP1	INT,
		@intDEP2	INT,
		@strTRANSFER	VARCHAR (20),
		@LINK_ATT	INT,
		@intINV_OUT	TINYINT,
		@strDATE_PROV	VARCHAR (10)

	SELECT
		@dDOC_DATE = [DATE],
		@intDEP1 = DEP_R_LINK,
		@intDEP2 = DEP_P_LINK,
		@strTRANSFER = CONVERT (VARCHAR (20), TRANSFER),
		@LINK_ATT = TRUST_LINK
	FROM dbo.BV_DOC_OS1B_VIEW
	WHERE LINK = @intLINK_DOC

	IF UPPER (@strTRANSFER) = 'ПЕРЕДАЧА'
		SELECT
			@intINV_OUT = 1,
			@dDATE_REST = @dDOC_DATE	
	ELSE
		SELECT
			@intINV_OUT = 0,
			@dDATE_REST = DATEADD (DAY, 1, @dDOC_DATE)

	DECLARE @TRUST_TABLE TABLE (LINK INT, ATT_NUM VARCHAR (10), ATT_DATE VARCHAR (10), ATT_EMP VARCHAR (254))
	INSERT INTO @TRUST_TABLE 
	SELECT
		LINK,
		NUMBER,
		CONVERT (VARCHAR (10), [DATE], 104),
		dbo.ku_GetEmplFIO (LINK_MOL)
	FROM dbo.DOCUMENTS_ATTORNEY 
	WHERE LINK = @LINK_ATT
	
	-- Перечень ОС --
	SELECT *
		INTO #T_NFA
	FROM dbo.BK_DOC_TABLE_NFA_FN (@intLINK_DOC)

	-- Основные данные --
	SELECT
		DOC.LINK AS LINK_DOC,
		ISNULL (DOC.NUMBER, '') AS DOC_NUM, 
		ISNULL (CONVERT (VARCHAR (10), DOC.[DATE], 104), '') AS DOC_DATE, 
		CASE WHEN @intINV_OUT = 0
				THEN ISNULL (CONVERT (VARCHAR (10), DOC.[DATE_PROV], 104), '')
			ELSE ''	
		END AS DATE_IN,
		CASE WHEN @intINV_OUT = 1
				THEN ISNULL (CONVERT (VARCHAR (10), DOC.[DATE_PROV], 104), '')
			ELSE ''	
		END AS DATE_OUT,
		ISNULL (NFA.ACC_CODE, '') AS ACCT_CODE,
		ISNULL (dbo.BK_GET_PRINT_DEP_NAME (DOC.DEP_R_LINK), '') AS DEP_NAME1,
		ISNULL (DEP1.OKPO, '') AS OKPO1,
		ISNULL (DEP1.KPP, '') AS KPP1,
		ISNULL (DEP1.INN, '') AS INN1,
		ISNULL (dbo.GetAddressByDepLink (DOC.DEP_R_LINK, 1), '') AS ADDRESS1,
		ISNULL (dbo.BK_ACCOUNT_DEP_INFO (DOC.DEP_R_LINK), '') AS BANK1,
		ISNULL (dbo.BK_GET_PRINT_DEP_NAME (DOC.DEP_P_LINK), '') AS DEP_NAME2,
		ISNULL (DEP2.OKPO, '') AS OKPO2,
		ISNULL (DEP2.KPP, '') AS KPP2,
		ISNULL (DEP2.INN, '') AS INN2,
		ISNULL (dbo.GetAddressByDepLink (DOC.DEP_P_LINK, 1), '') AS ADDRESS2,
		ISNULL (dbo.BK_ACCOUNT_DEP_INFO (DOC.DEP_P_LINK), '') AS BANK2,
		ISNULL (NFA.INV_CODE, '') AS INV_CODE,
		ISNULL (NFA.INV_NAME, '') AS INV_NAME,
		GRP_TYPE = replace( LTRIM(RTRIM(SUBSTRING ((SELECT
							', ' + (case when LEFT(ISNULL(n.GRP_CODE,''),4) = '1011' then 'недвижимое имущество'
										WHEN LEFT(ISNULL(n.GRP_CODE,''),4) = '1012' then 'особо ценное движимое имущество' 
										WHEN LEFT(ISNULL(n.GRP_CODE,''),4) = '1013' then 'иное движимое имущество' 
									else '' end)
							FROM #T_NFA n GROUP BY LEFT(ISNULL(n.GRP_CODE,''),4)
							FOR XML PATH ('')),
							3,
							1000) )) , ', ,', '')
	                ,
		
		ISNULL (CONVERT (VARCHAR (10), DOC.TRIAL_DATE, 104), '') AS DATE_TRIAL,
		ISNULL (EXPECTATION, 0) AS EXPECT,
		CASE WHEN EXPECTATION = 1 THEN ISNULL (CONVERT (VARCHAR (254), NOEXPECT), '') 
			ELSE ''
		END AS NOEXPECT,
		ISNULL (REWORK, 0) AS REWORK,
		CASE WHEN REWORK = 1 THEN ISNULL (CONVERT (VARCHAR (254), REWORK_DESC), '') 
			ELSE ''
		END AS REWORK_INF,
		ISNULL (CONVERT (VARCHAR (254), ENCLOSURE), '') AS TECH_DOC,
		ISNULL (CONVERT (VARCHAR (254), CONCLUSION), '') AS RESUM, 
--		ISNULL (DOC.OSNOV_INFO, '') AS BASED,
		ISNULL (OSN.TYPE, '') AS BASED,
		ISNULL (OSN.NUMBER, '') AS BASE_NUM,
		ISNULL (CONVERT (VARCHAR (10), OSN.[DATE], 104), '') AS BASE_DATE,
		ISNULL (GR_O.CODE, '') AS CODE_OKOF,
		ISNULL (DG.CODE, '') AS CODE_RATE,
		ISNULL (ASS.PLANT_NUM, '') AS NUMBER_F,
		ISNULL (ASS.OTHER_NUM, '') AS NUMBER_O,
		ISNULL (ASS.PASSPORT,'') AS PASSP, 
		ISNULL (ASS.MANUFACT, '')  AS MANUFACT,
		ISNULL (ASS.FIXING, '') AS FIXING,
		CASE WHEN @intINV_OUT = 0 THEN ISNULL (ASS.CARD_NO, '') ELSE '' END AS CARD_NO,
		CASE WHEN @intINV_OUT = 0
				THEN ISNULL (CONVERT (VARCHAR (10), ASS.DATE_FILLING, 104), '')
			ELSE ''
		END AS DATE_FIL,
		ISNULL (CONVERT (VARCHAR (10), ASS.DATE_PROD, 104), '') AS DATE_PROD,
		ISNULL (CONVERT (VARCHAR (10), ASS.DATE_BEGIN, 104), '') AS DATE_BEGIN,
		DATEDIFF (YEAR, ASS.DATE_BEGIN, DOC.[DATE]) AS ALL_USED,
		ISNULL (DG.VALUE, 0) AS PER_USED,
		ISNULL ((SELECT [NAME] FROM dbo.BV_DICTIONARY_DEPRE_METHOD WHERE VALUE = ASS.WEAR_FLAG), '') AS DEPRE_NAME,
		ISNULL (ND.DEPRE_RATE, 0) AS DEPRE_RATE,
		ISNULL (NFA.DEPRE_SUM, 0 ) AS REST_AMORT,
		ISNULL (NFA.BALANCE, 0 ) AS BALANSE,
		ISNULL (NFA.BALANCE, 0 ) - ISNULL (NFA.DEPRE_SUM, 0 ) AS LAST_COST,
		ISNULL (CHIEF1.SHORT_NAME, '') AS CHIEF1,
		ISNULL (CHIEF1.POST_NAME, '') AS CHPOST1,
		ISNULL (CHIEF2.SHORT_NAME, '') AS CHIEF2,
		ISNULL (CHIEF2.POST_NAME, '') AS CHPOST2,
		ISNULL (BUH1.SHORT_NAME, '') AS GLBUH1,
		ISNULL (BUH1.POST_NAME, '') AS GLPOST1,
		ISNULL (BUH2.SHORT_NAME, '') AS GLBUH2,
		ISNULL (BUH2.POST_NAME, '') AS GLPOST2,
		ISNULL (DOC.EMP_R_CODE, '') AS EMP_TAB1,
		dbo.BK_Get_EMPL_Signature (DOC.EMP_R_LINK, DEFAULT) AS EMP_NAME1,
		ISNULL (dbo.ku_GetEmplPostName (EMP_R_LINK, DOC.[DATE]), '') AS EMP_POST1,
		ISNULL (DOC.EMP_P_CODE, '') AS EMP_TAB2,
		dbo.BK_Get_EMPL_Signature (DOC.EMP_P_LINK, DEFAULT) AS EMP_NAME2,
		ISNULL (dbo.ku_GetEmplPostName (EMP_P_LINK, DOC.[DATE]), '') AS EMP_POST2,
		ISNULL (DOC.MOL_R_CODE, '') AS EMP_CD_R,
		dbo.BK_Get_EMPL_Signature (DOC.MOL_R_LINK, DEFAULT) AS EMP_NM_R,
		ISNULL (dbo.ku_GetEmplPostName (MOL_R_LINK, DOC.[DATE]), '') AS EMP_POST_R,
		ISNULL (D_ATT.ATT_DATE, '') AS ATT_DATE,
		ISNULL (D_ATT.ATT_NUM, '') AS ATT_NUM,
		ISNULL (D_ATT.ATT_EMP, '') AS ATT_EMP,
		USED_YM	=	CASE
						WHEN ASS.DATE_BEGIN IS NULL OR ASS.DATE_BEGIN >= DOC.[DATE] THEN ''
						ELSE CONVERT (VARCHAR (10), DATEDIFF (MONTH, ASS.DATE_BEGIN, DOC.[DATE])) + ' мес.'
					END
	INTO #DOC_OS1
	FROM dbo.BV_DOC_OS1B_VIEW DOC

	LEFT JOIN dbo.DEPARTMENTS DEP1 ON (DOC.DEP_R_LINK = DEP1.LINK)
	LEFT JOIN dbo.DEPARTMENTS DEP2 ON (DOC.DEP_P_LINK = DEP2.LINK)

	LEFT JOIN #T_NFA NFA ON (NFA.LINK_UP = DOC.LINK)
	LEFT JOIN dbo.INVENTORY I ON (NFA.INV_TYPE = 'INVENTORY_CARD'
			AND I.LINK = NFA.INV_LINK)
	LEFT JOIN dbo.ASSETS ASS ON (ASS.LINK_UP = I.LINK)
	LEFT JOIN dbo.ASSETS_GROUP_OKOF GR_O ON (GR_O.LINK = ASS.OKOF)
	LEFT JOIN dbo.DEPRE_GROUP DG ON (DG.LINK = ASS.DEPRE_GROUP)
	LEFT JOIN dbo.BK_GetNormDepreTableByOS (DEFAULT) ND ON (ND.INV = I.LINK)

	LEFT JOIN dbo.BD_OSNOV OSN ON (OSN.LINK = DOC.OSNOV_LINK)
	LEFT JOIN dbo.GetOtvFaceData (@intDEP1, 'РУКОВОДИТЕЛЬ') CHIEF1
			ON (CHIEF1.LINK_DEP = DOC.DEP_R_LINK)
	LEFT JOIN dbo.GetOtvFaceData (@intDEP2, 'РУКОВОДИТЕЛЬ') CHIEF2
			ON (CHIEF2.LINK_DEP = DOC.DEP_P_LINK)
	LEFT JOIN dbo.GetOtvFaceData (@intDEP1, 'ГЛАВНЫЙ БУХГАЛТЕР') BUH1
			ON (BUH1.LINK_DEP = DOC.DEP_R_LINK)
	LEFT JOIN dbo.GetOtvFaceData (@intDEP2, 'ГЛАВНЫЙ БУХГАЛТЕР') BUH2
			ON (BUH2.LINK_DEP = DOC.DEP_P_LINK)
	LEFT JOIN @TRUST_TABLE D_ATT ON (D_ATT.LINK = DOC.TRUST_LINK)
	WHERE DOC.LINK = @intLINK_DOC
	
	-- ХАРАКТЕРИСТИКА & ДРАГ. МЕТАЛЛЫ --
	DECLARE @TABLE_CHAR_DRAG TABLE (REC_NO INT, INV INT, INV_CODE VARCHAR (20),
		NAME_OBJ VARCHAR (7000), DR_NAME VARCHAR (100), DR_CODE VARCHAR (20),
		UM_CODE VARCHAR (20), UM_NAME VARCHAR (254), WEIGTH NUMERIC (10,2))

	-- Хар-ка --
	DECLARE @TABLE_CHAR TABLE
		(
		REC_NO INT IDENTITY,
		INV INT,
		NAME_OBJ VARCHAR (7000),
		BASIC_OBJ VARCHAR (254))

	INSERT INTO @TABLE_CHAR (INV, NAME_OBJ, BASIC_OBJ)
	SELECT
		T1.LINK_UP,
		CASE
			WHEN ISNULL (T1.NAME, '') = '' THEN ''
			ELSE RTRIM (T1.NAME) + ': '
		END
		+ ISNULL (RTRIM (LTRIM (T1.ATTR1)), '')
		+ ISNULL (RTRIM (', ' + LTRIM (T1.ATTR2)), '')
		+ ISNULL (RTRIM (', ' + LTRIM (T1.ATTR3)), '')
		+ ISNULL (RTRIM (', ' + LTRIM (T1.ATTR4)), '')
		+ ISNULL (RTRIM (', ' + LTRIM (T1.ATTR5)), '')
		+ ISNULL (RTRIM (', ' + LTRIM (T1.ATTR6)), ''),
		ISNULL (T1.BASIC_OBJ, '')
	FROM dbo.BV_DICTIONARY_SHORT_DESC T1
	INNER JOIN #T_NFA T2 ON (T2.INV_TYPE = 'INVENTORY_CARD'
		AND T2.INV_LINK = T1.LINK_UP)

	-- Драг. металлы --
	DECLARE @TABLE_DRAG TABLE (REC_NO INT IDENTITY, INV INT, DRAG_CODE VARCHAR (20),
		DRAG_NAME VARCHAR (254), UM_CODE VARCHAR (20), UM_NAME VARCHAR (254), WEIGTH NUMERIC (10,2))

	INSERT INTO @TABLE_DRAG (INV, DRAG_CODE, DRAG_NAME, UM_CODE, UM_NAME, WEIGTH)
	SELECT
		T1.LINK_UP,
		ISNULL (CODE_PREC, ''),
		ISNULL (NAME_PREC, ''),
		ISNULL (CODE_UM, ''),
		ISNULL (NAME_UM, ''),
		ISNULL (WEIGTH, 0)
	FROM dbo.BV_DICTIONARY_PRECIOUS_CONTENT T1
	INNER JOIN #T_NFA T2 ON (T2.INV_TYPE = 'INVENTORY_CARD'
		AND T2.INV_LINK = T1.LINK_UP)

	INSERT INTO @TABLE_CHAR_DRAG (REC_NO, INV, NAME_OBJ, DR_NAME, DR_CODE, UM_CODE,UM_NAME, WEIGTH)
	SELECT
		ISNULL (T1.REC_NO, T2.REC_NO),
		ISNULL (T1.INV, T2.INV),
		ISNULL (T1.NAME_OBJ, ''),
		ISNULL (T2.DRAG_NAME, ''),
		ISNULL (T2.DRAG_CODE, ''),
		ISNULL (T2.UM_CODE,  ''),
		ISNULL (T2.UM_NAME,  ''),
		ISNULL (T2.WEIGTH,  0)
	FROM @TABLE_CHAR T1
	FULL JOIN @TABLE_DRAG T2 ON (T2.REC_NO = T1.REC_NO
			AND T2.INV = T1.INV)
	
	UPDATE T1
	SET INV_CODE = T2.INV_CODE
	FROM @TABLE_CHAR_DRAG T1
	LEFT JOIN #T_NFA T2 ON (T2.INV_TYPE = 'INVENTORY_CARD'
		AND T2.INV_LINK = T1.INV)

	IF NOT EXISTS (SELECT * FROM @TABLE_CHAR_DRAG)
		INSERT INTO @TABLE_CHAR_DRAG (REC_NO, INV, INV_CODE, NAME_OBJ, DR_NAME, DR_CODE, UM_CODE,UM_NAME, WEIGTH)
		SELECT 0, 0, '', '', '', '', '', '', 0
	
	-- Основные сведения --
	SELECT
		T1.*,
		DOC_COM	=	ISNULL (GPCH.DOC_NUM, ''),
		DATE_DCOM	=	ISNULL (CONVERT (VARCHAR (10), GPCH.DOC_DATE, 104), ''),
		PRED_SIGN	=	ISNULL (dbo.BK_Get_EMPL_Signature (GPCH.EMP_PRED, DEFAULT), ''),
		NEW_PAGE1	=	''
	FROM #DOC_OS1 T1
	LEFT JOIN dbo.G_PROV_COMISSION_HEAD GPCH ON (GPCH.DOC_LINK = T1.LINK_DOC)
	LEFT JOIN dbo.KU_EMPL_PLACING GPCH_EM ON (GPCH_EM.LINK = GPCH.EMP_PRED)

/*
	SELECT
		*
	FROM (SELECT LINK1 = @intLINK_DOC) AS T1
	LEFT JOIN #DOC_OS1 T2 ON (@intINV_OUT = 1
		AND T2.LINK_DOC = T1.LINK1)
*/	
	-- Характеристика --
	SELECT
		TAB_NO = 1,
		@intINV_OUT,
		*
	FROM @TABLE_CHAR_DRAG
	ORDER BY REC_NO
	-- Комиссия --
	IF exists (select *	FROM dbo.G_PROV_COMISSION_MEMBERS GPCM
		LEFT JOIN dbo.KU_EMPL_PLACING GPCM_EM ON (GPCM_EM.LINK = GPCM.MEMBER)
		WHERE GPCM.DOC_LINK = @intLINK_DOC)
	begin
		SELECT
			DOC_LINK = ISNULL (GPCM.DOC_LINK, ''),
			MEMB_SIGN = ISNULL (dbo.BK_Get_EMPL_Signature (GPCM.MEMBER, DEFAULT), ''),
			TF_NAME	=	'C_COMIS'
		FROM dbo.G_PROV_COMISSION_MEMBERS GPCM
		LEFT JOIN dbo.KU_EMPL_PLACING GPCM_EM ON (GPCM_EM.LINK = GPCM.MEMBER)
		WHERE GPCM.DOC_LINK = @intLINK_DOC
		ORDER BY GPCM.ORDERS
	end 
	else begin 
		SELECT
			DOC_LINK = '',
			MEMB_SIGN =  '',
			TF_NAME	=	'C_COMIS'

	end

	-- Проводки --
	DECLARE @doc_date VARCHAR(10)
	SET @doc_date = (select top 1 doc_date FROM #DOC_OS1 )
	
	SELECT
		DEB_CODE	=	ISNULL (T2.DEB_CODE, ''),
		CRED_CODE	=	ISNULL (T2.CRED_CODE, ''),
		SUM_DC	=	ISNULL (T2.SUM_DC, 0),
		GLBUH1	=	ISNULL (T3.GLBUH1, ''),
		GLBUH2	=	ISNULL (T3.GLBUH2, ''),
		TF_NAME	=	'C_PROV',
		[TRANSFER]	=	@strTRANSFER,
		doc_date = @doc_date		
	FROM (SELECT LINK1 = @intLINK_DOC) AS T1
	LEFT JOIN (
		SELECT
			DOC_LINK = TTT.LINK_G,
			DEB_CODE	=	TTT.ACCT_CD_D,
			CRED_CODE	=	TTT.ACCT_CD_K,
			SUM_DC	=	SUM (TTT.SUMMA)
		FROM dbo.BK_PrintDocProv (@intLINK_DOC, DEFAULT) TTT
		GROUP BY
			TTT.LINK_G,
			TTT.ACCT_CD_D,
			TTT.ACCT_CD_K
		) AS T2 ON (T2.DOC_LINK = T1.LINK1)
	LEFT JOIN (
		SELECT
			TTT.LINK_DOC,
			GLBUH1,
			GLBUH2
		FROM #DOC_OS1 TTT
		GROUP BY
			TTT.LINK_DOC,
			GLBUH1,
			GLBUH2
		) AS T3 ON (T3.LINK_DOC = T1.LINK1)
		
END

GO


GRANT EXECUTE ON dbo.[BK_PRINTDOC_OS1B] TO PUBLIC

GO



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

GO

CREATE PROCEDURE dbo.BK_PRINTDOC_OS1
	@intLINK_DOC	INT
AS
BEGIN
	DECLARE @LINK_INV	INT,
		@dDOC_DATE	DATETIME,
		@dDATE_REST	DATETIME,
		@BALANSE	NUMERIC (28,4),
		@AMORT		NUMERIC (28,4),
		@OST_SUM	NUMERIC (28,4),
		@intDEP1	INT,
		@intDEP2	INT,
		@strTRANSFER	VARCHAR (20),
		@LINK_ATT	INT,
		@cACCOUNT	VARCHAR (60),
		@intINV_OUT	TINYINT,

		@USED_YM	VARCHAR (40),
		@USED_M		INT,
		@USED_Y		INT,
		@USED_M1	INT

	SELECT @LINK_INV = INV_LINK,
		@dDOC_DATE = [DATE],
		@intDEP1 = DEP_R_LINK,
		@intDEP2 = DEP_P_LINK,
		@strTRANSFER = CONVERT (VARCHAR (20), TRANSFER),
		@LINK_ATT = TRUST_LINK
	FROM dbo.BV_DOC_OS1_VIEW
	WHERE LINK = @intLINK_DOC

	SELECT bv.*, i.CODE_GRP
	INTO #DOC_OS1 
	FROM dbo.BV_DOC_OS1_VIEW bv
	LEFT JOIN dbo.INVENTORY_CARD i ON i.link = bv.INV_LINK
	WHERE bv.LINK = @intLINK_DOC

	--- Вычисляем факт. срок экспл. в годах и месяцах ---
	SELECT @USED_M = DATEDIFF (MONTH, ASS.DATE_BEGIN, @dDOC_DATE)
	FROM dbo.ASSETS ASS
	WHERE LINK_UP = @LINK_INV

	SET @USED_M1 = @USED_M % 12
	IF @USED_M1 = 0
		SET @USED_Y = @USED_M / 12
	ELSE
		SET @USED_Y = (@USED_M - @USED_M1) / 12

	SELECT @USED_YM = LTRIM (STR (ISNULL (@USED_Y, 0))) + ' л. ' + 
			LTRIM (STR (ISNULL (@USED_M1, 0))) + ' мес. '

	DECLARE @TRUST_TABLE TABLE (LINK INT, ATT_NUM VARCHAR (10), ATT_DATE VARCHAR (10), ATT_EMP VARCHAR (254))
	INSERT INTO @TRUST_TABLE 
	SELECT LINK,
		NUMBER,
		CONVERT (VARCHAR (10), [DATE], 104),
		dbo.ku_GetEmplFIO (LINK_MOL)
	FROM dbo.DOCUMENTS_ATTORNEY 
	WHERE LINK = @LINK_ATT

	SELECT TOP 1 @cACCOUNT = CASE
					WHEN SA.LINK = T1.ACCT_DB THEN T1.ACCT_CD_D
					WHEN SA.LINK = T1.ACCT_KT THEN T1.ACCT_CD_K
					ELSE ''
				END
	FROM dbo.BK_PrintDocProv (@intLINK_DOC, DEFAULT) T1
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = T1.ACCT_DB
		OR SA.LINK = T1.ACCT_KT)
	WHERE SA.cSINTH LIKE '10[1-3]' OR SA.cSINTH = '108'

	IF @strTRANSFER = 'Передача'
		SET @dDATE_REST = @dDOC_DATE
	ELSE 
		SET @dDATE_REST = DATEADD (DAY, 1, @dDOC_DATE)

	SELECT @intINV_OUT = CASE WHEN @strTRANSFER = 'Передача' THEN 1 ELSE 0 END

	SELECT @BALANSE = dbo.RestOSByDate(DEFAULT, @LINK_INV, @dDATE_REST),
		@AMORT = dbo.RestOSDepreByDate(DEFAULT, @LINK_INV, @dDATE_REST)

	-- Основные данные --
	SELECT DOC.LINK AS LINK_DOC,
		ISNULL (DOC.NUMBER, '') AS DOC_NUM, 
		ISNULL (CONVERT (VARCHAR (10), DOC.[DATE], 104), '') AS DOC_DATE, 
		CASE WHEN @intINV_OUT = 0
				THEN ISNULL (CONVERT (VARCHAR (10), DOC.[DATE_PROV], 104), '')
			ELSE ''	
		END AS DATE_IN,
		CASE WHEN @intINV_OUT = 1
				THEN ISNULL (CONVERT (VARCHAR (10), DOC.[DATE_PROV], 104), '')
			ELSE ''	
		END AS DATE_OUT,
		ISNULL (@cACCOUNT, '') AS ACCT_CODE,
		ISNULL (dbo.BK_GET_PRINT_DEP_NAME (DOC.DEP_R_LINK), '') AS DEP_NAME1,
		ISNULL (DEP1.OKPO, '') AS OKPO1,
		ISNULL (DEP1.KPP, '') AS KPP1,
		ISNULL (DEP1.INN, '') AS INN1,
		ISNULL (dbo.GetAddressByDepLink (DOC.DEP_R_LINK, 1), '') AS ADDRESS1,
		ISNULL (dbo.BK_ACCOUNT_DEP_INFO (DOC.DEP_R_LINK), '') AS BANK1,
		ISNULL (dbo.BK_GET_PRINT_DEP_NAME (DOC.DEP_P_LINK), '') AS DEP_NAME2,
		ISNULL (DEP2.OKPO, '') AS OKPO2,
		ISNULL (DEP2.KPP, '') AS KPP2,
		ISNULL (DEP2.INN, '') AS INN2,
		ISNULL (dbo.GetAddressByDepLink (DOC.DEP_P_LINK, 1), '') AS ADDRESS2,
		ISNULL (dbo.BK_ACCOUNT_DEP_INFO (DOC.DEP_P_LINK), '') AS BANK2,
		ISNULL (DOC.INV_CODE, '') AS INV_CODE,
		ISNULL (DOC.INV_NAME, '') AS INV_NAME,
		GRP_TYPE = CASE WHEN left(isnull(DOC.CODE_GRP,''),4) = '1011' then 'недвижимое имущество'
						WHEN LEFT(ISNULL(DOC.CODE_GRP,''),4) = '1012' then 'особо ценное движимое имущество' 
						WHEN LEFT(ISNULL(DOC.CODE_GRP,''),4) = '1013' then 'иное движимое имущество' 
					 ELSE 	''
	                END ,
		ISNULL (CONVERT (VARCHAR (10), DOC.TRIAL_DATE, 104), '') AS DATE_TRIAL,
		ISNULL (EXPECTATION, 0) AS EXPECT,
		CASE WHEN EXPECTATION = 1 THEN ISNULL (CONVERT (VARCHAR (254), NOEXPECT), '') 
			ELSE ''
		END AS NOEXPECT,
		ISNULL (REWORK, 0) AS REWORK,
		CASE WHEN REWORK = 1 THEN ISNULL (CONVERT (VARCHAR (254), REWORK_DESC), '') 
			ELSE ''
		END AS REWORK_INF,
		ISNULL (CONVERT (VARCHAR (254), ENCLOSURE), '') AS TECH_DOC,
		ISNULL (CONVERT (VARCHAR (254), CONCLUSION), '') AS RESUM, 
--		ISNULL (DOC.OSNOV_INFO, '') AS BASED,
		ISNULL (OSN.TYPE, '') AS BASED,
		ISNULL (OSN.NUMBER, '') AS BASE_NUM,
		ISNULL (CONVERT (VARCHAR (10), OSN.[DATE], 104), '') AS BASE_DATE,
		ISNULL (GR_O.CODE, '') AS CODE_OKOF,
		ISNULL (GR_W.CODE, '') AS CODE_RATE,
		ISNULL (ASS.PLANT_NUM, '') AS NUMBER_F,
		ISNULL (ASS.OTHER_NUM, '') AS NUMBER_O,
		ISNULL (ASS.PASSPORT,'') AS PASSP, 
		ISNULL (ASS.MANUFACT, '')  AS MANUFACT,
		ISNULL (ASS.FIXING, '') AS FIXING,
		CASE WHEN @intINV_OUT = 0 THEN ISNULL (ASS.CARD_NO, '') ELSE '' END AS CARD_NO,
		CASE WHEN @intINV_OUT = 0
				THEN ISNULL (CONVERT (VARCHAR (10), ASS.DATE_FILLING, 104), '')
			ELSE ''
		END AS DATE_FIL,
		ISNULL (CONVERT (VARCHAR (10), ASS.DATE_PROD, 104), '') AS DATE_PROD,
		ISNULL (CONVERT (VARCHAR (10), ASS.DATE_BEGIN, 104), '') AS DATE_BEGIN,
		DATEDIFF (YEAR, ASS.DATE_BEGIN, DOC.[DATE]) AS ALL_USED,
		ISNULL (GR_W.VALUE, 0) AS PER_USED,
		ISNULL ((SELECT [NAME] FROM dbo.BV_DICTIONARY_DEPRE_METHOD WHERE VALUE = ASS.WEAR_FLAG), '') AS DEPRE_NAME,
		ISNULL (ND.DEPRE_RATE, 0) AS DEPRE_RATE,
		ISNULL (@AMORT, 0 ) AS REST_AMORT,
		ISNULL (@BALANSE, 0 ) AS BALANSE,
		ISNULL (@BALANSE, 0 ) - ISNULL (@AMORT, 0 ) AS LAST_COST,
		ISNULL (CHIEF1.SHORT_NAME, '') AS CHIEF1,
		ISNULL (CHIEF1.POST_NAME, '') AS CHPOST1,
		ISNULL (CHIEF2.SHORT_NAME, '') AS CHIEF2,
		ISNULL (CHIEF2.POST_NAME, '') AS CHPOST2,
		ISNULL (BUH1.SHORT_NAME, '') AS GLBUH1,
		ISNULL (BUH1.POST_NAME, '') AS GLPOST1,
		ISNULL (BUH2.SHORT_NAME, '') AS GLBUH2,
		ISNULL (BUH2.POST_NAME, '') AS GLPOST2,
		ISNULL (DOC.EMP_R_CODE, '') AS EMP_TAB1,
		dbo.BK_Get_EMPL_Signature (DOC.EMP_R_LINK, DEFAULT) AS EMP_NAME1,
		ISNULL (dbo.ku_GetEmplPostName (EMP_R_LINK, DOC.[DATE]), '') AS EMP_POST1,
		ISNULL (DOC.EMP_P_CODE, '') AS EMP_TAB2,
		dbo.BK_Get_EMPL_Signature (DOC.EMP_P_LINK, DEFAULT) AS EMP_NAME2,
		ISNULL (dbo.ku_GetEmplPostName (EMP_P_LINK, DOC.[DATE]), '') AS EMP_POST2,
		ISNULL (DOC.MOL_R_CODE, '') AS EMP_CD_R,
		dbo.BK_Get_EMPL_Signature (DOC.MOL_R_LINK, DEFAULT) AS EMP_NM_R,
		ISNULL (dbo.ku_GetEmplPostName (MOL_R_LINK, DOC.[DATE]), '') AS EMP_POST_R,
		ISNULL (D_ATT.ATT_DATE, '') AS ATT_DATE,
		ISNULL (D_ATT.ATT_NUM, '') AS ATT_NUM,
		ISNULL (D_ATT.ATT_EMP, '') AS ATT_EMP,
		@USED_YM AS USED_YM
	FROM #DOC_OS1 DOC

	LEFT JOIN dbo.DEPARTMENTS DEP1 ON (DOC.DEP_R_LINK = DEP1.LINK)
	LEFT JOIN dbo.DEPARTMENTS DEP2 ON (DOC.DEP_P_LINK = DEP2.LINK)

	LEFT JOIN dbo.ASSETS ASS ON (ASS.LINK_UP = DOC.INV_LINK)
	LEFT JOIN dbo.ASSETS_GROUP_OKOF GR_O ON (GR_O.LINK = ASS.OKOF)
	LEFT JOIN dbo.DEPRE_GROUP GR_W ON (GR_W.LINK = ASS.DEPRE_GROUP)
	LEFT JOIN dbo.BD_OSNOV OSN ON (OSN.LINK = DOC.OSNOV_LINK)
	LEFT JOIN dbo.GetOtvFaceData (@intDEP1, 'РУКОВОДИТЕЛЬ') CHIEF1
			ON (CHIEF1.LINK_DEP = DOC.DEP_R_LINK)
	LEFT JOIN dbo.GetOtvFaceData (@intDEP2, 'РУКОВОДИТЕЛЬ') CHIEF2
			ON (CHIEF2.LINK_DEP = DOC.DEP_P_LINK)
	LEFT JOIN dbo.GetOtvFaceData (@intDEP1, 'ГЛАВНЫЙ БУХГАЛТЕР') BUH1
			ON (BUH1.LINK_DEP = DOC.DEP_R_LINK)
	LEFT JOIN dbo.GetOtvFaceData (@intDEP2, 'ГЛАВНЫЙ БУХГАЛТЕР') BUH2
			ON (BUH2.LINK_DEP = DOC.DEP_P_LINK)
	LEFT JOIN dbo.BK_GetNormDepreTableByOS (@LINK_INV) ND ON (ND.INV = DOC.INV_LINK)
	LEFT JOIN @TRUST_TABLE D_ATT ON (D_ATT.LINK = DOC.TRUST_LINK)
	WHERE DOC.LINK = @intLINK_DOC

	-- Характеристика --
	DECLARE @TAB_CHAR1 TABLE
		(RECNO INT IDENTITY,
		LINK_UP INT,
		NAME_OBJ VARCHAR (254),
		QTY NUMERIC (10,2))

	INSERT INTO @TAB_CHAR1 (LINK_UP, NAME_OBJ, QTY)
	SELECT LINK_UP,
		CONVERT (VARCHAR (254), BASIC_OBJ),
		QTY
	FROM dbo.BV_DICTIONARY_SHORT_DESC 
	WHERE LINK_UP = @LINK_INV

	-- Драг. металлы --
	DECLARE @TAB_DRAG TABLE (RECNO INT IDENTITY, LINK_UP INT,
			DR_CODE VARCHAR (20), DR_NAME VARCHAR (254),
			UM_CODE VARCHAR (20), WEIGTH NUMERIC (20,6))

	INSERT INTO @TAB_DRAG (LINK_UP, DR_CODE, DR_NAME, UM_CODE, WEIGTH)
	SELECT LINK_UP,
		CONVERT (VARCHAR (20), CODE_PREC),
		CONVERT (VARCHAR (254), NAME_PREC),
		CONVERT (VARCHAR (20), CODE_UM),
		CONVERT (NUMERIC (20,6), WEIGTH)
	FROM dbo.BV_DICTIONARY_PRECIOUS_CONTENT
	WHERE LINK_UP = @LINK_INV

	DECLARE @TAB_CHAR_OUT TABLE
		(TABNO_ID INT IDENTITY,
		TAB_NO INT,
		NAME_OBJ VARCHAR (254),
		QTY NUMERIC (10,2),
		DR_CODE VARCHAR (20), DR_NAME VARCHAR (254),
		UM_CODE VARCHAR (20), WEIGTH NUMERIC (20,6),
		OTHER_CHAR VARCHAR (1000))

	INSERT INTO @TAB_CHAR_OUT (TAB_NO, NAME_OBJ, QTY, 
		DR_CODE, DR_NAME, UM_CODE, WEIGTH, OTHER_CHAR)

	SELECT 1,
		ISNULL (C1.NAME_OBJ, ''),
		ISNULL (C1.QTY, 0),
		ISNULL (DR1.DR_CODE, ''),
		ISNULL (DR1.DR_NAME, ''),
		ISNULL (DR1.UM_CODE, ''),
		ISNULL (DR1.WEIGTH, 0),
		''
	FROM @TAB_CHAR1 C1
	FULL JOIN @TAB_DRAG DR1 ON (DR1.LINK_UP = C1.LINK_UP
		AND DR1.RECNO = C1.RECNO)

	IF @@ROWCOUNT = 0
		INSERT INTO @TAB_CHAR_OUT (TAB_NO, NAME_OBJ, QTY, 
			DR_CODE, DR_NAME, UM_CODE, WEIGTH, OTHER_CHAR)
		SELECT 1, '', 0, '', '', '', 0, ''

	--- Другие хар-ки объекта ---
	INSERT INTO @TAB_CHAR_OUT (TAB_NO, NAME_OBJ, QTY, 
		DR_CODE, DR_NAME, UM_CODE, WEIGTH, OTHER_CHAR)
	SELECT 2,
		'',
		0,
		'',
		'',
		'',
		0,
		STR_ATTR
	FROM dbo.BK_GET_STR_SHORT_DESC (@LINK_INV)

	IF @@ROWCOUNT = 0
		INSERT INTO @TAB_CHAR_OUT (TAB_NO, NAME_OBJ, QTY, 
			DR_CODE, DR_NAME, UM_CODE, WEIGTH, OTHER_CHAR)
		SELECT 2, '', 0, '', '', '', 0, ''

	SELECT  * FROM @TAB_CHAR_OUT
	ORDER BY TAB_NO

	DROP TABLE #DOC_OS1
END



GO


GRANT EXECUTE ON dbo.[BK_PRINTDOC_OS1] TO PUBLIC

GO



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

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


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

create  procedure dbo.BB_CREDIT_CARD_DOLG
	@cBufId 	char(100),
	@dDateB 	datetime,
	@dDateE 	datetime,
	@iAcc207 	tinyint,
	@iTypeRep 	tinyint = 1,
	@iDepLink 	int = 0,
	@iPrintKBK TINYINT,
	@iPrintSGU TINYINT,
	@cVal1 		char(1), 
	@nOtborLink1 	int,
	@cVal2 		char(1), 
	@nOtborLink2 	int
	

as
/*
select '@cBufId' = @cBufId 	,
	'@dDateB' = @dDateB 	,
	'@dDateE' = @dDateE 	,
	'@iAcc207' = @iAcc207 	,
	'@iTypeRep' = @iTypeRep 	,
	'@iDepLink' = @iDepLink 	,
	'@iPrintKBK' = @iPrintKBK ,
	'@iPrintSGU' = @iPrintSGU ,
	'@cVal1' = @cVal1 		, 
	'@nOtborLink1' = @nOtborLink1 	,
	'@cVal2' = @cVal2 		, 
	'@nOtborLink2' = @nOtborLink2*/
declare @iOwnDep	int,
		@dDateRest  datetime
	
declare @tRest table(DEP int,
		      		 DT_ACC varchar(35), 
					 KT_ACC varchar(35),
					 GRUP	int,
					 [TYPE]	tinyint,
					 SUMMA numeric(28,2))

declare @tAccTemp1 table(LINK int,
						 ACC int,
						 KBK int,
						 SGU int)

declare @tAccTemp2 table(LINK int,
						 ACC int,
						 KBK int,
						 SGU int)

declare @tDocAccCode table(LINK int,
						 DT_ACC varchar(40),
						 KT_ACC varchar(40))

set @iOwnDep = isnull (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())
set @iDepLink = isnull(@iDepLink,0)
if @cBufId is null or @cBufId = ''
begin
	set @cBufId = 'BB_DOLG'
	exec dbo.BufferClear @cBufId
	
	insert into BUFFER (link, id)
	select C.link, @cBufId 
	from BB_P_CREDIT C
	where C.DEP_LINK = @iOwnDep and 
			C.DATE_BEG <= @dDateE and C.DATE_END >= @dDateB and
	      (@iDepLink <> 0 and C.KDEP_LINK = @iDepLink or 
			(@iDepLink = 0 and (len(@cVal1) = 0  or len(@cVal1) <> 0 
			and EXISTS (select * from dbo.OBJECT_VAR_DEPARTMENT OVD where OVD.RECORD = C.KDEP_LINK AND OVD.LINK_UP = @nOtborLink1)))) 

			/*inner join dbo.OBJECT_VAR_CREDIT_TYPE OVC on OVC.RECORD = CH.TYPE AND OVC.LINK_UP = @nOtborLink2*/ 
	
end
IF @dDateB IS NULL
	select @dDateB = MIN(DATE)
	from G_PROV 
	where OBJECT in (select link from S_OBJECTS WHERE CODE = 'BB_P_CREDIT') and 
		(@cBufId is null or @cBufId = '' or link in (select * from dbo.BufferGetTableByID(@cBufId))) and
		DEP = @iOwnDep
IF @dDateE IS NULL
	select @dDateE = MAX(dbo.BB_CREDIT_DATE_END(LINK, default, default))
	from G_PROV 
	where OBJECT in (select link from S_OBJECTS WHERE CODE = 'BB_P_CREDIT') and
		(@cBufId is null or @cBufId = '' or link in (select * from dbo.BufferGetTableByID(@cBufId))) and
		DEP = @iOwnDep

exec dbo.BufferClear 'CREDIT_ACC'
exec dbo.BufferClear 'CREDIT_PER_D'
exec dbo.BufferClear 'CREDIT_PL_N'
exec dbo.BufferClear 'CREDIT_DOH_N'
exec dbo.BufferClear 'OSNOV'
exec dbo.BufferClear 'SGU_D'
exec dbo.BufferClear 'SGU_K'
exec dbo.BufferClear 'SGU_K_P'
exec dbo.BufferClear 'SGU_K_KL_N'

insert into BUFFER (link, id)
select link, 'CREDIT_ACC' from s_accounts where code like '%301.%'

insert into BUFFER (link, id)
select link, 'CREDIT_PER' from s_accounts where code like '%210.02%' or code like '%201.07%' or code like '%201.11%' or code like '%401.30%' or code like '%301.%'

insert into BUFFER (link, id)
select link, 'CREDIT_PL' from s_accounts where code like '%304.05%' or code like '%201.07%' or code like '%201.11%'or code like '%301.%'

insert into BUFFER (link, id)
select link, 'CREDIT_PL_N' from s_accounts where code like '%401.[1-2]0%'

insert into BUFFER (link, id)
select O.LINK, 'OSNOV' 
from dbo.BD_OSNOV O
inner join dbo.G_PROV G on G.LINK = O.DOC_LINK and G.LINK in (select * from dbo.BufferGetTableByID(@cBufId))

insert into BUFFER (link, id)
select link, 'SGU_D' from dbo.KOSGU where CODE like '8%'

insert into BUFFER (link, id)
select link, 'SGU_K' from dbo.KOSGU where CODE like '7%'

insert into BUFFER (link, id)
select link, 'SGU_K_P' from dbo.KOSGU where CODE like '23%'

insert into BUFFER (link, id)
select link, 'SGU_K_PL_N' from dbo.KOSGU where CODE like '171'


insert into @tAccTemp1
select isnull(KT_AP1, DT_AP1), KT_ACCOUNT, KT_KBK, KT_SGU 
from dbo.AProvByBufferConditions('19000101', '29991231', 'CREDIT_PER', 'CREDIT_ACC', null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,null,null,null,null,null,null,null,null,null,null,'SGU_K',null,'OSNOV', null,null) 
/*
insert into @tAccTemp2
select isnull(DT_AP1, KT_AP1), DT_ACCOUNT, DT_KBK, DT_SGU
from dbo.AProvByBufferConditions('19000101', '29991231', 'CREDIT_ACC', 'CREDIT_PL', null,null,null,null,null,null,null,null,null,null,'SGU_D',null,'OSNOV', null,null,null,null,null,null,null,null,null,null,null,null,NULL,null,null, null,null)
*/
delete T
from @tAccTemp1 T
where exists(SELECT * from @tAccTemp1 T1 where T.LINK = T1.LINK and T.ACC <> T1.ACC)
and exists(SELECT * from dbo.S_ACCOUNTS SA where T.ACC = SA.LINK and SA.cSinth = '301' and left(SA.cAnalit,1) = '0')
/*
delete T
from @tAccTemp2 T
where exists(SELECT * from @tAccTemp2 T1 where T.LINK = T1.LINK and T.ACC <> T1.ACC)
and exists(SELECT * from dbo.S_ACCOUNTS SA where T.ACC = SA.LINK and SA.cSinth = '301' and left(SA.cAnalit,1) = '0')
*/
insert into @tDocAccCode
select distinct O.DOC_LINK, 
				isnull(dbo.BK_GetAcctFullCode1 (T1.ACC, T1.KBK, T1.SGU, @iPrintKBK, @iPrintSGU),''),
				isnull(dbo.BK_GetAcctFullCode1 (T2.ACC, T2.KBK, T2.SGU, @iPrintKBK, @iPrintSGU),'')
from dbo.BD_OSNOV O 
inner join @tAccTemp1 T1 on T1.LINK = O.LINK
left join @tAccTemp2 T2 on T2.LINK = O.LINK

	
	
-- Раздел 1
declare @tTempRasdel1 table(OBJECT		varchar(254),
							LINK	int,
							DOC_NUM		char(25),
							DOC_DATE	datetime,
							OPER_NAME	varchar(254),
							OPER_DATE	datetime,
							SUM_PER		numeric(28,2),
							SUM_PL		numeric(28,2),
							SUM_PR 		numeric(28,2),
							DEP			int,
		      				DOC_LINK	int)

declare @tRasdel1 table(TYPE		int,
		      			ACC_CODE1 varchar(35),
		      			ACC_CODE2 varchar(35),
		      			DOC_NAME	varchar(254),
						DOC_NUM		char(25),
						DOC_DATE	datetime,
						OPER_NAME	varchar(254),
						OPER_DATE	datetime,
						SUM_PER		numeric(28,2),
						SUM_PL		numeric(28,2),
						SUM_PR 		numeric(28,2),
						SORT		tinyint,
						P_LINK		int,
						DOC_LINK	int,
						GRUP		INT)



insert into @tTempRasdel1
select S.DOC_OBJECT, S.LINK, S.NUMBER, S.DOC_DATE, S.NAME_OPER, S.DATE_PROV,S.SUMMA, 0, 0, isnull(S.KT_DEP, S.DT_DEP), isnull(S.KT_AP1, S.DT_AP1)
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_PER', 'CREDIT_ACC',
			 null,null,null,null,null,null,null,null,null,null,null,null,null, null,null,
			 null,null,null,null,null,null,null,null,null,null,'SGU_K',null,'OSNOV', null,null) S
union
select S.DOC_OBJECT, S.LINK, S.NUMBER, S.DOC_DATE, S.NAME_OPER, S.DATE_PROV, 0,S.SUMMA,  0, isnull(S.KT_DEP, S.DT_DEP), isnull(S.DT_AP1, S.KT_AP1)
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_ACC', 'CREDIT_PL',
			 null,null,null,null,null,null,null,null,null,null,'SGU_D',null,'OSNOV', null,null,
			 null,null,null,null,null,null,null,null,null,null,'SGU_D',null,null, null,null) S
union
select S.DOC_OBJECT, S.LINK, S.NUMBER, S.DOC_DATE, S.NAME_OPER, S.DATE_PROV, 0, 0, S.SUMMA, isnull(S.KT_DEP, S.DT_DEP), isnull(S.DT_AP1, S.KT_AP1)
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_ACC', 'CREDIT_PL_N',
				 null,null,null,null,null,null,null,null,null,null,'SGU_D',null,'OSNOV', null,null,
				 null,null,null,null,null,null,null,null,null,null,'SGU_K_PL_N',null,null, null,null) S
union
select S.DOC_OBJECT, S.LINK, S.NUMBER, S.DOC_DATE, S.NAME_OPER, S.DATE_PROV, 0, 0, S.SUMMA, isnull(S.KT_DEP, S.DT_DEP), isnull(S.KT_AP1, S.DT_AP1)
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_PL_N', 'CREDIT_ACC',
				 null,null,null,null,null,null,null,null,null,null,'SGU_K_PL_N',null,null, null,null,
				 null,null,null,null,null,null,null,null,null,null,'SGU_K',null,'OSNOV', null,null) S



-- Раздел 2
declare @tTempRasdel2 table(OBJECT	varchar(254),
							LINK	int,
							DOC_NUM	char(25),
							DOC_DATE	datetime,
							OPER_NAME	varchar(254),
							OPER_DATE	datetime,
							SUM_PER	numeric(28,2),
							SUM_PL	numeric(28,2),
							SUM_PR 	numeric(28,2),
							DEP			int,
		      				DOC_LINK	int,
		      				ACC_CODE varchar(35))

declare @tRasdel2 table(TYPE		int,
		      			ACC_CODE varchar(35),
						ACC_CODE1 varchar(35),
						ACC_CODE2 varchar(35),
						DOC_NAME	varchar(254),
						DOC_NUM		char(25),
						DOC_DATE	datetime,
						OPER_NAME	varchar(254),
						OPER_DATE	datetime,
						SUM_PER		numeric(28,2),
						SUM_PL		numeric(28,2),
						SUM_PR 		numeric(28,2),
						SORT		tinyint,
						P_LINK		int,
						DOC_LINK	int,
						GRUP		INT)

insert into @tTempRasdel2
select S.DOC_OBJECT, S.LINK, S.NUMBER, S.DOC_DATE, S.NAME_OPER, S.DATE_PROV, S.SUMMA, 0, 0, isnull(S.KT_DEP, S.DT_DEP), isnull(S.KT_AP1, S.DT_AP1), dbo.BK_GetAcctFullCode1 (KT_ACCOUNT, KT_KBK, KT_SGU, @iPrintKBK, @iPrintSGU)
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_PL_N', 'CREDIT_ACC',
				 null,null,null,null,null,null,null,null,null,null,'SGU_K_P',null,null, null,null,
				 null,null,null,null,null,null,null,null,null,null,'SGU_K',null,'OSNOV', null,null) S
union
select S.DOC_OBJECT, S.LINK, S.NUMBER, S.DOC_DATE, S.NAME_OPER, S.DATE_PROV, 0,S.SUMMA, 0, isnull(S.KT_DEP, S.DT_DEP), isnull(S.DT_AP1, S.KT_AP1), dbo.BK_GetAcctFullCode1 (DT_ACCOUNT, DT_KBK, DT_SGU, @iPrintKBK, @iPrintSGU)
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_ACC', 'CREDIT_PL',
				 null,null,null,null,null,null,null,null,null,null,'SGU_D',null,'OSNOV', null,null,
				 null,null,null,null,null,null,null,null,null,null,'SGU_K_P',null,null, null,null) S
union
select S.DOC_OBJECT, S.LINK, S.NUMBER, S.DOC_DATE, S.NAME_OPER, S.DATE_PROV, 0,S.SUMMA, 0, isnull(S.KT_DEP, S.DT_DEP), isnull(S.DT_AP1, S.KT_AP1), dbo.BK_GetAcctFullCode1 (DT_ACCOUNT, DT_KBK, DT_SGU, @iPrintKBK, @iPrintSGU)
from dbo.AProvByBufferConditions(@dDateB, @dDateE, 'CREDIT_ACC', 'CREDIT_ACC',
				 null,null,null,null,null,null,null,null,null,null,'SGU_D',null,'OSNOV', null,null,
				 null,null,null,null,null,null,null,null,null,null,'SGU_K',null,'OSNOV', null,null) S



if @iAcc207 = 0
begin
	insert into @tRest
	select C.KDEP_LINK,  A.DT_ACC, A.KT_ACC, case @iTypeRep when 1 then C.KDEP_LINK when 2 then C.TYPE when 3 then C.LINK  else null end, 0, sum(dbo.BB_CREDIT_REST(C.LINK, @dDateB,0))
	from dbo.BB_P_CREDIT C 
	left join @tDocAccCode A on A.LINK = C.LINK 
	where exists(select * from dbo.BufferGetTableByID(@cBufId) where LINK = C.LINK)
	group by C.KDEP_LINK,   A.DT_ACC, A.KT_ACC, case @iTypeRep when 1 then C.KDEP_LINK when 2 then C.TYPE when 3 then C.LINK  else null end
	
	insert into @tRest
	select C.KDEP_LINK, A.DT_ACC, A.KT_ACC, case @iTypeRep when 1 then C.KDEP_LINK when 2 then C.TYPE when 3 then C.LINK  else null end, 2, sum(dbo.BB_CREDIT_REST(C.LINK, @dDateE,0))
	from dbo.BB_P_CREDIT C 
	left join @tDocAccCode A on A.LINK = C.LINK 
	where exists(select * from dbo.BufferGetTableByID(@cBufId) where LINK = C.LINK)
	group by C.KDEP_LINK,  A.DT_ACC, A.KT_ACC, case @iTypeRep when 1 then C.KDEP_LINK when 2 then C.TYPE when 3 then C.LINK  else null end
	
	insert into @tRest
	select  C.KDEP_LINK, A.DT_ACC, A.KT_ACC, case @iTypeRep when 1 then C.KDEP_LINK when 2 then C.TYPE when 3 then C.LINK  else null end, 1,
			sum(dbo.BB_CREDIT_SUM_REST(C.LINK, @dDateB,'PROC','') + 
				 dbo.BB_CREDIT_SUM_REST(C.LINK, @dDateB,'SH_NECELEV','') + 
				 dbo.BB_CREDIT_SUM_REST(C.LINK, @dDateB,'SH_CREDIT','') + 
				 dbo.BB_CREDIT_SUM_REST(C.LINK, @dDateB,'SH_PROC',''))
	from dbo.BB_P_CREDIT C
	left join @tDocAccCode A on A.LINK = C.LINK 
	where exists(select * from dbo.BufferGetTableByID(@cBufId) where LINK = C.LINK)
	group by C.KDEP_LINK,  A.DT_ACC, A.KT_ACC, case @iTypeRep when 1 then C.KDEP_LINK when 2 then C.TYPE when 3 then C.LINK  else null end

	insert into @tRest
	select C.KDEP_LINK,   A.DT_ACC, A.KT_ACC, case @iTypeRep when 1 then C.KDEP_LINK when 2 then C.TYPE when 3 then C.LINK  else null end, 3,
			sum(dbo.BB_CREDIT_SUM_REST(C.LINK, @dDateE,'PROC','') + 
				 dbo.BB_CREDIT_SUM_REST(C.LINK, @dDateE,'SH_NECELEV','') + 
				 dbo.BB_CREDIT_SUM_REST(C.LINK, @dDateE,'SH_CREDIT','') + 
				 dbo.BB_CREDIT_SUM_REST(C.LINK, @dDateE,'SH_PROC',''))
	from dbo.BB_P_CREDIT C
	left join @tDocAccCode A on A.LINK = C.LINK 
	where exists(select * from dbo.BufferGetTableByID(@cBufId) where LINK = C.LINK)
	group by C.KDEP_LINK, A.DT_ACC, A.KT_ACC, case @iTypeRep when 1 then C.KDEP_LINK when 2 then C.TYPE when 3 then C.LINK  else null end

end
else
begin
	insert into @tRest
	select R.DEP, A.DT_ACC, A.KT_ACC, case @iTypeRep when 1 then R.DEP when 2 then C.TYPE when 3 then O.DOC_LINK  else null end,
				case KBK.TYPE when 1 then 1 else 0 end, 
				sum(R.K_SUMMA - R.D_SUMMA) 
		from dbo.aRestTableByDateAccounts(@dDateB,'CREDIT_ACC') R
		inner join dbo.KL_KBK KBK on R.KBK = KBK.LINK --and KBK.TYPE <> 2
		inner join dbo.BD_OSNOV O on R.AP1 = O.LINK  
		inner join dbo.BB_P_CREDIT C on C.LINK = O.DOC_LINK 
		left join @tDocAccCode A on A.LINK = C.LINK 
		where exists(select * from dbo.BufferGetTableByID(@cBufId) where LINK = C.LINK)
		group by R.DEP,A.DT_ACC, A.KT_ACC, case @iTypeRep when 1 then R.DEP when 2 then C.TYPE when 3 then O.DOC_LINK  else null end, KBK.TYPE
set @dDateE = @dDateE + 1
	insert into @tRest
	select R.DEP, A.DT_ACC, A.KT_ACC, case @iTypeRep when 1 then R.DEP when 2 then C.TYPE when 3 then O.DOC_LINK  else null end,
				2 + case KBK.TYPE when 1 then 1 else 0 end , 
				sum(R.K_SUMMA - R.D_SUMMA) 
		from dbo.aRestTableByDateAccounts(@dDateE,'CREDIT_ACC') R
		inner join dbo.KL_KBK KBK on R.KBK = KBK.LINK --and KBK.TYPE <> 2
		left join dbo.BD_OSNOV O on R.AP1 = O.LINK  
		inner join dbo.BB_P_CREDIT C on C.LINK = O.DOC_LINK 
		left join @tDocAccCode A on A.LINK = C.LINK 
		where exists(select * from dbo.BufferGetTableByID(@cBufId) where LINK = C.LINK)
		group by R.DEP, A.DT_ACC, A.KT_ACC, case @iTypeRep when 1 then R.DEP when 2 then C.TYPE when 3 then O.DOC_LINK  else null end, KBK.TYPE
end

insert into @tRasdel1
select  C.TYPE,
		A.DT_ACC, 
		A.KT_ACC, 
		DOC_NAME	= dbo.JurnalProvGetDocKind (S.LINK, S.OBJECT),
		DOC_NUM		= S.DOC_NUM,
		DOC_DATE	= S.DOC_DATE,
		S.OPER_NAME,
		S.OPER_DATE,
		S.SUM_PER,
		S.SUM_PL,
		S.SUM_PR,
		SORT		= 2,
		C.KDEP_LINK,
		C.LINK,
		GPUP = case @iTypeRep when 1 then isnull(C.KDEP_LINK, S.DEP)
								when 2 then isnull(C.TYPE, '')
								when 3 then O.DOC_LINK else '' end
from @tTempRasdel1 S
left join dbo.BD_OSNOV O on S.DOC_LINK = O.LINK
left join dbo.BB_P_CREDIT C on C.LINK = O.DOC_LINK and C.LINK in (select * from dbo.BufferGetTableByID(@cBufId))
left join @tDocAccCode A on A.LINK = O.DOC_LINK 

/*
select * from @tTempRasdel1 S
left join dbo.BD_OSNOV O on S.DOC_LINK = O.LINK
where O.DOC_LINK = 92167

select * from @tDocAccCode where LINK = 92167
*/
--select * from @tTempRasdel2

insert into @tRasdel2
select  C.TYPE,
		S.ACC_CODE,
		A.DT_ACC, 
		A.KT_ACC, 
		DOC_NAME	= dbo.JurnalProvGetDocKind (S.LINK, S.OBJECT),
		DOC_NUM		= S.DOC_NUM,
		DOC_DATE	= S.DOC_DATE,
		S.OPER_NAME,
		S.OPER_DATE,
		S.SUM_PER,
		S.SUM_PL,
		S.SUM_PR,
		SORT		= 2,
		C.KDEP_LINK,
		C.LINK,
		GPUP = case @iTypeRep when 1 then isnull(C.KDEP_LINK, S.DEP)
								when 2 then isnull(C.TYPE, '')
								when 3 then O.DOC_LINK else '' end
from @tTempRasdel2 S
left join dbo.BD_OSNOV O on S.DOC_LINK = O.LINK
left join dbo.BB_P_CREDIT C on C.LINK = O.DOC_LINK and C.LINK in (select * from dbo.BufferGetTableByID(@cBufId))
left join @tDocAccCode A on A.LINK = O.DOC_LINK 


--declare @tDocTable table(DOC_LINK	int, POL_LINK	int, TYPE int)
declare @tDocTable table( ACC_CODE1 varchar(35), ACC_CODE2 varchar(35), DEP int, GRUP int)

insert into @tDocTable
select ACC_CODE1, ACC_CODE2, P_LINK, GRUP from @tRasdel2 union
select ACC_CODE1, ACC_CODE2, P_LINK, GRUP from @tRasdel1 union
select DT_ACC, KT_ACC, DEP, GRUP from @tRest
/*
select * from @tDocTable  where GRUP = 92167
select * from @tRasdel2  where GRUP = 92167
select * from @tRasdel1  where GRUP = 92167
select * from @tRest where GRUP = 92167
*/

--select * from @tRest

select 	--DOC_LINK = DT.DOC_LINK,
		DOC_NAME = isnull(R.DOC_NAME,''),
		DOC_NUM = isnull(R.DOC_NUM,''),
		R.DOC_DATE,
		SUM_REST_B = isnull(RB.SUMMA,0),
		SUM_REST_E = isnull(RE.SUMMA,0),
		OPER_NAME = isnull(R.OPER_NAME,''),
		R.OPER_DATE,
		SUM_PER = isnull(R.SUM_PER,0),
		SUM_PL = isnull(R.SUM_PL,0),
		SUM_PR = isnull(R.SUM_PR,0),
		P_LINK = D.LINK, 
		P_CODE = D.CODE, 
		P_NAME = D.[NAME], 
		--DT.TYPE, 
		DATE_B = C.DATE_BEG,
		DATE_E = C.DATE_END,
		DT.ACC_CODE1,
		DT.ACC_CODE2,
		TYPE_CODE = coalesce(CT.CODE,C.TYPE_CODE), 
		[TYPE_NAME] = coalesce(CT.[NAME], rtrim(C.[TYPE_NAME]) + ' (договор №' + rtrim(ltrim(C.NUMBER)) + ')'),
		GRUP = rtrim(str(DT.DEP)) + '__' + rtrim(str(DT.GRUP)) + '__' +  isnull(DT.ACC_CODE1,'') + '__' +  isnull(DT.ACC_CODE2,'')
from @tDocTable DT
inner join dbo.DEPARTMENTS D   on D.LINK = DT.DEP
left join dbo.BB_P_CREDIT C ON @iTypeRep = 3 and  C.LINK  = DT.GRUP
left join dbo.CREDIT_TYPES CT ON @iTypeRep = 2 and CT.LINK  = DT.GRUP
left join @tRasdel1 R on (DT.GRUP = R.GRUP or DT.GRUP is null and R.GRUP is null) and R.P_LINK = DT.DEP and isnull(R.ACC_CODE1,'') = isnull(DT.ACC_CODE1,'') and isnull(R.ACC_CODE2,'') = isnull(DT.ACC_CODE2,'')
left join @tRest RB on (DT.GRUP = RB.GRUP or DT.GRUP is null and RB.GRUP is null) and RB.DEP = DT.DEP and isnull(RB.DT_ACC,'') = isnull(DT.ACC_CODE1,'') and isnull(RB.KT_ACC,'') = isnull(DT.ACC_CODE2,'') and RB.[TYPE] = 0
left join @tRest RE on (DT.GRUP = RE.GRUP or DT.GRUP is null and R.GRUP is null) and RE.DEP = DT.DEP and isnull(RE.DT_ACC,'') = isnull(DT.ACC_CODE1,'') and isnull(RE.KT_ACC,'') = isnull(DT.ACC_CODE2,'') and RE.[TYPE] = 2
order by DT.GRUP, P_LINK,/* DOC_NAME,*/ R.DOC_DATE, SUM_PL, SORT


select 	--DOC_LINK = DT.DOC_LINK,
		DOC_NAME = isnull(R.DOC_NAME,''),
		DOC_NUM = isnull(R.DOC_NUM,''),
		R.DOC_DATE,
		SUM_REST_B = isnull(RB.SUMMA,0),
		SUM_REST_E = isnull(RE.SUMMA,0),
		SUM_R_B1 = isnull(RB1.SUMMA,0),
		SUM_R_E1 = isnull(RE1.SUMMA,0),
		OPER_NAME = isnull(R.OPER_NAME ,''),
		R.OPER_DATE,
		SUM_PER = isnull(R.SUM_PER,0),
		SUM_PL = isnull(R.SUM_PL,0),
		SUM_PR = isnull(R.SUM_PR,0),
		SUM_PER1 = isnull(R1.SUM_PER,0),
		SUM_PL1 = isnull(R1.SUM_PL,0),
		SUM_PR1 = isnull(R1.SUM_PR,0),
		P_LINK = D.LINK, 
		P_CODE = D.CODE, 
		P_NAME = D.[NAME], 
		--DT.TYPE, 
		R.ACC_CODE,
		TYPE_CODE = isnull(CT.CODE,''), 
		[TYPE_NAME] = coalesce(CT.[NAME], rtrim(C.[TYPE_NAME]) + ' (договор №' + rtrim(ltrim(C.NUMBER)) + ')'),
		GRUP = rtrim(str(DT.DEP)) + '__' + rtrim(str(DT.GRUP)) + '__' +  isnull(DT.ACC_CODE1,'') + '__' +  isnull(DT.ACC_CODE2,'')
from @tDocTable DT
inner join dbo.DEPARTMENTS D   on D.LINK = DT.DEP
left join dbo.BB_P_CREDIT C ON @iTypeRep = 3 and  C.LINK  = DT.GRUP
left join dbo.CREDIT_TYPES CT ON @iTypeRep = 2 and CT.LINK  = DT.GRUP
left join @tRasdel2 R on (DT.GRUP = R.GRUP or DT.GRUP is null and R.GRUP is null) and R.P_LINK = DT.DEP and isnull(R.ACC_CODE1,'') = isnull(DT.ACC_CODE1,'') and isnull(R.ACC_CODE2,'') = isnull(DT.ACC_CODE2,'')
left join @tRest RB on (DT.GRUP = RB.GRUP or DT.GRUP is null and RB.GRUP is null) and RB.DEP = DT.DEP and isnull(RB.DT_ACC,'') = isnull(DT.ACC_CODE1,'') and isnull(RB.KT_ACC,'') = isnull(DT.ACC_CODE2,'') and RB.[TYPE] = 1
left join @tRest RE on (DT.GRUP = RE.GRUP or DT.GRUP is null and RE.GRUP is null) and RE.DEP = DT.DEP and isnull(RE.DT_ACC,'') = isnull(DT.ACC_CODE1,'') and isnull(RE.KT_ACC,'') = isnull(DT.ACC_CODE2,'') and RE.[TYPE] = 3
left join (select SUM_PER = sum(isnull(SUM_PER,0)), SUM_PL = sum(isnull(SUM_PL,0)), SUM_PR = sum(isnull(SUM_PR,0)), GRUP, P_LINK, ACC_CODE1, ACC_CODE2
			from @tRasdel1 group by GRUP, P_LINK, ACC_CODE1, ACC_CODE2) r1 on (DT.GRUP = R1.GRUP or DT.GRUP is null and R1.GRUP is null) and R1.P_LINK = DT.DEP and isnull(R1.ACC_CODE1,'') = isnull(DT.ACC_CODE1,'') and isnull(R1.ACC_CODE2,'') = isnull(DT.ACC_CODE2,'')
left join @tRest RB1 on (DT.GRUP = RB1.GRUP or DT.GRUP is null and RB1.GRUP is null) and RB1.DEP = DT.DEP and isnull(RB1.DT_ACC,'') = isnull(DT.ACC_CODE1,'') and isnull(RB1.KT_ACC,'') = isnull(DT.ACC_CODE2,'') and RB1.[TYPE] = 0
left join @tRest RE1 on (DT.GRUP = RE1.GRUP or DT.GRUP is null and RE1.GRUP is null) and RE1.DEP = DT.DEP and isnull(RE1.DT_ACC,'') = isnull(DT.ACC_CODE1,'') and isnull(RE1.KT_ACC,'') = isnull(DT.ACC_CODE2,'') and RE1.[TYPE] = 2
order by  DT.GRUP, P_LINK, /*DOC_NAME, */ R.DOC_DATE, SUM_PL, SORT


exec dbo.BufferClear 'CREDIT_ACC'
exec dbo.BufferClear 'CREDIT_PER_D'
exec dbo.BufferClear 'CREDIT_PL_N'
exec dbo.BufferClear 'CREDIT_DOH_N'
exec dbo.BufferClear 'OSNOV'
exec dbo.BufferClear 'SGU_D'
exec dbo.BufferClear 'SGU_K'
exec dbo.BufferClear 'SGU_K_KL_N'

return 1

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
grant all on dbo.BB_CREDIT_CARD_DOLG to public
GO


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

GO




CREATE PROCEDURE dbo.BK_PRINTREP_JO
	@intLINK_JO	INT,
	@dDATE_START	DATETIME,
	@dDATE_END	DATETIME,
--	@intUSE_FILTERS	INT,
	@strBUFFER_NAME_ACCOUNT		VARCHAR (30),
	@strBUFFER_NAME_ACTIVE		VARCHAR (30),
	@strBUFFER_NAME_SEPARATOR	VARCHAR (30),
	@strBUFFER_NAME_KL_KBK		VARCHAR (30),
	@intPRN_KBK			tinyint,
	@intPRN_SGU			tinyint,
	@intPRN_KBK_REST		tinyint,
	@intNO_USER_ACCT		tinyint,
	@intPRN_SVOD_ZB 		tinyint,
	@intINIT_SEPARATOR		tinyint,
	@cSOURCE			CHAR (1),
	@intGRP_DATE			tinyint,
	@intTypeOb_GK			tinyint = 0,
	@intGrp_Prov			tinyint
AS
BEGIN
	/* --- Настройки журнала операций --- */
	DECLARE @strActivities_Name	VARCHAR (30),
		@strSeparator_Name	VARCHAR (30),
		@strJO_NUMBER		VARCHAR (30),
		@strJO_Name		VARCHAR (100),
		@strTXT_TOTAL_DATE	VARCHAR (100),
		@strSEPARATOR_TITLE	VARCHAR (30),
		@strDATE_START		VARCHAR (10),
		@strDATE_END		VARCHAR (10),
		@dDATE_NEXT		DATETIME, 
		@strDATE_NEXT		VARCHAR (10),

		@intORG_LINK		INT,
		@strORG_OKPO		VARCHAR (30),
		@strORG_NAME		VARCHAR (254),
		@UCHR_NAME		VARCHAR (254),	-- Учредитель
		@BUDG_NAME		VARCHAR (254),	-- Наименование бюджета

		@intFACTOR_TOTAL	TINYINT,
		@intACCOUNT_TOTAL	TINYINT,
		@TDIN_SUM		NUMERIC (28,4),
		@TKIN_SUM		NUMERIC (28,4),
		@TDOUT_SUM		NUMERIC (28,4),
		@TKOUT_SUM		NUMERIC (28,4),
		@CUR_DATE_PROV		DATETIME,
		@DATE_PROV_NEXT		DATETIME,
		@DIN_SUM_DAY		NUMERIC (28,4),
		@KIN_SUM_DAY		NUMERIC (28,4),
		@DOUT_SUM_DAY		NUMERIC (28,4),
		@KOUT_SUM_DAY		NUMERIC (28,4),
		@intROWCOUNT		INT,
		@intTOTAL_MODE		TINYINT

	SELECT	@strActivities_Name = ACTIVITIES,
		@strSeparator_Name = DELIMITER,
		@strJO_NUMBER	= [CODE],
		@strJO_Name	= [NAME],
		@strTXT_TOTAL_DATE = ISNULL (TOTAL_DATE, ''),
		@intFACTOR_TOTAL = CONVERT (TINYINT, FACT_TOTAL),
		@intACCOUNT_TOTAL = CONVERT (TINYINT, ACCT_TOTAL),
		@intTOTAL_MODE = TOTAL_MODE
	FROM dbo.JOURNAL_OPERATION	
	WHERE LINK = @intLINK_JO


	IF @intGRP_DATE = 1 OR @intGRP_DATE = 2
	BEGIN
		SET @intFACTOR_TOTAL = 0
		SET @intACCOUNT_TOTAL = 0
	END
	
	IF @intFACTOR_TOTAL = 0 OR @intACCOUNT_TOTAL = 0
		SET @intTOTAL_MODE = 0

	IF @intFACTOR_TOTAL = 1 OR @intACCOUNT_TOTAL = 1
		SET @intPRN_KBK_REST = 0

	/* --- ФИЛЬТРЫ --- */
	/* --- Показатель --- */
	DECLARE @TAB_ACTIVITIES	TABLE	(LINK_AP INT, AP_CODE VARCHAR (30), AP_NAME VARCHAR (254))
	IF LEN (@strBUFFER_NAME_ACTIVE) = 0
		INSERT INTO @TAB_ACTIVITIES
		SELECT LINK_AP, AP_CODE, AP_NAME
		FROM dbo.BK_GetTableDictionByAP (@strActivities_Name)
	ELSE
		INSERT INTO @TAB_ACTIVITIES
		SELECT LINK_AP, AP_CODE, AP_NAME
		FROM dbo.BK_GetTableDictionByAP (@strActivities_Name) T1
		INNER JOIN dbo.BufferGetTableByID (@strBUFFER_NAME_ACTIVE) T2 ON (T2.LINK = T1.LINK_AP)

	/* --- Разделитель --- */
	DECLARE @TAB_SEPARATOR TABLE	(LINK_SEP INT, SEP_CODE VARCHAR (30), SEP_NAME VARCHAR (254))
	IF LEN (@strBUFFER_NAME_SEPARATOR) = 0
		INSERT INTO @TAB_SEPARATOR
		SELECT LINK_AP, AP_CODE, AP_NAME
		FROM dbo.BK_GetTableDictionByAP (@strSeparator_Name)
	ELSE
		INSERT INTO @TAB_SEPARATOR
		SELECT LINK_AP, AP_CODE, AP_NAME
		FROM dbo.BK_GetTableDictionByAP (@strSeparator_Name) T1
		INNER JOIN dbo.BufferGetTableByID (@strBUFFER_NAME_SEPARATOR) T2 ON (T2.LINK = T1.LINK_AP)

	 --- Счета --- 
	DECLARE @TAB_ACCOUNTS TABLE	(ACCOUNT INT)
	IF LEN (@strBUFFER_NAME_ACCOUNT)  = 0
		INSERT INTO @TAB_ACCOUNTS
		SELECT SA.LINK
		FROM dbo.BK_AccountsTableByJO (@intLINK_JO) T1
		INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = T1.ACCOUNT)
		WHERE @cSOURCE = '' OR SA.cSOURCE = @cSOURCE
	ELSE
		INSERT INTO @TAB_ACCOUNTS
		SELECT LINK
		FROM dbo.BufferGetTableByID (@strBUFFER_NAME_ACCOUNT)

	INSERT INTO @TAB_ACCOUNTS 
	SELECT SA.LINK_SELF
	FROM @TAB_ACCOUNTS T1
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = T1.ACCOUNT)
	WHERE SA.cUSER <> ''
		AND NOT EXISTS (SELECT * FROM @TAB_ACCOUNTS T2 WHERE T2.ACCOUNT = SA.LINK_SELF)
	GROUP BY SA.LINK_SELF

	/* --- КБК --- */
	DECLARE @TAB_KBK TABLE	(LINK_KBK INT)
	IF LEN (@strBUFFER_NAME_KL_KBK)  = 0
		INSERT INTO @TAB_KBK
		SELECT LINK_AP
		FROM dbo.BK_GetTableDictionByAP ('KBK')
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK
		FROM dbo.BufferGetTableByID (@strBUFFER_NAME_KL_KBK)

	/* -- Параметры организации -- */
	SET @intPRN_SVOD_ZB = ISNULL (@intPRN_SVOD_ZB, 0)
	SET @intORG_LINK = dbo.BK_GetDepZB ()

	IF @intPRN_SVOD_ZB = 1 OR @intORG_LINK IS NULL
		SET @intORG_LINK = dbo.GetOwnDepLink()

	SELECT @intORG_LINK = D.LINK,
		@strORG_OKPO = D.[OKPO],
		@strORG_NAME = dbo.BK_GET_PRINT_DEP_NAME (D.LINK),
		@UCHR_NAME = dbo.BK_GET_PRINT_DEP_NAME (D.UCHR_LINK),
		@BUDG_NAME = B.[NAME]
	FROM dbo.DEPARTMENTS D
	LEFT JOIN dbo.KL_ADMIN_BS V ON (V.LINK = D.VED_LINK)
	LEFT JOIN dbo.KL_BUDG_TYPE B ON (B.LINK = V.Link_Budg)
	WHERE D.LINK = @intORG_LINK

	SELECT @UCHR_NAME = ISNULL (@UCHR_NAME, ''),
		@BUDG_NAME = ISNULL (@BUDG_NAME, '')

	IF @intPRN_SVOD_ZB = 1
		SET @strORG_NAME = RTRIM (@strORG_NAME) + ' (ЦБ)'

	/* --- ОБОРОТЫ ЗА ПЕРИОД --- */
	DECLARE @TAB_OBOROT TABLE
		(REC_NO INT IDENTITY,
		ORDERS	INT,		
		NUMBER VARCHAR (50),
		[DATE]	DATETIME,
		DATE_PROV DATETIME,
		DATE_SORT DATETIME,
		ACCOUNT INT,
		DT int,
		KT int,
		DIN_SUM NUMERIC (28,4),
		KIN_SUM NUMERIC (28,4),
		DT_SUMMA NUMERIC (28,4),
		KT_SUMMA NUMERIC (28,4),
		DT_SUM1 NUMERIC (28,4),
		KT_SUM1 NUMERIC (28,4),
		DOUT_SUM NUMERIC (28,4),
		KOUT_SUM NUMERIC (28,4),
		SUMMA NUMERIC (28,4),
		SUMMA_OB NUMERIC (28,4),
		OBJECT INT,
		NAME_OPER VARCHAR(254),
		LEDGER_JOURNAL INT,
		AP INT,
		SEP INT,
		KBK_REST INT,
		KBK1 INT,
		KBK2 INT,
		SGU1 INT,
		SGU2 INT,
		INDATE	DATETIME,
		ADD_REC TINYINT,
		DOC_CODE	VARCHAR (30),	
		LINK_DOC	INT,
		LINK_G2		INT
		)

	IF LEN (@strBUFFER_NAME_ACCOUNT)  = 0
		INSERT INTO @TAB_OBOROT
		SELECT 1, NUMBER, 
			DATE,
			DATE_PROV,
			DATE_SORT,
			CASE
				WHEN ISNULL (SA1.cUSER, '') <> '' AND @intNO_USER_ACCT = 1 THEN ISNULL (SA1.LINK_SELF, SA1.LINK)
				ELSE SA1.LINK
			END,
			CASE
				WHEN ISNULL (D_SA.cUSER, '') <> '' AND @intNO_USER_ACCT = 1 THEN ISNULL (D_SA.LINK_SELF, DT)
				ELSE DT
			END,
			CASE
				WHEN ISNULL (K_SA.cUSER, '') <> '' AND @intNO_USER_ACCT = 1 THEN ISNULL (K_SA.LINK_SELF, KT)
				ELSE KT
			END,
			0, 0,	/* --- ВХОДЯЩИЕ ОСТАТКИ --- */
			CASE
				WHEN (JO1 = @intLINK_JO AND JO2 = @intLINK_JO 
					AND D_SA.S_ACTIVE = 1 AND K_SA.S_ACTIVE = 1) THEN 0
				WHEN (JO1 = @intLINK_JO AND D_SA.S_ACTIVE = 1) THEN SUMMA
				WHEN (JO2 = @intLINK_JO AND K_SA.S_ACTIVE = 1) THEN -SUMMA 
				ELSE 0
			END,
			CASE
				WHEN (JO1 = @intLINK_JO AND JO2 = @intLINK_JO 
					AND D_SA.S_PASSIVE = 1 AND K_SA.S_PASSIVE = 1) THEN 0
				WHEN (JO2 = @intLINK_JO AND K_SA.S_PASSIVE = 1) THEN SUMMA
				WHEN (JO1 = @intLINK_JO AND D_SA.S_PASSIVE = 1) THEN -SUMMA 
				ELSE 0
			END,
			CASE
				WHEN JO1 = @intLINK_JO THEN SUMMA
				ELSE 0
			END,
			CASE
				WHEN JO2 = @intLINK_JO THEN SUMMA
				ELSE 0
			END,
			0, 0,	/* --- ИСХОДЯЩИЕ ОСТАТКИ --- */
			SUMMA,
			CASE
				WHEN DT = KT THEN 0
				WHEN (ACCOUNT = KT AND K_SA.S_ACTIVE = 1)
					OR (ACCOUNT = DT AND D_SA.S_PASSIVE = 1) THEN -SUMMA
				ELSE SUMMA
			END,
			OBJECT,
			NAME_OPER,
			LEDGER_JOURNAL,
			AP = CASE
					WHEN JO1 = @intLINK_JO THEN COALESCE (AP_DB, AP_KT, 0) 
					WHEN JO2 = @intLINK_JO THEN COALESCE (AP_KT, AP_DB, 0) 
					ELSE COALESCE (AP_DB, AP_KT, 0) 
				END,
			SEP = CASE
					WHEN @intINIT_SEPARATOR = 1 THEN
						CASE
							WHEN JO1 = @intLINK_JO THEN COALESCE (SEP_DB, SEP_KT, 0) 
							WHEN JO2 = @intLINK_JO THEN COALESCE (SEP_KT, SEP_DB, 0) 
							ELSE COALESCE (SEP_DB, SEP_KT, 0) 
						END
					ELSE 0
			END,
			CASE
				WHEN JO1 = @intLINK_JO AND @intPRN_KBK = 1 THEN ISNULL(KBK1, 0)
				WHEN JO2 = @intLINK_JO AND @intPRN_KBK = 1 THEN ISNULL(KBK2, 0)
				ELSE 0
			END,
			ISNULL(KBK1, 0) AS KBK1, 
			ISNULL(KBK2, 0) AS KBK2,
			ISNULL(SGU1, 0) AS SGU1, 
			ISNULL(SGU2, 0) AS SGU2,
			CASE
				WHEN JO1 = @intLINK_JO THEN COALESCE (INDATE1, INDATE2)
				WHEN JO2 = @intLINK_JO THEN COALESCE (INDATE2, INDATE1)
				ELSE COALESCE (INDATE1, INDATE2)
			END,
			T1.ADD_REC,
			T1.DOC_CODE,
			T1.LINK_DOC,
			T1.LINK_G2
		FROM dbo.BK_GetTableOborotForJOByPeriod (@dDATE_START, @dDATE_END, DEFAULT, @intLINK_JO, DEFAULT, @intGRP_DATE) T1
		LEFT OUTER JOIN dbo.S_ACCOUNTS SA1 ON (SA1.LINK = ACCOUNT)
		LEFT OUTER JOIN dbo.S_ACCOUNTS D_SA ON (D_SA.LINK = DT)
		LEFT OUTER JOIN dbo.S_ACCOUNTS K_SA ON (K_SA.LINK = KT)
		WHERE (@intPRN_SVOD_ZB = 1 OR DEP_LINK = @intORG_LINK)
			AND (@cSOURCE = ''
				OR (@cSOURCE <> '' AND (D_SA.cSOURCE = @cSOURCE OR K_SA.cSOURCE = @cSOURCE)))
			AND (ISNULL (KBK1, 0) IN (SELECT LINK_KBK FROM @TAB_KBK)
				OR ISNULL (KBK2, 0) IN (SELECT LINK_KBK FROM @TAB_KBK))
	ELSE
		INSERT INTO @TAB_OBOROT
		SELECT 1, NUMBER, 
			DATE, 
			DATE_PROV,
			DATE_SORT,
			CASE
				WHEN ISNULL (SA1.cUSER, '') <> '' AND @intNO_USER_ACCT = 1 THEN ISNULL (SA1.LINK_SELF, SA1.LINK)
				ELSE SA1.LINK
			END,
			CASE
				WHEN ISNULL (D_SA.cUSER, '') <> '' AND @intNO_USER_ACCT = 1 THEN ISNULL (D_SA.LINK_SELF, DT)
				ELSE DT
			END,
			CASE
				WHEN ISNULL (K_SA.cUSER, '') <> '' AND @intNO_USER_ACCT = 1 THEN ISNULL (K_SA.LINK_SELF, KT)
				ELSE KT
			END,
			0, 0,	/* --- ВХОДЯЩИЕ ОСТАТКИ --- */
			CASE
				WHEN JO1 = @intLINK_JO THEN SUMMA
				ELSE 0
			END,
			CASE
				WHEN JO2 = @intLINK_JO THEN SUMMA
				ELSE 0
			END,
			CASE
				WHEN JO1 = @intLINK_JO THEN SUMMA
				ELSE 0
			END,
			CASE
				WHEN JO2 = @intLINK_JO THEN SUMMA
				ELSE 0
			END,
			0, 0,	/* --- ИСХОДЯЩИЕ ОСТАТКИ --- */
			SUMMA, 
			CASE
				WHEN DT = KT THEN 0
				WHEN (ACCOUNT = KT AND K_SA.S_ACTIVE = 1)
					OR (ACCOUNT = DT AND D_SA.S_PASSIVE = 1) THEN -SUMMA
				ELSE SUMMA
			END,
			OBJECT,
			NAME_OPER,
			LEDGER_JOURNAL,
			AP = CASE
					WHEN JO1 = @intLINK_JO THEN COALESCE (AP_DB, AP_KT, 0) 
					WHEN JO2 = @intLINK_JO THEN COALESCE (AP_KT, AP_DB, 0) 
					ELSE COALESCE (AP_DB, AP_KT, 0) 
				END,
			SEP = CASE
					WHEN @intINIT_SEPARATOR = 1 THEN
						CASE
							WHEN JO1 = @intLINK_JO THEN COALESCE (SEP_DB, SEP_KT, 0) 
							WHEN JO2 = @intLINK_JO THEN COALESCE (SEP_KT, SEP_DB, 0) 
							ELSE COALESCE (SEP_DB, SEP_KT, 0) 
						END
					ELSE 0
			END,
			CASE
				WHEN JO1 = @intLINK_JO  AND @intPRN_KBK = 1 THEN ISNULL(KBK1, 0)
				WHEN JO2 = @intLINK_JO  AND @intPRN_KBK = 1 THEN ISNULL(KBK2, 0)
				ELSE 0
			END,
			ISNULL(KBK1, 0) AS KBK1, 
			ISNULL(KBK2, 0) AS KBK2,
			ISNULL(SGU1, 0) AS SGU1, 
			ISNULL(SGU2, 0) AS SGU2,
			CASE
				WHEN JO1 = @intLINK_JO THEN COALESCE (INDATE1, INDATE2)
				WHEN JO2 = @intLINK_JO THEN COALESCE (INDATE2, INDATE1)
				ELSE COALESCE (INDATE1, INDATE2)
			END,
			T1.ADD_REC,
			T1.DOC_CODE,
			T1.LINK_DOC,
			T1.LINK_G2
		FROM dbo.BK_GetTableOborotForJOByPeriod (@dDATE_START, @dDATE_END, DEFAULT, @intLINK_JO, DEFAULT, @intGRP_DATE) T1
		LEFT OUTER JOIN dbo.S_ACCOUNTS SA1 ON (SA1.LINK = T1.ACCOUNT)
		LEFT OUTER JOIN dbo.S_ACCOUNTS D_SA ON (D_SA.LINK = T1.DT)
		LEFT OUTER JOIN dbo.S_ACCOUNTS K_SA ON (K_SA.LINK = T1.KT)
		WHERE (@intPRN_SVOD_ZB = 1 OR DEP_LINK = @intORG_LINK)
			AND (T1.DT IN (SELECT LINK FROM dbo.BufferGetTableByID (@strBUFFER_NAME_ACCOUNT))
				OR T1.KT IN (SELECT LINK FROM dbo.BufferGetTableByID (@strBUFFER_NAME_ACCOUNT)))
			AND (ISNULL (KBK1, 0) IN (SELECT LINK_KBK FROM @TAB_KBK)
				OR ISNULL (KBK2, 0) IN (SELECT LINK_KBK FROM @TAB_KBK))

	/* --- ОБОРОТЫ В ГЛАВНУЮ КНИГУ --- */
	DECLARE @TAB_OBOROT_GK TABLE (DT INT, KBK1 INT, SGU1 INT,
			KT INT, KBK2 INT, SGU2 INT,
			SUMMA NUMERIC (28,4))

	IF ISNULL (@intTypeOb_GK, 0) = 0
	BEGIN	--- Группировка оборотов для ГК счетам ---
		INSERT INTO @TAB_OBOROT_GK
		SELECT DT, KBK1, SGU1,
			0, 0, 0,
			D_SUM
		FROM (SELECT D.DT,
			CASE 
				WHEN @intPRN_KBK = 1 THEN D.KBK1
				ELSE 0
			END	AS KBK1,
			CASE 
				WHEN @intPRN_SGU = 1 THEN D.SGU1
				ELSE 0
			END	AS SGU1,
			SUM (D.SUMMA) AS D_SUM
			FROM @TAB_OBOROT D
			INNER JOIN @TAB_ACTIVITIES ACT ON (ACT.LINK_AP = D.AP)
			INNER JOIN @TAB_SEPARATOR SEP ON (SEP.LINK_SEP = D.SEP)
			WHERE D.LEDGER_JOURNAL = @intLINK_JO
				AND D.ADD_REC = 0
			GROUP BY D.DT,
				CASE 
					WHEN @intPRN_KBK = 1 THEN D.KBK1
					ELSE 0
				END,
				CASE 
					WHEN @intPRN_SGU = 1 THEN D.SGU1
					ELSE 0
				END
				) DT
		UNION ALL
		SELECT 0, 0, 0,
			KT, KBK2, SGU2,
			K_SUM
		FROM (SELECT K.KT,
			CASE 
				WHEN @intPRN_KBK = 1 THEN K.KBK2
				ELSE 0
			END	AS KBK2,
			CASE 
				WHEN @intPRN_SGU = 1 THEN K.SGU2
				ELSE 0
			END	AS SGU2,
			SUM (K.SUMMA) AS K_SUM
			FROM @TAB_OBOROT K
			INNER JOIN @TAB_ACTIVITIES ACT ON (ACT.LINK_AP = K.AP)
			INNER JOIN @TAB_SEPARATOR SEP ON (SEP.LINK_SEP = K.SEP)
			WHERE K.LEDGER_JOURNAL = @intLINK_JO
				AND K.ADD_REC = 0
			GROUP BY K.KT,
				CASE 
					WHEN @intPRN_KBK = 1 THEN K.KBK2
					ELSE 0
				END,
				CASE 
					WHEN @intPRN_SGU = 1 THEN K.SGU2
					ELSE 0
				END
				) KT
		
		SET @intROWCOUNT = @@ROWCOUNT
	END
	ELSE		
	BEGIN		--- Группировка оборотов для ГК проводкам ---
		INSERT INTO @TAB_OBOROT_GK
		SELECT DT, KBK1, SGU1,
			KT, KBK2, SGU2,
			SUM_GK
		FROM (SELECT OB.DT,
			CASE 
				WHEN @intPRN_KBK = 1 THEN OB.KBK1
				ELSE 0
			END	AS KBK1,
			CASE 
				WHEN @intPRN_SGU = 1 THEN OB.SGU1
				ELSE 0
			END	AS SGU1,
			OB.KT,
			CASE 
				WHEN @intPRN_KBK = 1 THEN OB.KBK2
				ELSE 0
			END	AS KBK2,
			CASE 
				WHEN @intPRN_SGU = 1 THEN OB.SGU2
				ELSE 0
			END	AS SGU2,
			SUM (OB.SUMMA) AS SUM_GK
			FROM @TAB_OBOROT OB
			INNER JOIN @TAB_ACTIVITIES ACT ON (ACT.LINK_AP = OB.AP)
			INNER JOIN @TAB_SEPARATOR SEP ON (SEP.LINK_SEP = OB.SEP)
			WHERE OB.LEDGER_JOURNAL = @intLINK_JO
				AND OB.ADD_REC = 0
			GROUP BY OB.DT,
				CASE 
					WHEN @intPRN_KBK = 1 THEN OB.KBK1
					ELSE 0
				END,
				CASE 
					WHEN @intPRN_SGU = 1 THEN OB.SGU1
					ELSE 0
				END,
				OB.KT,
				CASE 
					WHEN @intPRN_KBK = 1 THEN OB.KBK2
					ELSE 0
				END,
				CASE 
					WHEN @intPRN_SGU = 1 THEN OB.SGU2
					ELSE 0
				END
				) GK
		
		SET @intROWCOUNT = @@ROWCOUNT
	END

	IF ISNULL (@intROWCOUNT, 0) = 0
		INSERT INTO @TAB_OBOROT_GK VALUES (0, 0, 0, 0, 0, 0, 0)

	/* --- ВЫЧИСЛЯЕМ ОСТАТКИ --- */
	--- Таблица входящих остатков ---
	DECLARE @BEGIN_REST TABLE (ACCOUNT INT, AP INT, SEP INT, KBK INT, --INDATE DATETIME, 
			D_SUMMA NUMERIC (28,4), K_SUMMA NUMERIC (28,4))
	--- Таблица исходящих остатков ---
	DECLARE @END_REST TABLE (ACCOUNT INT, AP INT, SEP INT, KBK INT, --INDATE DATETIME, 
			D_SUMMA NUMERIC (28,4), K_SUMMA NUMERIC (28,4))
	--- Сводная таблица ---
	DECLARE @TAB_REST TABLE (ACCOUNT INT, AP INT, SEP INT, KBK INT, 
				DIN_SUMMA NUMERIC (28,4), KIN_SUMMA NUMERIC (28,4),
				DOUT_SUMMA NUMERIC (28,4), KOUT_SUMMA NUMERIC (28,4))
	
	--- Таблица расчета остатков по дням ---
	DECLARE @REST_BY_DATE TABLE (DATE_PROV DATETIME,
			DIN_SUMMA NUMERIC (28,4), KIN_SUMMA NUMERIC (28,4),
			DOUT_SUMMA NUMERIC (28,4), KOUT_SUMMA NUMERIC (28,4))

	IF @intGRP_DATE = 1 OR @intGRP_DATE = 2
	BEGIN
		--!!! Расчет остатков по дням !!!-- 
		DECLARE #CURS CURSOR LOCAL STATIC
			FOR SELECT DATE_SORT
				FROM @TAB_OBOROT
				WHERE ADD_REC = 0
					AND DATE_SORT IS NOT NULL
				GROUP BY DATE_SORT
				ORDER BY DATE_SORT

		OPEN #CURS
		FETCH FROM #CURS
			INTO @CUR_DATE_PROV
		WHILE @@FETCH_STATUS = 0
		BEGIN

--select @CUR_DATE_PROV, @DATE_PROV_NEXT

			IF @CUR_DATE_PROV = @DATE_PROV_NEXT	-- На предыдущей итерации пощитали
			BEGIN
				SELECT @DIN_SUM_DAY	= @DOUT_SUM_DAY,
					@KIN_SUM_DAY	= @KOUT_SUM_DAY
			END
			ELSE
			BEGIN
				SELECT @DIN_SUM_DAY	= 0, @KIN_SUM_DAY	= 0

				SELECT @DIN_SUM_DAY = SUM (R1.D_SUMMA),
					@KIN_SUM_DAY = SUM (R1.K_SUMMA)
				FROM dbo.BK_GetTableRestForJOByDate (@CUR_DATE_PROV, @intLINK_JO,
									@intINIT_SEPARATOR,
									@intNO_USER_ACCT,
									1,
									DEFAULT) R1
				INNER JOIN @TAB_ACCOUNTS T1 ON (T1.ACCOUNT = R1.ACCOUNT)
				INNER JOIN @TAB_ACTIVITIES ACT ON (ACT.LINK_AP = R1.AP)
				INNER JOIN @TAB_SEPARATOR SEP ON (SEP.LINK_SEP = R1.SEP)
				INNER JOIN @TAB_KBK T2 ON (T2.LINK_KBK = R1.KBK)
				WHERE @intPRN_SVOD_ZB = 1 OR R1.DEP_LINK = @intORG_LINK
			END

			SELECT @DOUT_SUM_DAY	= 0, @KOUT_SUM_DAY	= 0

			SET @DATE_PROV_NEXT = DATEADD (DAY, 1, @CUR_DATE_PROV)


			SELECT @DOUT_SUM_DAY = SUM (R1.D_SUMMA),
				@KOUT_SUM_DAY	= SUM (R1.K_SUMMA)
			FROM dbo.BK_GetTableRestForJOByDate (@DATE_PROV_NEXT, @intLINK_JO,
								@intINIT_SEPARATOR,
								@intNO_USER_ACCT,
								1,
								DEFAULT) R1
			INNER JOIN @TAB_ACCOUNTS T1 ON (T1.ACCOUNT = R1.ACCOUNT)
			INNER JOIN @TAB_ACTIVITIES ACT ON (ACT.LINK_AP = R1.AP)
			INNER JOIN @TAB_SEPARATOR SEP ON (SEP.LINK_SEP = R1.SEP)
			INNER JOIN @TAB_KBK T2 ON (T2.LINK_KBK = R1.KBK)
			WHERE @intPRN_SVOD_ZB = 1 OR R1.DEP_LINK = @intORG_LINK
			
			INSERT INTO @REST_BY_DATE (DATE_PROV, DIN_SUMMA, KIN_SUMMA, DOUT_SUMMA, KOUT_SUMMA)
			SELECT @CUR_DATE_PROV, @DIN_SUM_DAY, @KIN_SUM_DAY, @DOUT_SUM_DAY, @KOUT_SUM_DAY

			FETCH NEXT FROM #CURS
				INTO @CUR_DATE_PROV
		END
		CLOSE #CURS
		DEALLOCATE #CURS
	END
	ELSE
	BEGIN
		/* --- Входящие --- */
		INSERT INTO @BEGIN_REST
		SELECT
			CASE 
				WHEN @intACCOUNT_TOTAL = 0 AND @intFACTOR_TOTAL = 1 THEN 0
				ELSE
					CASE WHEN @intNO_USER_ACCT = 1 AND ISNULL (SA.cUSER, '') <> ''
								THEN ISNULL (SA.LINK_SELF, SA.LINK)
						ELSE R1.ACCOUNT END
			END,
			CASE 
				WHEN @intFACTOR_TOTAL = 1 THEN R1.AP
				ELSE 0
			END,
			R1.SEP,
			CASE 
				WHEN @intPRN_KBK_REST = 1 THEN ISNULL (R1.KBK, 0)
				ELSE 0
			END,
			SUM (R1.D_SUMMA),
			SUM (R1.K_SUMMA)
		FROM dbo.BK_GetTableRestForJOByDate (@dDATE_START, @intLINK_JO,
							@intINIT_SEPARATOR,
							0,
--							@intNO_USER_ACCT,
							1,
							DEFAULT) R1
		INNER JOIN @TAB_ACCOUNTS T1 ON (T1.ACCOUNT = R1.ACCOUNT)
		INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = T1.ACCOUNT)
		INNER JOIN @TAB_ACTIVITIES ACT ON (ACT.LINK_AP = R1.AP)
		INNER JOIN @TAB_SEPARATOR SEP ON (SEP.LINK_SEP = R1.SEP)
		INNER JOIN @TAB_KBK T2 ON (T2.LINK_KBK = R1.KBK)
		WHERE @intPRN_SVOD_ZB = 1 OR R1.DEP_LINK = @intORG_LINK
		GROUP BY
			CASE 
				WHEN @intACCOUNT_TOTAL = 0 AND @intFACTOR_TOTAL = 1 THEN 0
				ELSE
					CASE WHEN @intNO_USER_ACCT = 1 AND ISNULL (SA.cUSER, '') <> ''
								THEN ISNULL (SA.LINK_SELF, SA.LINK)
						ELSE R1.ACCOUNT END
			END,
			CASE 
				WHEN @intFACTOR_TOTAL = 1 THEN R1.AP
				ELSE 0
			END,
			R1.SEP,
			CASE 
				WHEN @intPRN_KBK_REST = 1 THEN ISNULL (R1.KBK, 0)
				ELSE 0
			END
		HAVING SUM (R1.D_SUMMA) <> 0 OR SUM (R1.K_SUMMA) <> 0

		/* --- Исходящие --- */
		SET @dDATE_NEXT = DATEADD (DAY, 1, @dDATE_END)
		
		INSERT INTO @END_REST
		SELECT 
			CASE 
				WHEN @intACCOUNT_TOTAL = 0 AND @intFACTOR_TOTAL = 1 THEN 0
				ELSE
					CASE WHEN @intNO_USER_ACCT = 1 AND ISNULL (SA.cUSER, '') <> ''
								THEN ISNULL (SA.LINK_SELF, SA.LINK)
						ELSE R1.ACCOUNT END
			END,
			CASE 
				WHEN @intFACTOR_TOTAL = 1 THEN R1.AP
				ELSE 0
			END,
			R1.SEP,
			CASE 
				WHEN @intPRN_KBK_REST = 1 THEN ISNULL (R1.KBK, 0)
				ELSE 0
			END,
			SUM (R1.D_SUMMA),
			SUM (R1.K_SUMMA)
		FROM dbo.BK_GetTableRestForJOByDate (@dDATE_NEXT, @intLINK_JO,
							@intINIT_SEPARATOR,
							0,
--							@intNO_USER_ACCT,
							1,
							DEFAULT) R1
		INNER JOIN @TAB_ACCOUNTS T1 ON (T1.ACCOUNT = R1.ACCOUNT)
		INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = T1.ACCOUNT)
		INNER JOIN @TAB_ACTIVITIES ACT ON (ACT.LINK_AP = R1.AP)
		INNER JOIN @TAB_SEPARATOR SEP ON (SEP.LINK_SEP = R1.SEP)
		INNER JOIN @TAB_KBK T2 ON (T2.LINK_KBK = R1.KBK)
		WHERE @intPRN_SVOD_ZB = 1 OR R1.DEP_LINK = @intORG_LINK
		GROUP BY
			CASE 
				WHEN @intACCOUNT_TOTAL = 0 AND @intFACTOR_TOTAL = 1 THEN 0
				ELSE
					CASE WHEN @intNO_USER_ACCT = 1 AND ISNULL (SA.cUSER, '') <> ''
								THEN ISNULL (SA.LINK_SELF, SA.LINK)
						ELSE R1.ACCOUNT END
			END,
			CASE 
				WHEN @intFACTOR_TOTAL = 1 THEN R1.AP
				ELSE 0
			END,
			R1.SEP,
			CASE 
				WHEN @intPRN_KBK_REST = 1 THEN ISNULL (R1.KBK, 0)
				ELSE 0
			END
		HAVING SUM (R1.D_SUMMA) <> 0 OR SUM (R1.K_SUMMA) <> 0
	
		INSERT INTO @TAB_REST (ACCOUNT, AP, SEP, KBK)
		SELECT ACCOUNT, AP, SEP, KBK
		FROM @BEGIN_REST
		UNION
		SELECT ACCOUNT, AP, SEP, KBK
		FROM @END_REST
	
		UPDATE @TAB_REST SET DIN_SUMMA = ISNULL (BR.D_SUMMA, 0),
					KIN_SUMMA = ISNULL (BR.K_SUMMA, 0),
					DOUT_SUMMA = ISNULL (ER.D_SUMMA, 0),
					KOUT_SUMMA = ISNULL (ER.K_SUMMA, 0)
		FROM @TAB_REST R1
		LEFT OUTER JOIN @BEGIN_REST BR ON (BR.ACCOUNT = R1.ACCOUNT
							AND BR.AP = R1.AP
							AND BR.SEP = R1.SEP
							AND BR.KBK = R1.KBK)
		LEFT OUTER JOIN @END_REST ER ON (ER.ACCOUNT = R1.ACCOUNT
							AND ER.AP = R1.AP
							AND ER.SEP = R1.SEP
							AND ER.KBK = R1.KBK)
	END

	/* --- Наименование разделителя --- */
	SELECT @strSEPARATOR_TITLE = S_TITLE FROM ANALIT WHERE CODE_AP = @strSeparator_Name
	SET @strSEPARATOR_TITLE = CASE
					WHEN @intINIT_SEPARATOR = 1 AND @strSeparator_Name = 'INDATE' THEN 'Дата: '
					WHEN @intINIT_SEPARATOR = 0 OR ISNULL (@strSEPARATOR_TITLE, '') = '' THEN ''
					ELSE RTRIM (@strSEPARATOR_TITLE) + ': '
				END
	/* --- --- */
	SET @strDATE_START = ISNULL (CONVERT (VARCHAR (10), @dDATE_START, 104), '')
	SET @strDATE_END = ISNULL (CONVERT (VARCHAR (10), @dDATE_END, 104), '')
	SET @strDATE_NEXT = ISNULL (CONVERT (VARCHAR (10), @dDATE_NEXT, 104), '')

	/* --- Расчет для вывода итогов по показателям и субсчетам --- */
	IF @intFACTOR_TOTAL = 1 OR @intACCOUNT_TOTAL = 1
	BEGIN
		UPDATE @TAB_OBOROT SET DIN_SUM = TR.DIN_SUMMA,
					KIN_SUM = TR.KIN_SUMMA,
					DOUT_SUM = TR.DOUT_SUMMA,
					KOUT_SUM = TR.KOUT_SUMMA
		FROM @TAB_OBOROT OB
		INNER JOIN @TAB_REST TR ON (((@intACCOUNT_TOTAL = 0 AND @intFACTOR_TOTAL = 1)
						OR (TR.ACCOUNT = OB.ACCOUNT))
					AND ((@intFACTOR_TOTAL = 1 AND TR.AP = OB.AP)
						OR (@intFACTOR_TOTAL = 0))
					AND TR.SEP = OB.SEP)
		
		INSERT INTO @TAB_OBOROT (ORDERS, ACCOUNT, AP, SEP,
			DIN_SUM, KIN_SUM,
			DT_SUMMA, KT_SUMMA,
			DOUT_SUM, KOUT_SUM,
			DOC_CODE,
			LINK_DOC,
			LINK_G2)
		SELECT 1,
			CASE 
				WHEN @intACCOUNT_TOTAL = 0 AND @intFACTOR_TOTAL = 1 THEN 0
				ELSE T1.ACCOUNT
			END,
			CASE
				WHEN @intFACTOR_TOTAL = 1 THEN T1.AP
				ELSE 0
			END,
			T1.SEP,
			T1.DIN_SUMMA, T1.KIN_SUMMA,
			0, 0,
			T1.DOUT_SUMMA, T1.KOUT_SUMMA,
			'', 0, 0
		FROM @TAB_REST T1
		WHERE NOT EXISTS (SELECT T2.*
					FROM @TAB_OBOROT T2
					WHERE ((@intACCOUNT_TOTAL = 0 AND @intFACTOR_TOTAL = 1)
							OR (T2.ACCOUNT = T1.ACCOUNT))
						AND ((@intFACTOR_TOTAL = 1 AND T2.AP = T1.AP)
							OR (@intFACTOR_TOTAL = 0))
						AND T2.SEP = T1.SEP)
	END

	/* --- Результаты для вывода --- */
	DECLARE @TAB_RES TABLE (ORDERS	INT, ACCOUNT INT, AP INT, SEP INT, 
		JO_CODE VARCHAR (20), JO_NAME VARCHAR (254),
		TOTAL_DATE VARCHAR (254),
		DATE_START VARCHAR (10), DATE_END VARCHAR (10), DATE_NEXT VARCHAR (10), 

		DEP_OKPO VARCHAR (20), DEP_NAME VARCHAR (254),
		UCHR_NAME VARCHAR (254), BUDG_NAME VARCHAR (254),

		DOC_NUM VARCHAR (50),
		DOC_DATE VARCHAR (10), dDOC_DATE DATETIME,
		DATE_PROV VARCHAR (10), dDATE_PROV DATETIME,
		DOC_NAME VARCHAR (254),
		ACT_NAME VARCHAR (254), SEP_CODE VARCHAR (20), SEP_NAME VARCHAR (254), NAME_OPER VARCHAR (254),
		DT_CODE VARCHAR (60), KT_CODE VARCHAR (60),
		ACCT_CODE VARCHAR (60),
		DT_LONG  VARCHAR (60), KT_LONG  VARCHAR (60),
	 	SUMMA NUMERIC (28,4), SUMMA_OB NUMERIC (28,4),
		DT_SUMMA NUMERIC (28,4),
		KT_SUMMA NUMERIC (28,4),
		DT_SUM1 NUMERIC (28,4),
		KT_SUM1 NUMERIC (28,4),
		DIC_NAME VARCHAR (60),
		DIN_SUM NUMERIC (28,4), KIN_SUM NUMERIC (28,4), 
		DOUT_SUM NUMERIC (28,4), KOUT_SUM NUMERIC (28,4), 
		FDIN_SUM NUMERIC (28,4), FKIN_SUM NUMERIC (28,4), 
		FDOUT_SUM NUMERIC (28,4), FKOUT_SUM NUMERIC (28,4),
		TDIN_SUM NUMERIC (28,4), TKIN_SUM NUMERIC (28,4), 
		TDOUT_SUM NUMERIC (28,4), TKOUT_SUM NUMERIC (28,4),
		DIN_DAY NUMERIC (28,4), KIN_DAY NUMERIC (28,4), 
		DOUT_DAY NUMERIC (28,4), KOUT_DAY NUMERIC (28,4), 
		OBJ_CODE VARCHAR (30),	
		LINK_DOC INT,
		LINK_G2	INT,
		JO_GK_LN INT,
		JO_GK_CD VARCHAR (10),
		DATE_SORT DATETIME,
		cDATE_SORT VARCHAR (10)
	)

	IF @intGrp_Prov = 1	-- Группировка проводок --
		INSERT INTO @TAB_RES
		SELECT JO.ORDERS,
			JO.ACCOUNT,
			0, JO.SEP,
			@strJO_NUMBER AS JO_CODE,
			@strJO_Name AS JO_NAME,
			@strTXT_TOTAL_DATE AS TOTAL_DATE,
			@strDATE_START AS DATE_START,
			@strDATE_END AS DATE_END,
			@strDATE_NEXT,
			ISNULL (@strORG_OKPO, '') AS DEP_OKPO,
			ISNULL (@strORG_NAME, '') AS DEP_NAME,
			@UCHR_NAME,
			@BUDG_NAME,

			'',	--JO.NUMBER AS DOC_NUM,
			CONVERT(VARCHAR(10), JO.DATE, 104) AS DOC_DATE,
			JO.DATE, 
			'', -- CONVERT(VARCHAR(10), JO.DATE_PROV, 104),
			NULL, -- JO.DATE_PROV, 
			'', --dbo.JurnalProvGetDocKind (JO.LINK_DOC, JO.OBJECT)
			--	+ ISNULL (' (пров.' + CONVERT (VARCHAR (10), JO.DATE_PROV, 104) + ')', '') AS DOC_NAME,
			ACT_NAME = '', --CASE 
					--WHEN @strActivities_Name = 'INDATE' THEN ISNULL (CONVERT (VARCHAR (10), INDATE, 104), '')
					--WHEN @strActivities_Name IN ('EKR', 'SGU', 'KBK') THEN AP.AP_CODE
					--ELSE AP.AP_NAME
				--END,
			SEP_CODE = CASE 
					WHEN @strSeparator_Name = 'INDATE' THEN ''
					ELSE SEP.SEP_CODE
				END,
			SEP_NAME = CASE 
					WHEN @strSeparator_Name = 'INDATE' THEN ISNULL (CONVERT (VARCHAR (10), INDATE, 104), '')
					ELSE SEP.SEP_NAME
				END,	
			'', --NAME_OPER,
			DT_CODE = ISNULL (SA1.CODE, ''),
			KT_CODE = ISNULL (SA2.CODE, ''),
			ACCT_CODE = ISNULL (SA3.CODE, ''),
			dbo.BK_GetAcctFullCode1 (JO.DT, JO.KBK1, JO.SGU1, @intPRN_KBK, @intPRN_SGU) AS DT_LONG,
			dbo.BK_GetAcctFullCode1 (JO.KT, JO.KBK2, JO.SGU2, @intPRN_KBK, @intPRN_SGU) AS KT_LONG,
			SUM (JO.SUMMA),
			SUM (JO.SUMMA_OB),
			SUM (JO.DT_SUMMA),
			SUM (JO.KT_SUMMA),
			SUM (JO.DT_SUM1),
			SUM (JO.KT_SUM1),
			@strSEPARATOR_TITLE AS DIC_NAME,
			DIN_SUM, KIN_SUM,
			DOUT_SUM, KOUT_SUM,
			0, 0, 0, 0,
			0, 0, 0, 0,
			RD.DIN_SUMMA, RD.KIN_SUMMA,
			RD.DOUT_SUMMA, RD.KOUT_SUMMA,
			'', --JO.DOC_CODE, 
			0, --JO.LINK_DOC,
			0, --JO.LINK_G2,
			0, --JO.LEDGER_JOURNAL,
			'', --ISNULL (JO_GK.CODE, ''),
			JO.DATE_SORT,
			CONVERT (VARCHAR (10), JO.DATE_SORT, 104)
		FROM @TAB_OBOROT JO
		INNER JOIN @TAB_ACTIVITIES AP ON (AP.LINK_AP = JO.AP )
		INNER JOIN @TAB_SEPARATOR SEP ON (SEP.LINK_SEP = JO.SEP)
		LEFT OUTER JOIN dbo.S_ACCOUNTS SA1 ON SA1.LINK = JO.DT
		LEFT OUTER JOIN dbo.S_ACCOUNTS SA2 ON SA2.LINK = JO.KT
		LEFT OUTER JOIN dbo.S_ACCOUNTS SA3 ON SA3.LINK = JO.ACCOUNT
		LEFT OUTER JOIN @REST_BY_DATE RD ON (RD.DATE_PROV = JO.DATE_PROV)
		LEFT OUTER JOIN dbo.JOURNAL_OPERATION JO_GK ON (JO_GK.LINK = JO.LEDGER_JOURNAL)
		GROUP BY JO.ORDERS, JO.ACCOUNT, JO.SEP, JO.[DATE], -- JO.DATE_PROV,
			CASE 
				WHEN @strSeparator_Name = 'INDATE' THEN ''
				ELSE SEP.SEP_CODE
			END,
			CASE 
				WHEN @strSeparator_Name = 'INDATE' THEN ISNULL (CONVERT (VARCHAR (10), INDATE, 104), '')
				ELSE SEP.SEP_NAME
			END,	
			ISNULL (SA1.CODE, ''), ISNULL (SA2.CODE, ''), ISNULL (SA3.CODE, ''), JO.SGU1, JO.KBK1, JO.DT,
			JO.SGU2, JO.KBK2, JO.KT, 
			RD.DIN_SUMMA, RD.KIN_SUMMA, RD.DOUT_SUMMA, RD.KOUT_SUMMA,
			DIN_SUM, KIN_SUM, DOUT_SUM, KOUT_SUM, 
			JO.DATE_SORT
		ORDER BY 6, JO.DATE_SORT --, JO.REC_NO
	ELSE		--- @intGrp_Prov = 0	-- Проводки полностью --
		INSERT INTO @TAB_RES
		SELECT JO.ORDERS,
			JO.ACCOUNT,
			JO.AP, JO.SEP,
			@strJO_NUMBER AS JO_CODE,
			@strJO_Name AS JO_NAME,
			@strTXT_TOTAL_DATE AS TOTAL_DATE,
			@strDATE_START AS DATE_START,
			@strDATE_END AS DATE_END,
			@strDATE_NEXT,
			ISNULL (@strORG_OKPO, '') AS DEP_OKPO,
			ISNULL (@strORG_NAME, '') AS DEP_NAME,
			@UCHR_NAME,
			@BUDG_NAME,

			JO.NUMBER AS DOC_NUM,
			CONVERT(VARCHAR(10),JO.DATE,104) AS DOC_DATE,
			JO.DATE, 
			CONVERT(VARCHAR(10), JO.DATE_PROV, 104),
			JO.DATE_PROV, 
			dbo.JurnalProvGetDocKind (JO.LINK_DOC, JO.OBJECT)
				+ ISNULL (' (пров.' + CONVERT (VARCHAR (10), JO.DATE_PROV, 104) + ')', '') AS DOC_NAME,
			ACT_NAME = CASE 
					WHEN @strActivities_Name = 'INDATE' THEN ISNULL (CONVERT (VARCHAR (10), INDATE, 104), '')
					WHEN @strActivities_Name IN ('EKR', 'SGU', 'KBK') THEN AP.AP_CODE
					ELSE AP.AP_NAME
				END,
			SEP_CODE = CASE 
					WHEN @strSeparator_Name = 'INDATE' THEN ''
					ELSE SEP.SEP_CODE
				END,
			SEP_NAME = CASE 
					WHEN @strSeparator_Name = 'INDATE' THEN ISNULL (CONVERT (VARCHAR (10), INDATE, 104), '')
					ELSE SEP.SEP_NAME
				END,	
			NAME_OPER,
			DT_CODE = ISNULL (SA1.CODE, ''),
			KT_CODE = ISNULL (SA2.CODE, ''),
			ACCT_CODE = ISNULL (SA3.CODE, ''),
			dbo.BK_GetAcctFullCode1 (JO.DT, JO.KBK1, JO.SGU1, @intPRN_KBK, @intPRN_SGU) AS DT_LONG,
			dbo.BK_GetAcctFullCode1 (JO.KT, JO.KBK2, JO.SGU2, @intPRN_KBK, @intPRN_SGU) AS KT_LONG,
			JO.SUMMA,
			JO.SUMMA_OB,
			JO.DT_SUMMA,
			JO.KT_SUMMA,
			JO.DT_SUM1,
			JO.KT_SUM1,
			@strSEPARATOR_TITLE AS DIC_NAME,
			DIN_SUM, KIN_SUM,
			DOUT_SUM, KOUT_SUM,
			0, 0, 0, 0,
			0, 0, 0, 0,
			RD.DIN_SUMMA, RD.KIN_SUMMA,
			RD.DOUT_SUMMA, RD.KOUT_SUMMA,
			JO.DOC_CODE, 
			JO.LINK_DOC,
			JO.LINK_G2,
			JO.LEDGER_JOURNAL,
			ISNULL (JO_GK.CODE, ''),
			JO.DATE_SORT,
			CONVERT (VARCHAR (10), JO.DATE_SORT, 104)
		FROM @TAB_OBOROT JO
		INNER JOIN @TAB_ACTIVITIES AP ON (AP.LINK_AP = JO.AP )
		INNER JOIN @TAB_SEPARATOR SEP ON (SEP.LINK_SEP = JO.SEP)
		LEFT OUTER JOIN dbo.S_ACCOUNTS SA1 ON SA1.LINK = JO.DT
		LEFT OUTER JOIN dbo.S_ACCOUNTS SA2 ON SA2.LINK = JO.KT
		LEFT OUTER JOIN dbo.S_ACCOUNTS SA3 ON SA3.LINK = JO.ACCOUNT
		LEFT OUTER JOIN @REST_BY_DATE RD ON (RD.DATE_PROV = JO.DATE_PROV)
		LEFT OUTER JOIN dbo.JOURNAL_OPERATION JO_GK ON (JO_GK.LINK = JO.LEDGER_JOURNAL)
		ORDER BY 6, JO.DATE_SORT, JO.REC_NO

	/* --- ОСТАТКИ --- */
	INSERT INTO @TAB_RES 
	SELECT 0,
		ACCOUNT, 0, SEP,
		@strJO_NUMBER AS JO_CODE,
		@strJO_Name AS JO_NAME,
		@strTXT_TOTAL_DATE AS TOTAL_DATE,
		@strDATE_START AS DATE_START,
		@strDATE_END AS DATE_END,
		@strDATE_NEXT,
		ISNULL (@strORG_OKPO, '') AS DEP_OKPO,
		ISNULL (@strORG_NAME, '') AS DEP_NAME,
		@UCHR_NAME,
		@BUDG_NAME,
		'',
		'',
		NULL,
		'',
		NULL,
		'',
		'',
		SEP.SEP_CODE,
		SEP.SEP_NAME,
		dbo.BK_GetAcctFullCode1 (R.ACCOUNT, R.KBK, 0, @intPRN_KBK_REST, @intPRN_SGU),
		'','',
		'',
		'', '',
		0, 0,
		0, 0,
		0, 0,
		@strSEPARATOR_TITLE,
		D_SUMMA, K_SUMMA,
		0, 0,
		0, 0, 0, 0,
		0, 0, 0, 0,
		0, 0, 0, 0,
		'', 0, 0,
		0, '',	-- ЖО для ГК --,
		NULL, ''
	FROM (SELECT S.ACCOUNT, S.KBK, S.SEP,
		SUM (D_SUMMA) AS D_SUMMA,
		SUM (K_SUMMA) AS K_SUMMA
		FROM @BEGIN_REST S
		GROUP BY S.ACCOUNT, S.KBK, S.SEP) R
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = R.ACCOUNT)
	INNER JOIN @TAB_SEPARATOR SEP ON (SEP.LINK_SEP = R.SEP)
	WHERE R.D_SUMMA <> 0 OR R.K_SUMMA <> 0
		
	INSERT INTO @TAB_RES 
	SELECT 2,
		ACCOUNT, 0, SEP,
		@strJO_NUMBER AS JO_CODE,
		@strJO_Name AS JO_NAME,
		@strTXT_TOTAL_DATE AS TOTAL_DATE,
		@strDATE_START AS DATE_START,
		@strDATE_END AS DATE_END,
		@strDATE_NEXT,
		ISNULL (@strORG_OKPO, '') AS DEP_OKPO,
		ISNULL (@strORG_NAME, '') AS DEP_NAME,
		@UCHR_NAME,
		@BUDG_NAME,
		'',
		'',
		NULL,
		'',
		NULL,
		'',
		'',
		SEP.SEP_CODE,
		SEP.SEP_NAME,
		dbo.BK_GetAcctFullCode1 (R.ACCOUNT, R.KBK, 0, @intPRN_KBK_REST, @intPRN_SGU),
		'','',
		'',
		'', '',
		0, 0,
		0, 0,
		0, 0,
		@strSEPARATOR_TITLE,
		0, 0,
		D_SUMMA, K_SUMMA,
		0, 0, 0, 0,
		0, 0, 0, 0,
		0, 0, 0, 0,
		'', 0, 0,
		0, '',		-- ЖО для ГК --
		NULL, ''
	FROM (SELECT S.ACCOUNT, S.KBK, S.SEP,
		SUM (D_SUMMA) AS D_SUMMA,
		SUM (K_SUMMA) AS K_SUMMA
		FROM @END_REST S
		GROUP BY S.ACCOUNT, S.KBK, S.SEP) R
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = R.ACCOUNT)
	INNER JOIN @TAB_SEPARATOR SEP ON (SEP.LINK_SEP = R.SEP)
	WHERE R.D_SUMMA <> 0 OR R.K_SUMMA <> 0

--SELECT @intFACTOR_TOTAL, @intACCOUNT_TOTAL, @intGRP_DATE 
	IF @intFACTOR_TOTAL = 0 AND @intACCOUNT_TOTAL = 0
		IF @intGRP_DATE = 1 OR @intGRP_DATE = 2
			SELECT *,
				@intFACTOR_TOTAL AS FACT_TOTAL,
				@intACCOUNT_TOTAL AS ACCT_TOTAL,
				@intGRP_DATE AS GRP_DATE 
			FROM @TAB_RES
			WHERE ORDERS = 1
			ORDER BY SEP_CODE, SEP, DATE_SORT, ACCT_CODE, AP, NAME_OPER, DOC_NAME
		ELSE
			SELECT *,
				@intFACTOR_TOTAL AS FACT_TOTAL,
				@intACCOUNT_TOTAL AS ACCT_TOTAL
			FROM @TAB_RES
			ORDER BY SEP_CODE, SEP, ORDERS, dDOC_DATE, DOC_NAME, RIGHT ('0000000000' + DOC_NUM, 8), NAME_OPER 
	ELSE
	BEGIN

		SELECT @TDIN_SUM = SUM (DIN_SUMMA),
			@TKIN_SUM = SUM (KIN_SUMMA),
			@TDOUT_SUM = SUM (DOUT_SUMMA),
			@TKOUT_SUM = SUM (KOUT_SUMMA)
		FROM @TAB_REST

		IF @intTOTAL_MODE = 0
			UPDATE @TAB_RES SET	TDIN_SUM = ISNULL (@TDIN_SUM, 0),
						TKIN_SUM = ISNULL (@TKIN_SUM, 0),
						TDOUT_SUM = ISNULL (@TDOUT_SUM, 0),
						TKOUT_SUM = ISNULL (@TKOUT_SUM, 0),
						FDIN_SUM = ISNULL (T2.DIN_SUM, 0),
						FKIN_SUM = ISNULL (T2.KIN_SUM, 0),
						FDOUT_SUM = ISNULL (T2.DOUT_SUM, 0),
						FKOUT_SUM = ISNULL (T2.KOUT_SUM, 0)
			FROM @TAB_RES T1
			LEFT OUTER JOIN (SELECT AP, SEP,
						SUM (R.DIN_SUMMA) AS DIN_SUM,
						SUM (R.KIN_SUMMA) AS KIN_SUM,
						SUM (R.DOUT_SUMMA) AS DOUT_SUM,
						SUM (R.KOUT_SUMMA) AS KOUT_SUM
					FROM @TAB_REST R
					GROUP BY R.AP, R.SEP) AS T2
				ON T2.AP = T1.AP
					AND T2.SEP = T1.SEP
		ELSE
			UPDATE @TAB_RES SET	TDIN_SUM = ISNULL (@TDIN_SUM, 0),
						TKIN_SUM = ISNULL (@TKIN_SUM, 0),
						TDOUT_SUM = ISNULL (@TDOUT_SUM, 0),
						TKOUT_SUM = ISNULL (@TKOUT_SUM, 0),
						FDIN_SUM = ISNULL (T2.DIN_SUM, 0),
						FKIN_SUM = ISNULL (T2.KIN_SUM, 0),
						FDOUT_SUM = ISNULL (T2.DOUT_SUM, 0),
						FKOUT_SUM = ISNULL (T2.KOUT_SUM, 0)
			FROM @TAB_RES T1
			LEFT OUTER JOIN (SELECT ACCOUNT, SEP,
						SUM (R.DIN_SUMMA) AS DIN_SUM,
						SUM (R.KIN_SUMMA) AS KIN_SUM,
						SUM (R.DOUT_SUMMA) AS DOUT_SUM,
						SUM (R.KOUT_SUMMA) AS KOUT_SUM
					FROM @TAB_REST R
					GROUP BY R.ACCOUNT, R.SEP) AS T2
				ON T2.ACCOUNT = T1.ACCOUNT
					AND T2.SEP = T1.SEP

		IF @intFACTOR_TOTAL = 1 AND @intACCOUNT_TOTAL = 0
			SELECT *,
				@intFACTOR_TOTAL AS FACT_TOTAL,
				@intACCOUNT_TOTAL AS ACCT_TOTAL
			FROM @TAB_RES
			WHERE ORDERS = 1
			ORDER BY SEP_CODE, SEP, ACT_NAME, AP, dDOC_DATE, NAME_OPER, DOC_NAME
		ELSE
			IF @intFACTOR_TOTAL = 0 AND @intACCOUNT_TOTAL = 1
					SELECT *,
						@intFACTOR_TOTAL AS FACT_TOTAL,
						@intACCOUNT_TOTAL AS ACCT_TOTAL
					FROM @TAB_RES
					WHERE ORDERS = 1
					ORDER BY SEP_CODE, SEP, ACCT_CODE, AP, dDOC_DATE, NAME_OPER, DOC_NAME
			ELSE
				IF @intTOTAL_MODE = 0
					SELECT *,
						@intFACTOR_TOTAL AS FACT_TOTAL,
						@intACCOUNT_TOTAL AS ACCT_TOTAL
					FROM @TAB_RES 	
					WHERE ORDERS = 1
					ORDER BY SEP_CODE, SEP, ACT_NAME, AP, ACCT_CODE, dDOC_DATE, NAME_OPER, DOC_NAME
				ELSE
					SELECT *,
						@intFACTOR_TOTAL AS FACT_TOTAL,
						@intACCOUNT_TOTAL AS ACCT_TOTAL,
						@intTOTAL_MODE AS TOTAL_MODE
					FROM @TAB_RES 	
					WHERE ORDERS = 1
					ORDER BY SEP_CODE, SEP, ACCT_CODE, ACT_NAME, AP, dDOC_DATE, NAME_OPER, DOC_NAME
	END

	DECLARE @strGLBUH VARCHAR (254)
	SELECT @strGLBUH = SHORT_NAME
	FROM dbo.GetOtvFaceData (@intORG_LINK, 'Главный бухгалтер')

	/* --- Обороты в ГК --- */
	SELECT ISNULL (dbo.BK_GetAcctFullCode1 (DT, KBK1, SGU1, @intPRN_KBK, @intPRN_SGU), '') AS DT_GK,
		ISNULL (dbo.BK_GetAcctFullCode1 (KT, KBK2, SGU2, @intPRN_KBK, @intPRN_SGU), '') AS KT_GK,
		SUMMA AS SUM_GK,
		@strGLBUH AS GLBUH
	FROM @TAB_OBOROT_GK
	LEFT JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = DT)
	ORDER BY ISNULL (SA.CODE, '9')

	/* --- Клеар буфер --- */
	EXEC dbo.BufferClear @strBUFFER_NAME_ACCOUNT
	EXEC dbo.BufferClear @strBUFFER_NAME_ACTIVE
	EXEC dbo.BufferClear @strBUFFER_NAME_SEPARATOR
	EXEC dbo.BufferClear @strBUFFER_NAME_KL_KBK
END




GO


GRANT EXECUTE ON dbo.[BK_PRINTREP_JO] TO PUBLIC

GO


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

GO
CREATE PROCEDURE dbo.BK_SAVE_DOC_TABLE_MZ_NDS
	@intLINK_ROW	INT = NULL OUTPUT,
	@varKSpLINK_UP	INT,
	@varKSpORDERS	INT,

	@INV_TYPE VARCHAR(30),
	@INV 	INT,
	@PRICE NUMERIC(19, 4) = 0,
	@AKCIZ NUMERIC (19, 4) = 0,
	@NUM_TD VARCHAR(30) = '',
	@QTY NUMERIC(19, 4) = 0,
	@SUMMA NUMERIC(19, 4) = 0,
	@STAVKA_NDS NUMERIC(5, 2) = 0,
	@SUMMA_NDS NUMERIC(19, 4) = 0,
	@SUMMA_ALL NUMERIC(19, 4) = 0,
	@EKR INT = NULL,
	@FIN_SOURCE CHAR(1)= '',
	@NO_NDS	TINYINT = 0,
	@COUNTRY_LINK	INT = NULL,
	@TNDS_LINK	INT = NULL,
	@COMMENT	VARCHAR (1000) = NULL

AS
BEGIN
	DECLARE
		@varKSERROR	tinyint,
		@varKSstrVALUE	varchar(7000),
		@varKStrancount	int,

		@intOBJ_TABLE INT,
		@int@OBJ_COM	INT

	SELECT @intOBJ_TABLE = LINK FROM dbo.S_OBJECTS WITH (NOLOCK) WHERE CODE = 'DOC_TABLE_MZ_NDS'

	SET @varKStrancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON

	EXECUTE @varKSERROR = dbo.X_UPDATE_OUT_TABLE_ROW @intLINK_ROW OUTPUT, @varKSpLINK_UP,
			@intOBJ_TABLE, @varKSpORDERS

	IF @varKSERROR <> 0
		RETURN @varKSERROR

	EXECUTE @varKSERROR = dbo.XK_UPDATE_OUT_TABLE_MZ_SUMMA
			@intLINK_ROW,
			@INV_TYPE, @INV,
			@PRICE, @AKCIZ, @NUM_TD, @QTY, @SUMMA, @STAVKA_NDS,
			@SUMMA_NDS, @SUMMA_ALL, @EKR, @FIN_SOURCE, @NO_NDS,
			@COUNTRY_LINK,
			@TNDS_LINK

	IF @varKSERROR <> 0
		RETURN @varKSERROR

	SET @int@OBJ_COM = dbo.GetObjLink ('DOC_TABLE_MZ_NDS_COMMENT')

	EXECUTE @varKSERROR = dbo.X_UPDATE_OUT_TABLE_STRING
				@varKSLink_Up	=	@intLINK_ROW,
				@varKSObject	=	@int@OBJ_COM,
				@varKSString	=	@COMMENT

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


GO


GRANT EXECUTE ON dbo.[BK_SAVE_DOC_TABLE_MZ_NDS] 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),
	@pTARGETTEXT 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
	@pKIND           CHAR(50),
	@pS_LINK         INT, --Ссылка на свою организацию		
	@pS_ACC_LINK     INT, --Счет своей организации
	@pD_LINK         INT,		
	@pD_ACC_LINK     INT,
	@pORDER          CHAR(1),
	@pPAYKIND        CHAR(5),
	@pREASON         CHAR(5),
	@pSBANK_LINK     INT,	
	@pDBANK_LINK     INT,
	@pNDSKIND        VARCHAR(100),
	@pNDS            INT,
	@pBK_IN_TGT      tinyint,
	@pPRINT_KPP      tinyint,
	@pNDS_LINK       INT,
	@pDOG_LINK       INT,
	@SROK		      Datetime,
	--
	@AVANSE TINYINT,
	@SHORT BIT,
	@BO_NUM char(10),
	@NDS_SUM NUMERIC(18,2)	

--Назначение платежа из шаблона платежки
DECLARE 
	@pDOH_LINK		INT,
	@pSGU_LINK		INT,
	@pOKATO		VARCHAR(11),
	@pP_REASON		VARCHAR(2),
	@pPERIOD1		VARCHAR(2),
	@pPERIOD		VARCHAR(10),
	@pTREBNUM		VARCHAR(30),
	@pTREBDATE		DATETIME,
	@pZERODATE		BIT,
	@pP_TYPE		VARCHAR(2),
	@pSTATUS		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(30), @ACC_CODE VARCHAR(13),
		@trancount INT, @ERROR 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, @LINK_SAL_SFIN INT, @LINK_LACC 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

IF NOT EXISTS (SELECT * FROM dbo.DEPARTMENT_ACCOUNTS T2 WHERE LINK_UP = @LINK_DEP AND [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,
	LINK_LACC
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] = 3
	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, LINK_LACC
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, @LINK_LACC

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  @pKIND = PP.KIND,
				@pD_LINK = PP.D_LINK,
				@pD_ACC_LINK = PP.D_ACC_LINK,
				@pORDER = PP.[ORDER],
				@pPAYKIND = PP.PAYKIND,
				@pREASON = PP.REASON,
				@pSBANK_LINK = PP.SBANK_LINK,		
				@pDBANK_LINK = PP.DBANK_LINK,		
				@pNDSKIND = PP.NDSKIND,	
				@pNDS = PP.NDS,
				@pBK_IN_TGT = PP.BK_IN_TGT,
				@pPRINT_KPP = PP.PRINT_KPP,
				@pNDS_LINK = PP.NDS_LINK,
				@pDOG_LINK = PP.DOG_LINK,
				@SROK 		= PP.SROK,
				@pTARGETTEXT = 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), --Авансовый платеж 
				@pKIND = KIND, --Вид платежа
				@pD_LINK = KOR_LINK, -- Получатель
				@pD_ACC_LINK = KOR_ACC_LINK, --Номер счета получателя 
				@pORDER = [ORDER], --Очередность платежа     
				@pNDS = NDS, --Процент НДС  
				@pNDS_LINK = NDS_LINK, --Шаблон НДС  
				@SROK 		= SROK, --Срок платежа 
				@SHORT = ISNULL(SHORT,0), -- Сокращенная форма заявки
				@pTARGETTEXT = RTRIM(LTRIM(TARGETTEXT)), --Назначение платежа,
				@BO_NUM = ISNULL(BO_NUM,''),
				@UIN = ISNULL(UIN_CODE,'')
			FROM dbo.BB_ZAYAVKA_KR WHERE LINK = @SHABLON_LINK			
		
		SET @BO_NUM = ISNULL(@BO_NUM,'')
		SET @AVANSE = ISNULL(@AVANSE,'')
		SET @SHORT = ISNULL(@SHORT,0)
	
		--Назначение платежа из шаблона платежки
		SELECT
			@pDOH_LINK       = DOH_LINK,
			@isNALOG	      = DOH_LINK,
			@pSGU_LINK       = SGU_LINK,
			@pOKATO          = OKATO,
			@pP_REASON  = P_REASON,
			@pPERIOD1         = LEFT(PERIOD,2),
			@pTREBNUM        = '0',
			@pTREBDATE       = @DATE_PP,
			@pZERODATE       = ZERODATE,
			@pP_TYPE         = P_TYPE,
			@pSTATUS         = STATUS,
			@UIN = ISNULL(UIN_CODE,'')
		from dbo.DOCUMENTS_PAY_ADD where link = @SHABLON_LINK
	
		SET @pD_ACC_LINK = COALESCE(@LINK_ACC,@pD_ACC_LINK)
		SET @pDOH_LINK = COALESCE(@LINK_DOH,@pDOH_LINK)
		SET @pTARGETTEXT = @pTARGETTEXT + case when @SALARY_OPTIONS_OPT9 = 1 then CASE WHEN LEN(@pTARGETTEXT) > 0 THEN ', ' else '' end + RTRIM(LTRIM(@P_NAME)) ELSE '' END	
		SET @pTARGETTEXT = @pTARGETTEXT + case when @SALARY_OPTIONS_OPT11 = 1 then CASE WHEN LEN(@pTARGETTEXT) > 0 AND LEN(RTRIM(LTRIM(@REG_NUM))) >0 THEN ', рег.номер ' else '' end + RTRIM(LTRIM(@REG_NUM)) ELSE '' END	
		SET @pSGU_LINK = COALESCE(@LINK_SGU,@pSGU_LINK)
		SET @pPERIOD = @pPERIOD1 + 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 @trancount = @@TRANCOUNT
		SET IMPLICIT_TRANSACTIONS ON
		BEGIN TRAN 
		COMMIT TRAN
	
		IF @ERROR <> 0
			RETURN @ERROR

		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

		IF @pD_ACC_LINK IS NULL
		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				
	
		--вначале поставим любой, потом вычислим точнее и заменим
		SET @pS_ACC_LINK = dbo.SA_GET_DEP_ACC(@LINK_DEP, DEFAULT, DEFAULT, DEFAULT)
	
		-- Сохраняем ПП 
		Set @LINK_PP = NULL
		IF @iCreatePP = 0 BEGIN
			exec X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_PP, @DATE_PROV, @SUMMA_PP, '',
				@pKIND, @pS_LINK, @pS_ACC_LINK, @pD_LINK, @pD_ACC_LINK,
				@SROK, @pORDER, @pPAYKIND, @pREASON, --@pSBANK_LINK, @pDBANK_LINK,
				@pTARGETTEXT, /*@pNDSKIND, */@pNDS, @pBK_IN_TGT, @pPRINT_KPP,
				@pNDS_LINK, /*@pDOG_LINK*/ 'DOCUMENTS_PAY'

			-- Сохраняем назначение платежа
			IF COALESCE(@isNALOG,0) <> 0 
				exec X_SAVE_DOCUMENTS_PAY_ADD @LINK_PP OUT, @pDOH_LINK, @pSGU_LINK, @pOKATO, @pP_REASON,
					 @pPERIOD, @pTREBNUM, @DATE_PP, @pZERODATE, @pP_TYPE, @pSTATUS, @UIN
		END
		ELSE BEGIN
			EXEC dbo.X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_PP, @DATE_PROV, @SUMMA_PP, '',
				@pKIND, @pS_LINK, @pS_ACC_LINK, @pD_LINK, @pD_ACC_LINK,
				@SROK, @pORDER, NULL, DEFAULT, 
				@pTARGETTEXT, @pNDS, @pBK_IN_TGT, NULL,
				@pNDS_LINK, 'BB_ZAYAVKA_KR'

			SET @NDS_SUM = ISNULL(@SUMMA_PP * ISNULL(@pNDS,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, @pDOH_LINK, @pSGU_LINK, @pOKATO, @pP_REASON,
				 @pPERIOD, @pTREBNUM, @DATE_PP, @pZERODATE, @pP_TYPE, @pSTATUS, @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),
				F.LINK			
			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
				AND ISNULL(F.LINK_LACC,0) = ISNULL(@LINK_LACC,0)
			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, F.LINK
		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, @LINK_SAL_SFIN
		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, @pD_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
					
					SET @pS_ACC_LINK = dbo.SA_GET_DEP_ACC(@LINK_DEP, @Account2, @LINK_SAL_SFIN, DEFAULT)

					UPDATE dbo.G_PROV SET ACC = @pS_ACC_LINK WHERE LINK = @LINK_PP

					exec X_UPDATE_G_PROV_AP @P2, 1, @Account2, @LINK_KBK, @LINK_EKR, @LINK_DEP /*отправитель*/, NULL, NULL, NULL, NULL, @LINK_KAU, @pS_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, @LINK_SAL_SFIN
		END
		
		CLOSE @Cur
		DEALLOCATE @Cur
		
		--
		UPDATE dbo.G_PROV SET SUMMA = @SUMMA_PP WHERE LINK = @LINK_PP
		
		--
		IF @@TRANCOUNT > @trancount 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, @LINK_LACC
END

CLOSE @Cur1
DEALLOCATE @Cur1

IF @LINK_OBJ_DOCUMENTS_DGH = @LINK_OBJ BEGIN
	/*Создадим платежку на перечисление НДФЛ*/
	SET @P1 = 0
	EXEC dbo.SA_CREATE_PP @LINK_PP = @P1 OUT, @LINK_DOC = @LINK_DOC, @DATE_DOC = @DATE_DOC, @P = 1, @CLEAR_SAL_WORNINGS = 0
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.[BK_REPORT_SV_EMPL]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_REPORT_SV_EMPL]

GO


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

CREATE PROCEDURE dbo.BK_REPORT_SV_EMPL
	@varKSdDate1	DATETIME			,
	@varKScVal1 char(1), @varKSnOtborLink1 int	,
	@varKScVal2 char(1), @varKSnOtborLink2 int	,
	@varKScVal3 char(1), @varKSnOtborLink3 int	,
	@varKSnPRN_KBK INT				,
	@varKSnPRN_SGU INT				,
	@intREPORT_EMPL INT				,
	@varKScOtborAccount	VARCHAR (100),
	@cVal_KBK char(1), @nOtborLinkKBK int	/* Отбор КБК */,
	@intSVOD_ZB INT,
	@intPRN_INV_PLACE	INT = 0
AS
BEGIN
	DECLARE	@varKSDIC_EMP	INT,
		@varKSDEP_LINK	INT,
		@varKSORGNAME	VARCHAR(254),
		@strREP_NAME	VARCHAR (254),
		@dDATE_REST	DATETIME

	SET @intPRN_INV_PLACE = ISNULL (@intPRN_INV_PLACE, 0)

	DECLARE @DEP TABLE (DEP [INT], DEP_CODE  [VARCHAR] (20), DEP_NAME [VARCHAR] (254) )
	IF LEN(@varKScVal1)>0 BEGIN
		INSERT INTO @DEP
			SELECT OVR.RECORD, D.CODE, D.[NAME]
			FROM OBJECT_VAR_DEPARTMENT OVR, DICTIONARY_DEPARTMENT D
			WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@varKSnOtborLink1
	END
	ELSE
	BEGIN
		INSERT INTO @DEP
			SELECT D.LINK, D.CODE, D.[NAME] FROM DICTIONARY_DEPARTMENT D
		INSERT INTO @DEP VALUES (0, '', 'Не указан')
	END

	DECLARE @EMP TABLE (LINK_EMP [INT], EMP_CODE  [VARCHAR] (20), EMP_NAME [VARCHAR] (254) )
	IF LEN(@varKScVal2)>0 BEGIN
		INSERT INTO @EMP
			SELECT OVR.RECORD, D.TAB, D.[NAME_EMPL]
			FROM OBJECT_VAR_EMPL OVR, KU_EMPL_PLACING D
			WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@varKSnOtborLink2
	END
	ELSE
	BEGIN
		INSERT INTO @EMP
			SELECT D.LINK, D.TAB, D.[NAME_EMPL] FROM KU_EMPL_PLACING D
		INSERT INTO @EMP VALUES (0, '', 'Не указан')
	END

	DECLARE @ACCT TABLE (LINK_ACCT [INT])
	IF LEN (@varKScVal3) > 0
		INSERT INTO @ACCT
		SELECT RECORD
		FROM OBJECT_VAR_ACCT
		WHERE LINK_UP = @varKSnOtborLink3
	ELSE
		INSERT INTO @ACCT
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode (DEFAULT, DEFAULT, DEFAULT, DEFAULT) ACCT
		INNER JOIN dbo.BK_GetValuesTableBySTR (@varKScOtborAccount, DEFAULT) T1 ON (T1.VALUE = ACCT.cSINTH)
		UNION ALL
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode ('201', '05', DEFAULT, DEFAULT) ACCT
		UNION ALL
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode ('201', '35', DEFAULT, DEFAULT) ACCT

	--- ОТБОР КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	/* -- Параметры организации -- */
	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)
	SET @varKSDEP_LINK = dbo.BK_GetDepZB ()

	IF @intSVOD_ZB = 1 OR @varKSDEP_LINK IS NULL
		SET @varKSDEP_LINK = dbo.GetOwnDepLink()

	SELECT @varKSDEP_LINK = LINK,
		@varKSORGNAME = [NAME]
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @varKSDEP_LINK

	IF @intSVOD_ZB = 1
		SET @varKSORGNAME = RTRIM (@varKSORGNAME) + ' (ЦБ)'

--	SET @dDATE_REST = DATEADD (DAY, 1, @varKSdDate1)
	SET @dDATE_REST = @varKSdDate1

	DECLARE @TABLE1 TABLE (DEP [INT], ACCOUNT [INT], INV [INT], NOMEN [INT], EMP [INT],
			KBK [INT], KOSGU [INT],
			PRICE NUMERIC (28,6), PRICE_TYPE TINYINT,
			SUMMA [NUMERIC] (20,4), QTY [NUMERIC] (20,4))  

	INSERT INTO @TABLE1
	SELECT ISNULL (T1.DEP, 0),
		T1.ACCOUNT,
		ISNULL (T1.INV, 0),
		ISNULL (T1.NOMEN, 0),
		CASE
			WHEN @intREPORT_EMPL = 1 THEN ISNULL (T1.EMP, 0)
			ELSE 0
		END,
		CASE
			WHEN @varKSnPRN_KBK = 1 THEN ISNULL (T1.KBK, 0)
			ELSE 0
		END,
		CASE
			WHEN @varKSnPRN_SGU = 1 THEN ISNULL (T1.SGU, 0)
			ELSE 0
		END,
		CASE WHEN PRICE_TYPE = 1 THEN PRICE ELSE 0 END,
		PRICE_TYPE,
		SUM (T1.D_SUMMA), SUM (T1.D_QuantiTY)
--	FROM dbo.ARestTableByDate (@varKSdDate1, DEFAULT) T1
	FROM dbo.ARestTableByDate (@dDATE_REST, DEFAULT) T1
	INNER JOIN @ACCT AC ON (AC.LINK_ACCT = T1.ACCOUNT)
	INNER JOIN @TAB_KBK T2 ON (T2.LINK_KBK = ISNULL (T1.KBK, 0))
--	WHERE @intSVOD_ZB = 1 
	WHERE (@intSVOD_ZB = 1
			AND T1.DEP_LINK IN (SELECT LINK FROM dbo.DEPARTMENTS WHERE ZB = 1 OR [TYPE] = 4))
		OR (@intSVOD_ZB = 0 AND T1.DEP_LINK = @varKSDEP_LINK)
	GROUP BY  ISNULL (T1.DEP, 0),
		T1.ACCOUNT,
		ISNULL (T1.INV, 0),
		ISNULL (T1.NOMEN, 0),
		CASE
			WHEN @intREPORT_EMPL = 1 THEN ISNULL (T1.EMP, 0)
			ELSE 0
		END,
		CASE
			WHEN @varKSnPRN_KBK = 1 THEN ISNULL (T1.KBK, 0)
			ELSE 0
		END,
		CASE
			WHEN @varKSnPRN_SGU = 1 THEN ISNULL (T1.SGU, 0)
			ELSE 0
		END,
		CASE WHEN PRICE_TYPE = 1 THEN PRICE ELSE 0 END,
		PRICE_TYPE

	SET @strREP_NAME = ''
	IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS, @ACCT WHERE LINK_ACCT = LINK AND cSINTH = '101')
		SET @strREP_NAME = 'ОСНОВНЫХ СРЕДСТВ'

	IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS, @ACCT WHERE LINK_ACCT = LINK AND cSINTH = '105')
		SET @strREP_NAME = @strREP_NAME + CASE
							WHEN @strREP_NAME = '' THEN ''
							ELSE ', '
						END 
			+ 'МАТЕРИАЛЬНЫХ ЗАПАСОВ'
	
	IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS, @ACCT WHERE LINK_ACCT = LINK AND cSINTH = '201')
		SET @strREP_NAME = @strREP_NAME + CASE
							WHEN @strREP_NAME = '' THEN ''
							ELSE ', '
						END 
			+ 'ДЕНЕЖНЫХ ДОКУМЕНТОВ'

	DECLARE @RESULT TABLE (DEP [INT], ACCOUNT [INT], INV [INT], EMP [INT],
			DEP_CODE [VARCHAR] (20), DEP_NAME [VARCHAR] (254),
			ACCT_GR [VARCHAR] (20), ACCT_CODE [VARCHAR] (60), 
			INV_CODE [VARCHAR] (20), INV_NAME [VARCHAR] (254),
			UM_CODE [VARCHAR] (20), UM_NAME [VARCHAR] (254),
			PRICE [NUMERIC] (20,4),	PRICE_TYPE TINYINT,
			EMP_CODE [VARCHAR] (20), EMP_NAME [VARCHAR] (254),
			SUMMA [NUMERIC] (20,4), QTY [NUMERIC] (20,4),
			PLACE_CODE VARCHAR (10), PLACE_NAME VARCHAR (254), 
			ORGNAME [VARCHAR] (254),
			REP_NAME [VARCHAR] (254),
			SORT1 VARCHAR (30),
			PRN_PLACE INT)

	INSERT INTO @RESULT
	SELECT T1.DEP,
		T1.ACCOUNT,
		T1.INV,
		T1.EMP,
		DEP.DEP_CODE,
		DEP.DEP_NAME,
		SA.CODE,
		dbo.BK_GetAcctFullCode1 (T1.ACCOUNT, T1.KBK, T1.KOSGU, @varKSnPRN_KBK, @varKSnPRN_SGU),
		ISNULL (INV.CODE, ISNULL (NOMEN.CODE, '')),	
		ISNULL (INV.[NAME], ISNULL (NOMEN.NAME, '')),	
		'',	
		ISNULL (INV.[NAME_UM], ISNULL (NOMEN.[NAME_UM], '')),
--		ISNULL (INV.BALANCE, 0),
		T1.PRICE, T1.PRICE_TYPE,
		EMP.EMP_CODE,
		EMP.EMP_NAME,
		T1.SUMMA, T1.QTY,
		ISNULL (INV_DOP.PLACE_CODE, ''),		
		ISNULL (INV_DOP.LOCATION, ''),
		@varKSORGNAME,
		@strREP_NAME,
		'',
		@intPRN_INV_PLACE
	FROM @TABLE1 T1
	INNER JOIN @EMP EMP ON (EMP.LINK_EMP = T1.EMP)
	INNER JOIN @DEP DEP ON (DEP.DEP = T1.DEP)
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = T1.ACCOUNT)
	LEFT JOIN dbo.BV_NOMENCLATURE NOMEN ON (NOMEN.LINK = T1.NOMEN)
	LEFT JOIN dbo.INVENTORY_CARD INV ON (INV.LINK = T1.INV)
	LEFT JOIN dbo.BV_INVENTORY_CARD_DOP INV_DOP ON (INV_DOP.LINK_UP = INV.LINK)
	WHERE (T1.SUMMA <> 0) OR (T1.QTY <> 0)


	UPDATE @RESULT SET PRICE = SUMMA / QTY
	WHERE PRICE = 0 AND QTY <> 0 AND PRICE_TYPE = 0

/*
	UPDATE @RESULT SET SORT1 = RIGHT ('00000000000000000000000000000000' + RTRIM (INV_CODE), 30),
		PRICE = CASE
				WHEN PRICE = 0 AND QTY <> 0 AND PRICE_TYPE = 0 THEN SUMMA / QTY
				ELSE PRICE
			END
*/
	SELECT * 
	FROM @RESULT
	ORDER BY DEP_CODE, EMP_CODE, ACCT_GR, ACCT_CODE,
		RIGHT ('00000000000000000000000000000000' + RTRIM (INV_CODE), 30)
END



GO


GRANT EXECUTE ON dbo.[BK_REPORT_SV_EMPL] 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 -- Признак для подавления проверки на существование платежек
					-- Проверка выполняется в другом месте
			,@CLEAR_SAL_WORNINGS TINYINT = 1
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

/*Очистить старые сообщения об ошибках*/
IF @CLEAR_SAL_WORNINGS = 1
	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
	@pKIND           CHAR(50),
	@pS_LINK         INT,		
	@pS_ACC_LINK     INT,
	@pD_LINK         INT,		
	@pD_ACC_LINK     INT,
	@pORDER          CHAR(1),
	@pPAYKIND        CHAR(5),
	@pREASON         CHAR(5),
	@pSBANK_LINK     INT,	
	@pDBANK_LINK     INT,
	@pNDSKIND        VARCHAR(100),
	@pNDS            INT,
	@pBK_IN_TGT      tinyint,
	@pPRINT_KPP      tinyint,
	@pNDS_LINK       INT,
	@pDOG_LINK       INT,
	@SROK		      Datetime,
	@pTARGETTEXT     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)

IF @iCreatePP = 0
	--Реквизиты ПП
	SELECT  
		@pKIND = PP.KIND, --Вид платежа
		@pD_LINK = PP.D_LINK, -- Получатель
		@pD_ACC_LINK = PP.D_ACC_LINK, --Номер счета получателя 
		@pORDER = PP.[ORDER], --Очередность платежа     
		@pPAYKIND = PP.PAYKIND, --Вид оплаты   
		@pREASON = PP.REASON, --Назначение  
		@pSBANK_LINK = PP.SBANK_LINK, --банк плательщика		
		@pDBANK_LINK = PP.DBANK_LINK,	--банк получателя	
		@pNDSKIND = PP.NDSKIND, --Указание НДС 	
		@pNDS = PP.NDS, --Процент НДС  
		@pBK_IN_TGT = PP.BK_IN_TGT, --Показать БК в назначении платежа  
		@pPRINT_KPP = PP.PRINT_KPP, --Показывать КПП   
		@pNDS_LINK = PP.NDS_LINK, --Шаблон НДС  
		@pDOG_LINK = PP.DOG_LINK, -- Номер договора 
		@SROK 		= PP.SROK, --Срок платежа   
		@pTARGETTEXT = RTRIM(LTRIM(PP.TARGETTEXT)), --Назначение платежа 
		@BO_NUM = ''
	FROM dbo.DOCUMENTS_PAY PP
	WHERE 
		PP.LINK = @SHABLON_LINK
ELSE
	SELECT  
		@AVANSE = ISNULL(AVANSE,0), --Авансовый платеж 
		@pKIND = KIND, --Вид платежа
		@pD_LINK = KOR_LINK, -- Получатель
		@pD_ACC_LINK = KOR_ACC_LINK, --Номер счета получателя 
		@pORDER = [ORDER], --Очередность платежа     
		@pNDS = NDS, --Процент НДС  
		@pNDS_LINK = NDS_LINK, --Шаблон НДС  
		@SROK 		= SROK, --Срок платежа 
		@SHORT = ISNULL(SHORT,0), -- Сокращенная форма заявки
		@pTARGETTEXT = RTRIM(LTRIM(TARGETTEXT)), --Назначение платежа,
		@BO_NUM = ISNULL(BO_NUM,''),
		@UIN = ISNULL(UIN_CODE,'')
	FROM dbo.BB_ZAYAVKA_KR WHERE LINK = @SHABLON_LINK		

SET @BO_NUM = ISNULL(@BO_NUM,'')
SET @AVANSE = ISNULL(@AVANSE,'')
SET @SHORT = ISNULL(@SHORT,0)

DECLARE 
	@pDOH_LINK       INT,
	@pSGU_LINK       INT,
	@pOKATO          VARCHAR(11),
	@pP_REASON       VARCHAR(2),
	@pPERIOD1         VARCHAR(2),
	@pPERIOD         VARCHAR(10),
	@pTREBNUM        VARCHAR(30),
	@pTREBDATE       DATETIME,
	@pZERODATE       BIT,
	@pP_TYPE         VARCHAR(2),
	@pSTATUS         VARCHAR(2),
	@DAY			INT,
	@DT_FULL_CODE_ACC VARCHAR(13),
	@KD_FULL_CODE_ACC VARCHAR(13),
	@ACC_NAME varchar(15)	

--Реквизиты назначения платежа
SELECT
	@pDOH_LINK       = DOH_LINK, --Код дохода
	@pSGU_LINK       = SGU_LINK, --ОСГУ
	@pOKATO          = OKATO, --Код окато
	@pP_REASON       = P_REASON, --Основание платежа
	@pPERIOD1        = LEFT(PERIOD,2), --налоговый период
	@pTREBNUM        = '0', -- Номер требования
	@pTREBDATE       = @DATE_PP, --Дата документа
	@pZERODATE       = ZERODATE, --Дата документа = 0
	@pP_TYPE         = P_TYPE, --Тип платежа
	@pSTATUS         = [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 * FROM dbo.DEPARTMENT_ACCOUNTS T2 WHERE LINK_UP = @LINK_DEP AND [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(30), @ACC_CODE VARCHAR(13),
	@trancount INT, @ERROR 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),
	@pTARGETTEXT + case when dbo.sa_get_option_by_code('SALARY_OPTIONS_OPT9') = 1 then CASE WHEN LEN(@pTARGETTEXT) > 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, @pTARGETTEXT, @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 @pPERIOD = @pPERIOD1 + 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 @pD_ACC_LINK = COALESCE(@LINK_ACC,@pD_ACC_LINK)
		SET @pDOH_LINK = COALESCE(@LINK_DOH,@pDOH_LINK)
		SET @pD_LINK = COALESCE(@LINK_ORG,@pD_LINK)
		---

			
		IF @pD_ACC_LINK is null OR @pD_ACC_LINK is null OR @pD_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 @trancount = @@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	

		--вначале поставим любой, потом вычислим точнее и заменим
		SET @pS_ACC_LINK = dbo.SA_GET_DEP_ACC(@LINK_DEP, DEFAULT, DEFAULT, DEFAULT)

		-- Сохраняем ПП 
		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, '',
				@pKIND, @pS_LINK, @pS_ACC_LINK, @pD_LINK, @pD_ACC_LINK,
				@SROK, @pORDER, @pPAYKIND, @pREASON,
				@pTARGETTEXT, @pNDS, @pBK_IN_TGT, @pPRINT_KPP,
				@pNDS_LINK, 'DOCUMENTS_PAY'

			EXEC dbo.X_SAVE_DOCUMENTS_PAY_ADD @LINK_PP OUT, @pDOH_LINK, @pSGU_LINK, @pOKATO, @pP_REASON,
				 @pPERIOD, @pTREBNUM, @DATE_PP, @pZERODATE, @pP_TYPE, @pSTATUS, @UIN
		END		 
		ELSE
		BEGIN
			EXEC dbo.X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_PP, @DATE_PROV, @SUMMA_PP, '',
				@pKIND, @pS_LINK, @pS_ACC_LINK, @pD_LINK, @pD_ACC_LINK,
				@SROK, @pORDER, NULL, DEFAULT, 
				@pTARGETTEXT, @pNDS, @pBK_IN_TGT, NULL,
				@pNDS_LINK, 'BB_ZAYAVKA_KR'

			SET @NDS_SUM = ISNULL(@SUMMA_PP * ISNULL(@pNDS,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, @pDOH_LINK, @pSGU_LINK, @pOKATO, @pP_REASON,
				 @pPERIOD, @pTREBNUM, @DATE_PP, @pZERODATE, @pP_TYPE, @pSTATUS, @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, @pD_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	
					
					SET @pS_ACC_LINK = dbo.SA_GET_DEP_ACC(@LINK_DEP, @Account2, @LINK_SFIN, DEFAULT)

					UPDATE dbo.G_PROV SET ACC = @pS_ACC_LINK WHERE LINK = @LINK_PP

					exec X_UPDATE_G_PROV_AP @P2, 1, @Account2, @LINK_KBK, @LINK_EKR, @LINK_DEP /*отправитель*/, @SUBDIV_HEAD, NULL, NULL, NULL, @LINK_KAU, @pS_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 > @trancount 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, @pTARGETTEXT, @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.[FI_FINANS_TABLE_SELECT]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[FI_FINANS_TABLE_SELECT]

GO



CREATE              PROCEDURE [dbo].FI_FINANS_TABLE_SELECT
	@varKSiLink	int,
	@varKSintSummaType	tinyint = 1,
	@varKSintTypeKBK	tinyint = 1 

AS
IF @varKSiLink = 0 
BEGIN
	IF @varKSintSummaType = 2
		SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * FROM dbo.FINANS_TABLE_MONTHS_1000 WHERE LINK_UP = 0
	ELSE
		SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * FROM dbo.FINANS_TABLE_MONTHS WHERE LINK_UP = 0
RETURN 1
END
DECLARE	@varKSintLimType	tinyint,
	@varKSintLimPer	tinyint,
	@varKScObjCode	varchar(30)

SELECT @varKScObjCode = code from s_objects where link = (select object from g_prov where link = @varKSiLink)
IF len(coalesce(@varKScObjCode,''))=0 
	RETURN -1

IF @varKScObjCode like '%_LIMIT%'
	SELECT	@varKSintLimType = max(FIN_LIM_TYPE),
		@varKSintLimPer = max(FIN_LIM_PER) FROM WorkMode

IF @varKScObjCode like '%_ASSIGN%' or @varKScObjCode like '%_SMETA%' or @varKScObjCode = 'FB_PLAN_FHD'
	SELECT	@varKSintLimType = 0,
		@varKSintLimPer = max(FIN_SMETA_PER) FROM WorkMode

IF @varKScObjCode = 'FB_RESULT_FINANS'
	SELECT	@varKSintLimType = 1, @varKSintLimPer = 3 

IF @varKScObjCode like 'FB_PLAN'
	SELECT	@varKSintLimType = 0, @varKSintLimPer = PERIOD from dbo.FB_PLAN_OPTIONS

IF @varKScObjCode like 'FB_PLAN_D'
	SELECT	@varKSintLimType = 0, @varKSintLimPer = PERIOD from dbo.FB_PLAN_D_OPTIONS

IF @varKScObjCode like 'FB_ZAYAVKA'
	SELECT	@varKSintLimType = 0, @varKSintLimPer = PERIOD from dbo.FB_ZAYAVKA_OPTIONS

IF ISNULL (@varKSintLimPer, 0) = 0
	SET @varKSintLimPer = 1

IF @varKSintSummaType = 2 
BEGIN 
	IF @varKSintLimPer = 1 OR @varKSintLimType = 1
		SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * 
		FROM dbo.FINANS_TABLE_YEAR_1000 
		WHERE LINK_UP = @varKSiLink and (TYPE_KBK & @varKSintTypeKBK) > 0
	IF @varKSintLimPer = 2 AND @varKSintLimType = 0
		SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * 
		FROM dbo.FINANS_TABLE_QUARTERS_1000 
		WHERE LINK_UP = @varKSiLink and (TYPE_KBK & @varKSintTypeKBK) > 0
	IF @varKSintLimPer = 3 AND @varKSintLimType = 0
		SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * 
		FROM dbo.FINANS_TABLE_MONTHS_1000 
		WHERE LINK_UP = @varKSiLink and (TYPE_KBK & @varKSintTypeKBK) > 0
END
ELSE
BEGIN	
	IF @varKSintLimPer = 1 OR @varKSintLimType = 1
		SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * 
		FROM dbo.FINANS_TABLE_YEAR 
		WHERE LINK_UP = @varKSiLink and (TYPE_KBK & @varKSintTypeKBK) > 0
	IF @varKSintLimPer = 2 AND @varKSintLimType = 0
		SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * 
		FROM dbo.FINANS_TABLE_QUARTERS 
		WHERE LINK_UP = @varKSiLink and (TYPE_KBK & @varKSintTypeKBK) > 0
	IF @varKSintLimPer = 3 AND @varKSintLimType = 0
		SELECT 0 as CHECKED, 0 as UPD, 0 as DEL, * 
		FROM dbo.FINANS_TABLE_MONTHS 
		WHERE LINK_UP = @varKSiLink and (TYPE_KBK & @varKSintTypeKBK) > 0
END

RETURN 1


GO


GRANT EXECUTE ON dbo.[FI_FINANS_TABLE_SELECT] 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,
	@pTARGETTEXT     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(30), 
	@Fin_Source CHAR(1),
	@LINK_EKR INT,
	@MONTH_BASE INT,
	@YEAR_BASE INT,
	@ACC_CODE VARCHAR(30),
	@UIN VARCHAR(20)
	

DECLARE @trancount INT, @ERROR 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
	@pKIND           CHAR(50),
	@pS_LINK         INT,		
	@pS_ACC_LINK     INT,
	@pD_LINK         INT,		
	@pD_ACC_LINK     INT,
	@pORDER          CHAR(1),
	@pPAYKIND        CHAR(5),
	@pREASON         CHAR(5),
	@pSBANK_LINK     INT,	
	@pDBANK_LINK     INT,
	@pNDSKIND        VARCHAR(100),
	@pNDS            INT,
	@pBK_IN_TGT      tinyint,
	@pPRINT_KPP      tinyint,
	@pNDS_LINK       INT,
	@pDOG_LINK       INT,
	--
	@AVANSE TINYINT,
	@SHORT BIT,
	@BO_NUM char(10),
	@NDS_SUM NUMERIC(18,2)	


IF @iCreatePP = 0
	--Реквизиты ПП
	SELECT  @pKIND = PP.KIND,
		@pD_LINK = PP.D_LINK,
		@pD_ACC_LINK = PP.D_ACC_LINK,
		@pORDER = PP.[ORDER],
		@pPAYKIND = PP.PAYKIND,
		@pREASON = PP.REASON,
		@pSBANK_LINK = PP.SBANK_LINK,		
		@pDBANK_LINK = PP.DBANK_LINK,		
		@pNDSKIND = PP.NDSKIND,	
		@pNDS = PP.NDS,
		@pBK_IN_TGT = PP.BK_IN_TGT,
		@pPRINT_KPP = PP.PRINT_KPP,
		@pNDS_LINK = PP.NDS_LINK,
		@pDOG_LINK = PP.DOG_LINK,
		@pTARGETTEXT = 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), --Авансовый платеж 
		@pKIND = KIND, --Вид платежа
		@pD_LINK = KOR_LINK, -- Получатель
		@pD_ACC_LINK = KOR_ACC_LINK, --Номер счета получателя 
		@pORDER = [ORDER], --Очередность платежа     
		@pNDS = NDS, --Процент НДС  
		@pNDS_LINK = NDS_LINK, --Шаблон НДС  
--		@SROK 		= SROK, --Срок платежа 
		@SHORT = ISNULL(SHORT,0), -- Сокращенная форма заявки
		@pTARGETTEXT = 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,
	@pTARGETTEXT = @pTARGETTEXT + case when dbo.sa_get_option_by_code('SALARY_OPTIONS_OPT9') = 1 then CASE WHEN LEN(@pTARGETTEXT) > 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

IF NOT EXISTS (SELECT * FROM dbo.DEPARTMENT_ACCOUNTS T2 WHERE LINK_UP = @DEP_LINK AND [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, @LINK_SFIN 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,
		F.LINK
	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, F.LINK
	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, @LINK_SFIN
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN	--Формирование расходников для каждого КБК по отдельности

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

		IF @ERROR <> 0
			RETURN @ERROR


		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
		
		SET @pS_ACC_LINK = dbo.SA_GET_DEP_ACC(@DEP_LINK, @Account2, @LINK_SFIN, DEFAULT)
		
		IF COALESCE(@pS_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 @pD_ACC_LINK = @LINK_ACC--COALESCE(@LINK_ACC,@pD_ACC_LINK)
		SET @pD_LINK = @LINK_ORG--COALESCE(@LINK_ORG,@pD_LINK)
		
		IF @iCreatePP = 0 
		BEGIN
			EXEC dbo.X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_VEDOM, @DATE_PROV, 0, '',
				@pKIND, @pS_LINK, @pS_ACC_LINK, @pD_LINK, @pD_ACC_LINK,
				@DATE_VEDOM, @pORDER, @pPAYKIND, @pREASON,
				@pTARGETTEXT, @pNDS, @pBK_IN_TGT, @pPRINT_KPP,
				@pNDS_LINK, 'DOCUMENTS_PAY'
		END		 
		ELSE
		BEGIN
			EXEC dbo.X_SAVE_DOCUMENTS_PAY @LINK_PP OUT, @NUM_PP, @DATE_VEDOM, @DATE_PROV, 0, '',
				@pKIND, @pS_LINK, @pS_ACC_LINK, @pD_LINK, @pD_ACC_LINK,
				@DATE_VEDOM, @pORDER, NULL, DEFAULT, 
				@pTARGETTEXT, @pNDS, @pBK_IN_TGT, NULL,
				@pNDS_LINK, 'BB_ZAYAVKA_KR'

			SET @NDS_SUM = ISNULL(@SUMMA_PP * ISNULL(@pNDS,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, @pD_LINK, NULL, NULL, NULL, NULL, @LINK_KAU, @pD_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, @pS_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 > @trancount 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, @LINK_SFIN
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_CREATE_PROV_N]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_CREATE_PROV_N]

GO

CREATE PROCEDURE [dbo].[SA_CREATE_PROV_N]
	@nMonth INT,
	@nYear INT,
	@DEP_LINK int
AS


DECLARE @varKStrancount int, @varKSERROR int


DECLARE @DATE_CRT DATETIME
SET @DATE_CRT = dbo.ConvertDMY2Date(1,@nMonth, @nYear)
SET @DATE_CRT = dbo.DateEndOfMonth(@DATE_CRT)

DECLARE @LinkEKR211 int,
		@LInkEKR213 int,
		@LinkEKR_R211 int

SELECT @LinkEKR211 = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '211'
SELECT @LinkEKR213 = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '213'
SELECT @LinkEKR_R211 = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = 'R211'

/* Для штатников, кроме НДФЛ и ЕСН*/
SELECT 		
		JC.LINK_PAYS AS [LINK_PAYS],
		 RTRIM(P.NAME) AS [NAME_PAY],
		 RTRIM(P.CODE) AS [CODE_PAY],
		 SUM(JC.SUMMA) AS [SUMMA],
		 JC.PERIOD_END AS [DATE2],
		 [TYP_OPER] = 
				(CASE P.WAY_CALC 
					WHEN 13 THEN (CASE WHEN JC.LINK_EKR = @LinkEKR213 THEN P.LINK_OPER ELSE P.LINK_OPER3 END) 
					WHEN 15 THEN (CASE WHEN JC.LINK_EKR = @LinkEKR_R211 THEN P.LINK_OPER3 ELSE P.LINK_OPER END)
					ELSE P.LINK_OPER 
				END
				),
		 [REF_ORG] = JC.LINK_ORG,
		 [REF_BUD] = JC.LINK_VKR,
		 [REF_EKR] = (CASE WHEN JC.LINK_EKR = @LinkEKR_R211 THEN @LinkEKR211 ELSE JC.LINK_EKR END)
into 
	#tmp
FROM 
	dbo.CALCULATE_JURNAL JC 
	left outer join dbo.PAYS P on P.LINK = JC.LINK_PAYS
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 NOT(JC.LINK_EMPL IS NULL AND JC.PERS_LINK IS NOT NULL)
	AND P.OBJECT = 1
	AND JC.LINK_DEP = @DEP_LINK
GROUP BY 
	P.LINK_OPER,P.LINK_OPER2,P.LINK_OPER3,P.WAY_CALC,JC.LINK_PAYS, JC.PERIOD_END, JC.LINK_ORG, JC.LINK_VKR, JC.LINK_EKR,P.[NAME], P.CODE
UNION ALL
-- Для внештатников 
SELECT 		
	JC.LINK_PAYS AS [LINK_PAYS],
	 RTRIM(P.NAME) AS [NAME_PAY], 
	 RTRIM(P.CODE) AS [CODE_PAY],
	 SUM(JC.SUMMA) AS [SUMMA],
	 JC.PERIOD_END AS [DATE2],
	 [TYP_OPER] = P.LINK_OPER2,
	 [REF_ORG] = NULL,
	 [REF_BUD] = JC.LINK_VKR,
	 [REF_EKR] = JC.LINK_EKR
FROM dbo.CALCULATE_JURNAL JC left outer join dbo.PAYS P on P.LINK = JC.LINK_PAYS
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 (JC.LINK_EMPL IS NULL AND JC.PERS_LINK IS NOT NULL) 
	AND P.WAY_CALC NOT IN (13,14) AND P.OBJECT = 1   
	AND JC.LINK_DEP = @DEP_LINK
GROUP BY P.LINK_OPER,P.LINK_OPER2,JC.LINK_PAYS, JC.PERIOD_END,JC.LINK_VKR, JC.LINK_EKR, P.[NAME],P.CODE

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

DECLARE @P tinyint
SET @P = dbo.sa_get_option_by_code('SALARY_PROV_OPT1')

declare @O_BI_DICTION_KBK int
set @O_BI_DICTION_KBK = (SELECT top 1 LINK FROM S_OBJECTS WHERE CODE = 'BI_DICTION_KBK')

declare @O_DICTIONARY_ITEM int
set @O_DICTIONARY_ITEM = (SELECT top 1 LINK FROM S_OBJECTS WHERE CODE = 'DICTIONARY_ITEM')

DECLARE @Cur CURSOR, @OSNOVANIE VARCHAR(254), @SUM_PROV NUMERIC(20,2), @LINK_GP1 float, @LINK_TYP_OPER int,
	@LINK_PAYS int, @LINK_KBK int, @REF_EKR int, @LINK_KAU int, @LINK_DOP_KL int, @USER_ACC varchar(4), @USER_ACC1 varchar(4),
	@CODE_SFIN VARCHAR(30)

DECLARE @Cur1 CURSOR, @LINK_GP2 int, @NAME_GP2 varchar(250), @ORD_GP2 tinyint, @LINK_GP2_ECONOM_OPER int,
	@NEW_LINK_GP2 int, @d_acc  as int, @new_d_acc as int, @new_k_acc as int, @k_acc     as int, @d_cSource as char(1),	
		@d_cSinth char(3), @d_cAnalit char(2), @d_pKassa bit, @k_cSource char(1), @k_cSinth char(3),	
		@k_cAnalit char(2), @k_pKassa bit, @nFin_Source int, @DEP_LINK_ACC int, @CODE_PAYS VARCHAR(10)

SET @nFin_Source = 1

DECLARE @KBK int, @EKR int, @DEP int, @SUB int, @EMP int, @NOMEN int, @INV int, @KAU int, @DEP_ACC int, @TMC int, 
	@INDATE datetime, @SGU int, @AP1 int, @AP2 int, @AP3 int, @LINK_SAL_SFIN INT

DECLARE @LINK_DOC_SAL INT, @NUM_DOC_SAL VARCHAR(25), @SUM_DOC_SAL NUMERIC(18,2)

INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
select 'Не сформированы проводки для начисления с кодом "' + COALESCE(LTRIM(RTRIM(CODE_PAY)),'') + '"',
	'Не указана типовая операция в настройках этого вида начисления.',
	'Укажите в настройках этого начисления типовую операцию.',
	'SALARY'
FROM #TMP WHERE TYP_OPER IS NULL

-------
SET @Cur = CURSOR FORWARD_ONLY
FOR 

	Select 
		F.CODE,
		LINK_PAYS= (CASE WHEN @P = 1 AND COALESCE(PE.PAYS_EMPL,0) > 0 THEN 0 ELSE t.LINK_PAYS END), 
		NAME_PAY = (CASE WHEN @P = 1 AND COALESCE(PE.PAYS_EMPL,0) > 0 THEN 'Начисление зарплаты' ELSE NAME_PAY END), 
		CODE_PAY = (CASE WHEN @P = 1 AND COALESCE(PE.PAYS_EMPL,0) > 0 THEN '' ELSE CODE_PAY END), 
		TYP_OPER,
		LINK_KBK = F.KBK, 
		REF_EKR,
		LINK_KAU = F.KAU,
		LINK_DOP_KL = F.DOP_KL,
		COALESCE(CAST (F.SOURCE as CHAR(1)),''),
		F.USER_ACC,
		SUMMA= SUM(SUMMA),
		F.LINK 
	from 
		#tmp t 
		inner join dbo.SAL_SFIN F on t.ref_bud = f.link
		left join 
			(select DISTINCT PAYS_EMPL= LINK_PAYS from dbo.PAYS_EMPL
			WHERE @DATE_CRT BETWEEN [DATE] AND COALESCE(dbo.SalaryPaysEmplEndDate(LINK_EMPL,LINK_PAYS, [DATE]),@DATE_CRT)) PE
			ON PE.PAYS_EMPL = t.LINK_PAYS
	group by
		F.CODE, 
		(CASE WHEN @P = 1 AND COALESCE(PE.PAYS_EMPL,0) > 0 THEN 0 ELSE t.LINK_PAYS END),
		(CASE WHEN @P = 1 AND COALESCE(PE.PAYS_EMPL,0) > 0 THEN 'Начисление зарплаты' ELSE NAME_PAY END),
		(CASE WHEN @P = 1 AND COALESCE(PE.PAYS_EMPL,0) > 0 THEN '' ELSE CODE_PAY END),
		TYP_OPER,
		F.KBK,
		REF_EKR,
		F.KAU,
		F.DOP_KL,
		F.SOURCE,
		F.USER_ACC,
		F.LINK
	order by 2
OPEN @Cur
FETCH NEXT FROM @Cur INTO @CODE_SFIN, @LINK_PAYS,@OSNOVANIE,@CODE_PAYS, @LINK_TYP_OPER,@LINK_KBK,@REF_EKR,@LINK_KAU,@LINK_DOP_KL,@nFin_Source,@USER_ACC1,@SUM_PROV,@LINK_SAL_SFIN
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN
		IF COALESCE(@SUM_PROV,0) <> 0 BEGIN

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

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

			IF @LINK_TYP_OPER IS NULL BEGIN
				ROLLBACK
				SET IMPLICIT_TRANSACTIONS OFF
				IF COALESCE(@LINK_PAYS,0) > 0 BEGIN
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформированы проводки для начисления с кодом "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '"',
						'Не указана типовая операция в настройках этого вида начисления.',
						'Укажите в настройках этого начисления типовую операцию.',
						'SALARY'
				END
				GOTO DO_NEXT
			END
			
			-- Сохраняем документ
			SELECT @LINK_DOC_SAL = 0, @NUM_DOC_SAL = NULL
			-- определим максимальный номер
			exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'DOCUMENTS_SALARY', @NUM_DOC_SAL output, @DEP_LINK

			exec X_SAVE_DOCUMENTS_SALARY @LINK_DOC_SAL OUT, @NUM_DOC_SAL, @DATE_CRT, @DATE_CRT, @SUM_PROV, @OSNOVANIE, @DEP_LINK, NULL

			SET @LINK_GP1 = NULL
			exec X_UPDATE_G_PROV1 @LINK_GP1 output, @LINK_DOC_SAL, NULL, @OSNOVANIE, 1
			
			-- Сохраняем проводки (по количеству в типовой операции)
			SET @Cur1 = CURSOR FORWARD_ONLY
			FOR select link, name, orders, econ_oper from dbo.g_prov2 where link_up = @LINK_TYP_OPER
			
			OPEN @Cur1
			FETCH NEXT FROM @Cur1 INTO @LINK_GP2, @NAME_GP2, @ORD_GP2, @LINK_GP2_ECONOM_OPER
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @NEW_LINK_GP2 = 0
				EXEC X_UPDATE_G_PROV2 @NEW_LINK_GP2 output, @LINK_GP1, null, @SUM_PROV, 0, 0, @OSNOVANIE, @LINK_GP2_ECONOM_OPER, @ORD_GP2
				IF @NEW_LINK_GP2 > 0 
				BEGIN
				
					-- проверим, указан ли у хозоперации признак "Документ для зарплаты". Иначе не будет отображаться проводка в зарплате

					IF NOT EXISTS (SELECT * FROM dbo.XOZ_OPER XO WHERE XO.LINK = @LINK_GP2_ECONOM_OPER AND XO.ZP = 1)
					BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформированы проводки для начисления с кодом "' + CASE WHEN COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') <> '' THEN 
					 				COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') ELSE  (Select TOP 1 CODE_PAY from #tmp WHERE TYP_OPER = @LINK_TYP_OPER) END + '"',
							'В настройках Хоз.операции ' + FULLCODE + ' не включен признак "Показывать в подсистеме "Зарплата"' ,
							'Необходимо включить признак "Показывать в подсистеме "Зарплата" у хоз. операции ' + FULLCODE,
							'SALARY'
						FROM dbo.XD_XOZ_OPER WHERE LINK = @LINK_GP2_ECONOM_OPER
						
						GOTO DO_NEXT
					END					
				
					-- проверим если ли в счете код источника финансирования, если нет - добавим
					SELECT	@d_acc = account
					FROM G_PROV_AP WHERE link_UP = @LINK_GP2 and DB_KR = 0

					IF COALESCE(@d_acc,0)= 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформированы проводки для начисления с кодом "' + CASE WHEN COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') <> '' THEN 
					 				COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') ELSE  (Select TOP 1 CODE_PAY from #tmp WHERE TYP_OPER = @LINK_TYP_OPER) END + '"',
							'В настройках указана типовая операция, в которой отсутствует счет дебета' ,
							'Исправьте типовую операцию, указанную в настройках этого начисления',
							'SALARY'
						GOTO DO_NEXT
					END

					--Пользовательский субсчет может быть задан в типовой операции, но требовать его для дебета не нужно, если он задан в источнике финансирования
					SET @d_cSource = CAST (@nFin_Source as CHAR(1))
					SELECT @d_cSinth=cSinth, @d_cAnalit=cAnalit, @USER_ACC = (CASE WHEN COALESCE(RTRIM(LTRIM(cUser)),'') <> '' THEN cUser ELSE @USER_ACC1 END) 
  					FROM s_accounts 
					WHERE link = @d_acc
					
					SET @d_acc = NULL
					-- выбираем @d_acc с учётом вида деятельности, заданного в настройках источника финансирования
					SELECT top 1 @d_acc=link, @d_pKassa = p_KASSA 
					FROM s_accounts
					WHERE 	cSource = @d_cSource AND @d_cSinth = cSinth AND @d_cAnalit=cAnalit

					--Если в плане счетов стоит пользовательский субсчет, а в источнике финансирования или типовой операции не указан
					IF COALESCE(@USER_ACC,0)= 0 and exists (Select link from s_accounts where cSource = @d_cSource AND @d_cSinth = cSinth AND @d_cAnalit=cAnalit and len(cUser) > 0)
					BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформированы проводки для начисления с кодом "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '"',
								'В типовой операции начисления "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '" или источнике финанансирования "' + COALESCE(LTRIM(RTRIM(@CODE_SFIN)),'') + '" не указан пользовательский субсчет'  
								 + 'но в плане счетов у счета ' + COALESCE(@d_cSource,'') + '.' + COALESCE(@d_cSinth,'') + '.' + COALESCE(@d_cAnalit,'') + ' пользовательский субсчет задан!',
								'Укажите пользовательский субсчет в настройках источника финансирования "' + COALESCE(LTRIM(RTRIM(@CODE_SFIN)),'') + '" или уберите субсчет для счета ' + COALESCE(@d_cSource,'') + '.' + COALESCE(@d_cSinth,'') + '.' + COALESCE(@d_cAnalit,'')+  ' из плана счетов',
								'SALARY'
						GOTO DO_NEXT
					END

					IF COALESCE(@d_acc,0)= 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформированы проводки для начисления с кодом "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '"',
								'В источнике финанансирования "' + COALESCE(LTRIM(RTRIM(@CODE_SFIN)),'') + '" указан вид деятельности "' + ISNULL((SELECT TOP 1 FS.CODE + '.' + FS.NAME FROM dbo.BB_FIN_SOURCE FS WHERE FS.CODE = @nFin_Source),'') +  '", ' 
								 + 'но в плане счетов нет счета ' + COALESCE(@d_cSource,'') + '.' + COALESCE(@d_cSinth,'') + '.' + COALESCE(@d_cAnalit,''),
								'Добавьте в план счетов такой счет, либо измените вид деятельности в настройках источника финансирования',
								'SALARY'
						GOTO DO_NEXT
					END

					IF COALESCE(RTRIM(LTRIM(@USER_ACC)),'') <> ''
					BEGIN
						SET @new_d_acc = NULL
						SELECT top 1 @new_d_acc=link, @d_pKassa = p_KASSA 
						FROM s_accounts
						WHERE 	cSource = @d_cSource AND @d_cSinth = cSinth AND @d_cAnalit=cAnalit AND cUser = @USER_ACC

						IF @new_d_acc is not null 
							SET @d_acc=@new_d_acc
						ELSE BEGIN
							ROLLBACK
							SET IMPLICIT_TRANSACTIONS OFF
							INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформированы проводки для начисления с кодом "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '"',
								'В источнике финанансирования "' + COALESCE(LTRIM(RTRIM(@CODE_SFIN)),'') + '" указана пользовательская часть счета, ' 
								 + 'но в плане счетов нет счета ' + COALESCE(@d_cSource,'') + '.' + COALESCE(@d_cSinth,'') + '.' + COALESCE(@d_cAnalit,'') + '/' + COALESCE(@USER_ACC,''),
								'Добавьте в план счетов такой счет, либо уберите пользовательскую часть счета из настроек источника финансирования',
								'SALARY'
							GOTO DO_NEXT
						END
					END

					--===========================================================
					
					SELECT	@k_acc = account
					FROM G_PROV_AP WHERE link_UP = @LINK_GP2 and DB_KR = 1
					
					IF COALESCE(@k_acc,0) = 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
						select 'Не сформированы проводки для начисления с кодом "' + CASE WHEN COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') <> '' THEN 
					 				COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') ELSE  (Select TOP 1 CODE_PAY from #tmp WHERE TYP_OPER = @LINK_TYP_OPER) END + '"',
							'В настройках указана типовая операция, в которой отсутствует счет кредита' ,
							'Исправьте типовую операцию, указанную в настройках этого начисления',
							'SALARY'
						GOTO DO_NEXT
					END


					--Пользовательский субсчет может быть задан в типовой операции. Но если он задан в источнике, то должен быть в дебете обязательно
					SET @k_cSource = CAST (@nFin_Source as CHAR(1))
					SELECT @k_cSinth=cSinth, @k_cAnalit=cAnalit, @USER_ACC = (CASE WHEN COALESCE(RTRIM(LTRIM(@USER_ACC1)),'') <> '' THEN @USER_ACC1 ELSE cUser END)
  					FROM s_accounts 
					WHERE link = @k_acc 
 
 					SET @k_acc = NULL
					-- выбираем @@k_acc с учётом вида деятельности, заданного в настройках источника финансирования
					SELECT top 1 @k_acc=link, @k_pKassa = p_KASSA 
					FROM s_accounts
					WHERE 	cSource = @k_cSource AND @k_cSinth = cSinth AND	@k_cAnalit=cAnalit AND cUser = @USER_ACC

					--Если в плане счетов стоит пользовательский субсчет, а в источнике финансирования или типовой операции не указан
					IF COALESCE(@USER_ACC,0)= 0 and exists (Select link from s_accounts where cSource = @k_cSource AND @k_cSinth = cSinth AND @k_cAnalit=cAnalit and len(cUser) > 0)
					BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформированы проводки для начисления с кодом "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '"',
								'В типовой операции начисления "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '" или источнике финанансирования "' + COALESCE(LTRIM(RTRIM(@CODE_SFIN)),'') + '" не указан пользовательский субсчет'  
								 + 'но в плане счетов у счета ' + COALESCE(@k_cSource,'') + '.' + COALESCE(@k_cSinth,'') + '.' + COALESCE(@k_cAnalit,'') + ' пользовательский субсчет задан!',
								'Укажите пользовательский субсчет в настройках источника финансирования "' + COALESCE(LTRIM(RTRIM(@CODE_SFIN)),'') + '" или уберите субсчет для счета ' + COALESCE(@k_cSource,'') + '.' + COALESCE(@k_cSinth,'') + '.' + COALESCE(@k_cAnalit,'')+  ' из плана счетов',
								'SALARY'
						GOTO DO_NEXT
					END

					IF COALESCE(@k_acc,0)= 0 BEGIN
						ROLLBACK
						SET IMPLICIT_TRANSACTIONS OFF
						INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформированы проводки для начисления с кодом "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '"',
								'В источнике финанансирования "' + COALESCE(LTRIM(RTRIM(@CODE_SFIN)),'') + '" указан вид деятельности "' + ISNULL((SELECT TOP 1 FS.CODE + '.' + FS.NAME FROM dbo.BB_FIN_SOURCE FS WHERE FS.CODE = @nFin_Source),'') +  '", ' 
								 + 'но в плане счетов нет счета ' + COALESCE(@k_cSource,'') + '.' + COALESCE(@k_cSinth,'') + '.' + COALESCE(@k_cAnalit,''),
								'Добавьте в план счетов такой счет, либо измените вид деятельности в настройках источника финансирования',
								'SALARY'
						GOTO DO_NEXT
					END

					IF COALESCE(RTRIM(LTRIM(@USER_ACC)),'') <> ''
					BEGIN
						SET @new_k_acc = NULL
						SELECT top 1 @new_k_acc=link, @k_pKassa = p_KASSA 
						FROM s_accounts
						WHERE 	cSource = @k_cSource AND @k_cSinth = cSinth AND	@k_cAnalit=cAnalit AND cUser = @USER_ACC

						IF @new_k_acc is not null 
							SET @k_acc = @new_k_acc
						ELSE BEGIN
							ROLLBACK
							SET IMPLICIT_TRANSACTIONS OFF
							INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформированы проводки для начисления с кодом "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '"',
								'В источнике финанансирования "' + COALESCE(LTRIM(RTRIM(@CODE_SFIN)),'') + '" указана пользовательская часть счета, '
								 + 'но в плане счетов нет счета ' + COALESCE(@k_cSource,'') + '.' + COALESCE(@k_cSinth,'') + '.' + COALESCE(@k_cAnalit,'') + '/' + COALESCE(@USER_ACC,''),
								'Добавьте в план счетов такой счет, либо уберите пользоательскую часть счета из настроек источника финансирования',
								'SALARY'
							GOTO DO_NEXT
						END
					END

					IF  COALESCE(@d_acc,0) > 0 AND COALESCE(@k_acc,0) > 0 BEGIN
					
						--Проверка на счета, имеющие детей
						IF EXISTS(SELECT * FROM dbo.S_ACCOUNTS SA WHERE SA.LINK_SELF = @d_acc )
						BEGIN
							ROLLBACK
							SET IMPLICIT_TRANSACTIONS OFF
							INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформированы проводки для начисления с кодом "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '"',
								'В проводке определен счет ДТ ' + COALESCE(SA.CODE,'') + ', у которого есть субсчета!',
								'Исправте настройки типовой операции, либо исправьте план счетов.',
								'SALARY'
							FROM dbo.S_ACCOUNTS SA WHERE LINK = @d_acc	
							GOTO DO_NEXT													
						END	

						--Проверка на счета, имеющие детей
						IF EXISTS(SELECT * FROM dbo.S_ACCOUNTS SA WHERE SA.LINK_SELF = @k_acc )
						BEGIN
							ROLLBACK
							SET IMPLICIT_TRANSACTIONS OFF
							INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
							select 'Не сформированы проводки для начисления с кодом "' + COALESCE((LTRIM(RTRIM(@CODE_PAYS))),'') + '"',
								'В проводке определен счет КТ ' + COALESCE(SA.CODE,'') + ', у которого есть субсчета!',
								'Исправте настройки типовой операции, либо исправьте план счетов.',
								'SALARY'
							FROM dbo.S_ACCOUNTS SA WHERE LINK = @k_acc	
							GOTO DO_NEXT													
						END												

						SELECT	
							@KBK = COALESCE(KBK,@LINK_KBK), @EKR = COALESCE(EKR,@REF_EKR), @DEP = COALESCE(DEP,@DEP_LINK), 
							@SUB = SUB, @EMP = EMP, @NOMEN = NOMEN, @INV = INV,
							@KAU = COALESCE(KAU,@LINK_KAU), @TMC = TMC, @INDATE = INDATE, @SGU = SGU,
							@AP1 = AP1, @AP2 = COALESCE(AP2,@LINK_DOP_KL), @AP3 = AP3
						FROM G_PROV_AP WHERE link_UP = @LINK_GP2 and DB_KR = 0

						-- Сохранаем Дт проводки
						if @d_pKassa = 1
							set @SGU = @EKR

						SET @DEP_ACC = dbo.SA_GET_DEP_ACC(@DEP_LINK, @k_acc, @LINK_SAL_SFIN, DEFAULT)
						UPDATE dbo.G_PROV SET ACC = @DEP_ACC WHERE LINK = @LINK_DOC_SAL

						EXEC X_UPDATE_G_PROV_AP @NEW_LINK_GP2, 0, @d_acc, @KBK, @EKR, @DEP,
							@SUB, @EMP, @NOMEN, @INV, @KAU, @DEP_ACC, @TMC, 
							@INDATE, @AP1, @AP2, @AP3, @SGU
	
						SELECT	
							@KBK = COALESCE(KBK,@LINK_KBK), @EKR = COALESCE(EKR,@REF_EKR), @DEP = COALESCE(DEP,@DEP_LINK), 
							@SUB = SUB, @EMP = EMP, @NOMEN = NOMEN, @INV = INV,
							@KAU = COALESCE(KAU,@LINK_KAU), @TMC = TMC, @INDATE = INDATE, @SGU = SGU,
							@AP1 = AP1, @AP2 = COALESCE(AP2,@LINK_DOP_KL), @AP3 = AP3
						FROM G_PROV_AP WHERE link_UP = @LINK_GP2 and DB_KR = 1
	
						-- Сохранаем Кт проводки
						if @k_pKassa = 1
							set @SGU = @EKR

						EXEC X_UPDATE_G_PROV_AP @NEW_LINK_GP2, 1, @k_acc, @KBK, @EKR, @DEP,
							@SUB, @EMP, @NOMEN, @INV, @KAU, @DEP_ACC, @TMC, 
							@INDATE, @AP1, @AP2, @AP3, @SGU

					END

				END

				FETCH NEXT FROM @Cur1 INTO @LINK_GP2, @NAME_GP2, @ORD_GP2, @LINK_GP2_ECONOM_OPER
			
			END
			CLOSE @Cur1
			DEALLOCATE @Cur1

			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 @CODE_SFIN, @LINK_PAYS,@OSNOVANIE,@CODE_PAYS,@LINK_TYP_OPER,@LINK_KBK,@REF_EKR,@LINK_KAU,@LINK_DOP_KL,@nFin_Source,@USER_ACC1,@SUM_PROV,@LINK_SAL_SFIN
END

CLOSE @Cur
DEALLOCATE @Cur

exec X_SALDO_CommitChanges

Return 0




GO


GRANT EXECUTE ON dbo.[SA_CREATE_PROV_N] 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 @LINK int
AS 

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

---
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 = @LINK order by YEAR(SD.PERIOD),MONTH(SD.PERIOD)

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

--- Начало периода, за который предоставляется отпуск
declare @dDateBegin datetime
exec dbo.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,
		INN = de.INN,
		KPP = de.KPP,
		[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 , dbo.departments de
where D.LINK =@LINK AND D.REF_EMPL = EP.LINK and de.LINK = D.LINK_DEP 

----
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 = @LINK --AND NUM BETWEEN 1 AND 12
GROUP BY	[MONTH], [YEAR], [DAY], [HOUR], DAY01, HOUR01, KOEF, NUM, Y, M
ORDER BY 	Y, M

----
select  
	ref, 
	[acc_code],
	[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 
	(
	SELECT 
		[REF]		= SD.LINK_PAY,
		[acc_code] = 
			(
				SELECT TOP 1
					(case when (ISNULL(CONVERT(VARCHAR(1),F.[SOURCE]),'') <> '') then (CONVERT(VARCHAR(1),F.[SOURCE]) + '.') else '' end + rtrim([cSinth]) + case when ([cAnalit] <> '') then ('.' + [cAnalit]) else '' end)
				FROM
					dbo.G_PROV1 G1
					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 AND GAP.DB_KR = 1
					INNER JOIN dbo.S_ACCOUNTS SA ON SA.LINK = GAP.ACCOUNT
				WHERE
					G1.LINK = P.LINK_OPER	
			),	
		[KSUMMA1]		= round(SD.SUMMA1 * coalesce(SD.KOEF1,0),4),
		[KSUMMA2]		= round(SD.SUMMA2 * coalesce(SD.KOEF2,0),4),
		[KSUMMA3]		= round(SD.SUMMA3 * coalesce(SD.KOEF3,0),4),
		[KSUMMA4]		= round(SD.SUMMA4 * coalesce(SD.KOEF4,0),4),
		[KSUMMA5]		= round(SD.SUMMA5 * coalesce(SD.KOEF5,0),4),
		[KSUMMA6]		= round(SD.SUMMA6 * coalesce(SD.KOEF6,0),4),
		[KSUMMA7]		= round(SD.SUMMA7 * coalesce(SD.KOEF7,0),4),
		[KSUMMA8]		= round(SD.SUMMA8 * coalesce(SD.KOEF8,0),4),
		[KSUMMA9]		= round(SD.SUMMA9 * coalesce(SD.KOEF9,0),4),
		[KSUMMA10]		= round(SD.SUMMA10 * coalesce(SD.KOEF10,0),4),
		[KSUMMA11]		= round(SD.SUMMA11 * coalesce(SD.KOEF11,0),4),
		[KSUMMA12]		= round(SD.SUMMA12 * coalesce(SD.KOEF12,0),4)
	FROM 	
		dbo.SDOC_AVAC_TABLE3 SD
		INNER JOIN dbo.PAYS P ON P.LINK = SD.LINK_PAY
		INNER JOIN dbo.SAL_SFIN F ON F.LINK = SD.LINK_KBK
	WHERE
		SD.LINK_UP = @LINK		
	) t1, #Tem T2


--Для расчета по постановлению 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 = @LINK

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 TOP 1 
					(case when (ISNULL(CONVERT(VARCHAR(1),F.[SOURCE]),'') <> '') then (CONVERT(VARCHAR(1),F.[SOURCE]) + '.') else '' end + rtrim([cSinth]) + case when ([cAnalit] <> '') then ('.' + [cAnalit]) else '' end)
				FROM
					dbo.PAYS PS
					INNER JOIN dbo.G_PROV1 G1 ON G1.LINK = PS.LINK_OPER
					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 AND GAP.DB_KR = 1
					INNER JOIN dbo.S_ACCOUNTS SA ON SA.LINK = GAP.ACCOUNT
				WHERE
					PS.LINK = P.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
		INNER JOIN dbo.SAL_SFIN F ON F.LINK = P.LINK_KBK
	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= @LINK )
Set @CurYM = (select min(Year(DATE) * 100 + month(DATE)) from #CurDoc where link= @LINK )

----
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 = @LINK and Year(DATE1) * 100 + month(DATE1) = @CurYM ) ,
[sm_m2] = (select sum(summa) from DOCUMENTS_ADD_FUR_TABLE0 where link = @LINK and Year(DATE1) * 100 + month(DATE1) <> @CurYM),
[sm_d1] = (select top 1 [DAY] from DOCUMENTS_ADD_FUR_TABLE0 where link = @LINK and Year(DATE1) * 100 + month(DATE1) = @CurYM ) ,
[sm_d2] = (select top 1 [DAY]from DOCUMENTS_ADD_FUR_TABLE0 where link = @LINK 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 @acct1 VARCHAR(20), @acct2 VARCHAR(20), @acct3 VARCHAR(20)
SELECT 
	@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)

--В ТАБЛИЦЕ НАЧИСЛЕНИЯ ЗА ОТПУСК ПО ПЕРИОДАМ И ВИДАМ ФО
CREATE TABLE #AVAC_SUM (CURRENT_MONTH TINYINT, SRC TINYINT, SUMMA NUMERIC(18,2))
INSERT INTO #AVAC_SUM (CURRENT_MONTH, SRC, SUMMA)
SELECT 
	CURRENT_MONTH = CASE WHEN YEAR(D.[DATE]) = YEAR(T1.DATE1) AND MONTH(D.[DATE]) = MONTH(T1.DATE1) THEN 1 ELSE 0 END, 
	F.[SOURCE], 
	SUMMA = SUM(T1.SUMMA)
FROM 	
	dbo.SDOC D
	INNER JOIN dbo.SDOC_AVAC_TABLE1 T1 ON D.LINK = T1.LINK_UP
	INNER JOIN dbo.SAL_SFIN F ON F.LINK = T1.LINK_KBK
WHERE
	D.LINK = @LINK	
GROUP BY
	CASE WHEN YEAR(D.[DATE]) = YEAR(T1.DATE1) AND MONTH(D.[DATE]) = MONTH(T1.DATE1) THEN 1 ELSE 0 END,
	F.[SOURCE]	

---
declare @sm_all numeric(20,2), @sr_mes numeric(20,4), @sr_d numeric(20,4), @sm_m1 numeric(20,2), @sm_m2 numeric(20,2)
declare @sum_d1 numeric(18,2), @sum_d2 numeric(18,2)
--select top 1 @sr_mes = isnull(sr_mes, 0), @sr_d = isnull(sr_d, 0), @sm_m1 = isnull(sm_m1, 0), @sm_m2 = isnull(sm_m2, 0) from #v2 set @sr_mes = coalesce((select top 1 sr_mes from #v2),0)

--Вычисление среднемесячного заработка. Для 922 постановления Итого за расчетные мес / 12, по 562 не надо делить
set @sr_mes = coalesce((select SUM(coalesce(summa,0)+coalesce(summa_prem,0) + coalesce(mater,0)) from #Temp),0)
IF @INSTR = 1 
BEGIN
	IF (select COUNT(ORDERS) from #Temp) > 0
		set @sr_mes = COALESCE(@sr_mes,0) / (select COUNT(ORDERS) from #Temp)
END
---
set @sr_d = coalesce((select top 1 sr_d from #v2),0)
set @sm_m1 = ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE CURRENT_MONTH = 1),0)
set @sm_m2 = ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE CURRENT_MONTH = 0),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 @sm_all = sum(sm1+sm2+sm3) from #v2
Set @sm_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 @sm_all = 0 THEN 0.00 ELSE @sr_mes * sum(sm1)/@sm_all END,
	CASE WHEN @sm_all = 0 THEN 0.00 ELSE @sr_mes * sum(sm2)/@sm_all END,
	CASE WHEN @sm_all = 0 THEN 0.00 ELSE @sr_mes * sum(sm3)/@sm_all END,
	@acct1, @acct2, @acct3,
	@sr_mes, @sr_d, @sm_m1, @sm_m2,
	@sr_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 @sm_all = 0 THEN 0.00 ELSE @sr_d * sum(sm1)/@sm_all END,
	CASE WHEN @sm_all = 0 THEN 0.00 ELSE @sr_d * sum(sm2)/@sm_all END,
	CASE WHEN @sm_all = 0 THEN 0.00 ELSE @sr_d * sum(sm3)/@sm_all END,
	@acct1, @acct2, @acct3,
	@sr_d, @sr_d, @sm_m1, @sm_m2,
	@sr_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,
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE CURRENT_MONTH = 1 AND SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 1)),0),
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE CURRENT_MONTH = 1 AND SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 2)),0),
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE CURRENT_MONTH = 1 AND SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 3)),0),
	@acct1, @acct2, @acct3, @sr_d, @sr_d, 
	@sm_m1, 
	@sm_m2, 
	@sm_m1

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,
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE CURRENT_MONTH = 0 AND SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 1)),0),
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE CURRENT_MONTH = 0 AND SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 2)),0),
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE CURRENT_MONTH = 0 AND SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 3)),0),
	@acct1, @acct2, @acct3, @sr_d, @sr_d, 
	@sm_m1, 
	@sm_m2, 
	@sm_m2

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,
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 1)),0),
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 2)),0),
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 3)),0),	
	@acct1, @acct2, @acct3,
	@sr_d, @sr_d,
	@sm_m1, 
	@sm_m2, 
	@sm_m1 + @sm_m2	


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, @acct2, @acct3,
	0, 0, 0, 0,
	SUM(summa)
from 
	dbo.CALCULATE_JURNAL J 
	INNER JOIN dbo.PAYS P ON J.LINK_PAYS = P.LINK
	left join
	(select distinct G1.link, A.code
		from 
		dbo.g_prov1 g1
		inner join dbo.G_PROV2 G2 on G2.LINK_UP = G1.link 
		inner join dbo.g_prov_ap G on G.link_up = G2.link and G.db_kr = 1
		inner join dbo.s_accounts A on A.link = G.account
	) PA on P.link_oper = PA.link
	INNER JOIN #ACC_CODE c ON c.acc_c = LEFT(PA.CODE,6)	
where 
	J.LINK_EMPL = @ref_empl and MONTH(J.PERIOD_BEGIN) = @CurYM%100 and YEAR(J.PERIOD_BEGIN) = @CurYM/100 and P.[OBJECT] = 1
	and LINK_DOC <> @LINK



----
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, @acct2, @acct3,
	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], sf.CODE AS ACC_CODE
into #t9
from s_j_c , #D1 D1 , SAL_SFIN  sf 
where link_empl = @ref_empl and month_begin = d1.[month] and year_begin = [year] and typ_oper = 2 AND sf.LINK =  link_vkr AND WAY_CALC IN (4,5,6)
group by D1.code,link_pays,name_pays,code_pays, [month], [year], WAY_CALC,sf.CODE


--Список счетов по ндфл
create table #ACC_CODE_NDFL (id int identity(1,1), acc_c varchar(20))
insert into #ACC_CODE_NDFL (acc_c)
SELECT DISTINCT LEFT(acc_code,20) FROM #t9 ORDER BY LEFT(acc_code,20)


---- Удержания за текущий

--выделим отдельно удержания по НДФЛ
select 	D1.code AS CODE1,
		sm_N_1 = isnull((select SUM(sm1) from #T9 A INNER JOIN #ACC_CODE_NDFL B ON LEFT(a.ACC_CODE,20) = b.acc_c where b.id = 1 /*and acc_c =sf.CODE*/ AND  a.[month] = d1.[month] AND a.[year] = d1.[year] /*AND a.LINK_PAYS = s_j_c.link_pays*/),0),
		sm_N_2 = isnull((select SUM(sm1) from #T9 A INNER JOIN #ACC_CODE_NDFL B ON LEFT(a.ACC_CODE,20) = b.acc_c where b.id = 2 /*and acc_c =sf.CODE*/ AND  a.[month] = d1.[month] AND a.[year] = d1.[year] /*AND a.LINK_PAYS = s_j_c.link_pays*/),0),
		sm_N_3 = isnull((select SUM(sm1) from #T9 A INNER JOIN #ACC_CODE_NDFL B ON LEFT(a.ACC_CODE,20) = b.acc_c where b.id = 3 /*and acc_c =sf.CODE*/ AND a.[month] = d1.[month] AND a.[year] = d1.[year] /*AND a.LINK_PAYS = s_j_c.link_pays*/),0),
		[accU1] = ISNULL((SELECT TOP 1 acc_code FROM #T9 A INNER JOIN #ACC_CODE_NDFL B ON LEFT(a.acc_code,20) = b.acc_c where b.id = 1 /*AND a.[month] = d1.[month] AND a.[year] = d1.[year]*/ /*AND a.LINK_PAYS = s_j_c.link_pays*/),''),
		[accU2] = ISNULL((SELECT TOP 1 acc_code FROM #T9 A INNER JOIN #ACC_CODE_NDFL B ON LEFT(a.acc_code,20) = b.acc_c where b.id = 2 /*AND a.[month] = d1.[month] AND a.[year] = d1.[year]*/ /*AND a.LINK_PAYS = s_j_c.link_pays*/),''),
		[accU3] = ISNULL((SELECT TOP 1 acc_code FROM #T9 A INNER JOIN #ACC_CODE_NDFL B ON LEFT(a.acc_code,20) = b.acc_c where b.id = 3 /*AND a.[month] = d1.[month] AND a.[year] = d1.[year]*/ /*AND a.LINK_PAYS = s_j_c.link_pays*/),''),
		sum(summa) as sm1, 
	    link_pays, 
	    name_pays AS NP, 
	    code_pays AS CP, 
	    [month], 
	    [year], 
	    ndfl = CASE WHEN WAY_CALC IN (4,5,6) THEN 1 ELSE 0 END -- , 
	    --sf.CODE AS ACC_CODE
into #t10
from s_j_c S LEFT JOIN #D1 D1 ON 1=1  LEFT JOIN SAL_SFIN  sf  ON sf.LINK =  link_vkr
where link_empl = @ref_empl and month_begin = d1.[month] and year_begin = [year] and typ_oper = 2 --AND sf.LINK =  link_vkr
group by D1.code,link_pays,name_pays,code_pays, [month], [year], WAY_CALC --,sf.CODE


---- Удержания за текущий
insert into #t10
SELECT distinct convert(varchar(2),@M+7) AS CODE1 ,
		sm_N_1 = isnull((SELECT distinct SUM(summa) from s_j_c JJ left JOIN dbo.SAL_SFIN  sf1 ON  sf1.LINK =  jJ.link_vkr INNER JOIN #ACC_CODE_NDFL B ON LEFT(SF1.CODE,20) = b.acc_c  where b.id = 1 AND  JJ.month_begin = @CurYM%100 AND JJ.year_begin = @CurYM/100  AND JJ.link_empl = J.link_empl AND JJ.typ_oper = 2 AND jj.WAY_CALC IN (4,5,6)/*AND a.LINK_PAYS = j.link_pays*/),0),
		sm_N_2 = isnull((SELECT distinct SUM(summa) from s_j_c JJ left JOIN dbo.SAL_SFIN  sf1 ON  sf1.LINK =  jJ.link_vkr INNER JOIN #ACC_CODE_NDFL B ON LEFT(SF1.CODE,20) = b.acc_c  where b.id = 2 AND  JJ.month_begin = @CurYM%100 AND JJ.year_begin = @CurYM/100  AND JJ.link_empl = J.link_empl AND JJ.typ_oper = 2 AND jj.WAY_CALC IN (4,5,6)/*AND a.LINK_PAYS = j.link_pays*/),0),
		sm_N_3 = isnull((SELECT distinct SUM(summa) from s_j_c JJ left JOIN dbo.SAL_SFIN  sf1 ON  sf1.LINK =  jJ.link_vkr INNER JOIN #ACC_CODE_NDFL B ON LEFT(SF1.CODE,20) = b.acc_c  where b.id = 3 AND  JJ.month_begin = @CurYM%100 AND JJ.year_begin = @CurYM/100  AND JJ.link_empl = J.link_empl AND JJ.typ_oper = 2 AND jj.WAY_CALC IN (4,5,6)/*AND a.LINK_PAYS = j.link_pays*/),0),
		[accU1] = ISNULL((SELECT TOP 1 LEFT(SF1.CODE,20) from s_j_c JJ left JOIN dbo.SAL_SFIN  sf1 ON  sf1.LINK =  jJ.link_vkr INNER JOIN #ACC_CODE_NDFL B ON LEFT(SF1.CODE,20) = b.acc_c  where b.id = 1 AND  JJ.month_begin = @CurYM%100 AND JJ.year_begin = @CurYM/100  AND JJ.link_empl = J.link_empl AND JJ.typ_oper = 2  AND jj.WAY_CALC IN (4,5,6)/*AND a.LINK_PAYS = j.link_pays*/),''),
		[accU2] = ISNULL((SELECT TOP 1 LEFT(SF1.CODE,20) from s_j_c JJ left JOIN dbo.SAL_SFIN  sf1 ON  sf1.LINK =  jJ.link_vkr INNER JOIN #ACC_CODE_NDFL B ON LEFT(SF1.CODE,20) = b.acc_c  where b.id = 2 AND  JJ.month_begin = @CurYM%100 AND JJ.year_begin = @CurYM/100  AND JJ.link_empl = J.link_empl AND JJ.typ_oper = 2  AND jj.WAY_CALC IN (4,5,6)/*AND a.LINK_PAYS = j.link_pays*/),''),
		[accU3] = ISNULL((SELECT TOP 1 LEFT(SF1.CODE,20) from s_j_c JJ left JOIN dbo.SAL_SFIN  sf1 ON  sf1.LINK =  jJ.link_vkr INNER JOIN #ACC_CODE_NDFL B ON LEFT(SF1.CODE,20) = b.acc_c  where b.id = 3 AND  JJ.month_begin = @CurYM%100 AND JJ.year_begin = @CurYM/100  AND JJ.link_empl = J.link_empl AND JJ.typ_oper = 2  AND jj.WAY_CALC IN (4,5,6)/*AND a.LINK_PAYS = j.link_pays*/),''),
		sum(summa) as sm1, link_pays, name_pays AS NP, code_pays AS CP, @CurYM%100 as [month], @CurYM/100 as [year], ndfl = CASE WHEN WAY_CALC IN (4,5,6) THEN 1 ELSE 0 END -- , sf.CODE AS ACC_CODE
  from dbo.s_j_c j 
	left JOIN dbo.SAL_SFIN  sf ON  sf.LINK =  j.link_vkr
where link_empl = @ref_empl  and month_begin = @CurYM%100 and year_begin = @CurYM/100 and typ_oper = 2
group by j.LINK_EMPL,link_pays ,name_pays,code_pays,WAY_CALC--,sf.CODE



------ Итого удержано
insert into #t10
Select convert(varchar(2),@M+8) as code1, 
	   sum(sm_N_1),
	   sum(sm_N_2) ,
	   sum(sm_N_3) ,
	   [accU1] ,
	   [accU2] ,
	   [accU3] ,
		sum(sm1), link_pays, np, cp, [month], [year], ndfl 
from #t10 where code1 = convert(varchar(2),@M+7) 
GROUP BY [accU1],[accU2],[accU3],link_pays,np, cp, [month], [year], ndfl 

----
-- Удержания по НДФЛ оставляем статичными 

select code1 as code2, sum(sm_n_1) AS sm_n1_all , sum(sm_n_2) AS sm_n2_all, sum(sm_n_3) AS sm_n3_all, sum(sm1) as sm_all ,[accU1] AS [accUN1],[accU2] AS [accUN2],[accU3] AS  [accUN3]   into #t11 from #t10 WHERE ndfl = 1 group by code1 ,[accU1],[accU2],[accU3]

DELETE FROM #t10 WHERE ndfl = 1   -- удаляем удержания по ндфл из таблицы удержаний, которые будут идти по порядку динамически, НДФЛ будет статичным

DECLARE @COUNT_U int, @COUNT_U_NDFL INT 

SET @COUNT_U = (SELECT COUNT(CODE1) FROM #t10 WHERE CODE1 <19)
SET @COUNT_U_NDFL = (SELECT COUNT(CODE2) FROM #T11 WHERE CODE2 <19)

----
DECLARE @Table_Name VARCHAR(100), @table1 VARCHAR(100)
EXEC X_GET_TABLE_NAME @Table_Name OUTPUT
EXEC X_GET_TABLE_NAME @table1 OUTPUT
EXEC M_CROSS_TABLE 
	'CODE1, MONTH, YEAR , sm_n_1, sm_n_2, sm_n_3,accU1,accU2,accU3',
	'CP, NP',
	'VARCHAR(10)#VARCHAR(254)',
	'SM1', 'NUMERIC(20,2)', 'SUM(SM1) AS SM1',
	#t10,
	@Table_Name

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

EXEC ('alter table ' + @table1 + '  add [sm_U_all] numeric(20,2) default 0.00 ')

EXEC('UPDATE  TT
		SET  CODE1 = (CASE WHEN '+ @COUNT_U +' <  '+ @COUNT_U_NDFL +'  then T1.code2  else T.code1 end ),
			MONTH = (CASE WHEN '+ @COUNT_U +' <  '+ @COUNT_U_NDFL +'  then (select top 1 month FROM #D1 where code = T1.code2 ) else T.MONTH end ),
			YEAR = (CASE WHEN '+ @COUNT_U +' <  '+ @COUNT_U_NDFL +'  then (select top 1 YEAR FROM #D1 where code = T1.code2 ) else T.YEAR end ),
		    accU1 = (CASE WHEN '+ @COUNT_U +' <  '+ @COUNT_U_NDFL +'  then T1.accUN1  else T.accU1 end ),
			accU2 = (CASE WHEN '+ @COUNT_U +' <  '+ @COUNT_U_NDFL +'  then T1.accUN2  else T.accU2 end ), 
			accU3 = (CASE WHEN '+ @COUNT_U +' <  '+ @COUNT_U_NDFL +'  then T1.accUN3  else T.accU3 end )
	  FROM  ' + @table1 + ' TT 
			left join #T11 T1 on  TT.CODE = T1.CODE2
			LEFT  JOIN ' + @Table_Name + ' T ON TT.CODE = T.CODE1 '	)

EXEC('UPDATE  TT
		SET  sm_U_all = ISNULL(T1.SM1,0)
	  FROM  ' + @table1 + ' TT 
			left join  (SELECT TA.CODE1 , sum(TA.SM1) AS sm1 FROM ' + @table1 + ' Tb 
			left join #T10 Ta on  Tb.CODE = Ta.CODE1   group by Ta.CODE1 ) T1 on  TT.CODE = T1.CODE1')



DECLARE @CODE_CNT INT, @DELTA INT, @I INT, @SQL_STR VARCHAR(8000)
SET @CODE_CNT = (SELECT COUNT(DISTINCT CP) FROM #t10 )

SET @DELTA = CASE WHEN @CODE_CNT = 0 THEN 1  ELSE 0 END

IF @DELTA > 0 BEGIN
	SET @I=1
	WHILE @I<=@DELTA BEGIN
		SET @SQL_STR= 'ALTER TABLE '  + @table1 + '  ADD CP_' + LTRIM(STR(@CODE_CNT+@I)) + '  VARCHAR(10) DEFAULT '''', NP_' + LTRIM(STR(@CODE_CNT+@I)) + '_' + LTRIM(STR(@CODE_CNT+@I)) + ' VARCHAR(254) DEFAULT '''', SM1_'
		+  LTRIM(STR(@CODE_CNT+@I)) + '_' + LTRIM(STR(@CODE_CNT+@I)) + '  NUMERIC(20,2) DEFAULT 0'
		EXEC (@SQL_STR)
		SET @I=@I+1
	END
END

DECLARE @FIELD_NAME VARCHAR(254)
SET @I = 1
SET @CODE_CNT = CASE WHEN @CODE_CNT < @DELTA THEN @DELTA ELSE @CODE_CNT END
WHILE @I <=@CODE_CNT BEGIN
	SET @FIELD_NAME= 'CP_' + RTRIM(LTRIM(STR(@I))) 
	SET @SQL_STR= ' UPDATE ' + @table1 + '  SET ' + @FIELD_NAME+ ' = ISNULL((SELECT TOP 1 '+@FIELD_NAME+' FROM ' +@Table_Name + ' WHERE '+
			@FIELD_NAME+ '  IS NOT NULL ), '''') ' 

	EXEC (@SQL_STR)

	SET @FIELD_NAME= 'NP_' + RTRIM(LTRIM(STR(@I))) + '_' + + RTRIM(LTRIM(STR(@I))) 
	SET @SQL_STR= ' UPDATE ' + @table1 + '  SET ' + @FIELD_NAME+ ' = ISNULL((SELECT TOP 1 '+@FIELD_NAME+' FROM ' +@Table_Name + ' WHERE '+
			@FIELD_NAME+ '  IS NOT NULL ), '''') ' 

	EXEC (@SQL_STR)

	SET @FIELD_NAME= 'SM1_' + RTRIM(LTRIM(STR(@I))) + '_' + + RTRIM(LTRIM(STR(@I))) 
	SET @SQL_STR= ' UPDATE ' + @table1 + '  SET ' + @FIELD_NAME+ ' = 0 WHERE ' + @FIELD_NAME + ' IS NULL ' 

	EXEC (@SQL_STR)
	SET @I=@I+1
END

Declare @Script varchar(254)
EXEC('UPDATE ' + @table1 + ' SET SM_ALL = 0 WHERE SM_ALL IS NULL')
set @Script = 'SELECT * FROM ' + @table1 + ' WHERE CODE <= ''' + convert(varchar(2),@M) + ''' ORDER BY CODE'
EXEC (@Script)
Set @Script = 'SELECT * FROM ' + @table1 + ' WHERE CODE > ''' + convert(varchar(2),@M) + ''' ORDER BY CODE'
EXEC (@Script)

Set @Script = 'SELECT CASE WHEN COALESCE(sm_all0,0) > (COALESCE(sm_all,0) + COALESCE(sm_U_all,0)) then  COALESCE(sm_all0,0) - (COALESCE(sm_all,0) + COALESCE(sm_U_all,0)) else 0 end as sm_all0 FROM ' + @table1 + ' WHERE CODE = ''' + convert(varchar(2),@M+8) + ''' ORDER BY CODE'
EXEC (@Script)
EXEC('DROP TABLE ' + @Table_Name)
EXEC('DROP TABLE ' + @table1)





GO


GRANT EXECUTE ON dbo.[SALARY_REP_AVG] TO PUBLIC

GO




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

GO





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

CREATE PROCEDURE dbo.BK_REPORT_OSV_EMPL
	@varKSdDate1	DATETIME	,
	@varKSdDate2	DATETIME	,
	@varKScVal1 char(1), @varKSnOtborLink1 int	,
	@varKScVal3 char(1), @varKSnOtborLink3 int	,
	@cVal_KBK char(1), @nOtborLinkKBK int,	-- Отбор КБК --
	@varKSnPRN_KBK INT				,
	@varKSnPRN_SGU INT				,
	@intREPORT_EMPL INT				,
	@varKScOtborAccount	VARCHAR (100),
        @intSVOD_ZB     int     , -- Сводный отчет (ЦБ) --
	@intSORT_FIO	INT = 0,	-- Сортировать по ФИО -- 
	@intSORT_INV_NAME	INT = 0,		-- Сортировать по Наименованию  -- 
	@GRP_DOP_CL	INT = 0,
	@cVal_DOP_CL char(1), @nOtbor_DOP_CL int,	-- Отбор по доп. классификации --
	@intOBOROT_ONLY INT = 0,
	@cVal_KAU CHAR(1), @nOtbor_KAU INT,	-- Отбор КАУ --
	@intGRP_KAU INT,	-- Группировать по КАУ --
	@intGRP_SUB	INT,	-- Группировать по подразделениям --
	@cVal_SUB CHAR(1), @nOtbor_SUB INT	-- Отбор подразделений --
AS
BEGIN
	DECLARE	@varKSDEP_LINK	INT,
		@varKSDIC_EMP	INT,
		@varKSORGNAME	VARCHAR(254),
		@strDATE_NEXT	VARCHAR (10),
		@strREP_NAME	VARCHAR (254)

	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)
	SET @varKSDEP_LINK = dbo.BK_GetDepZB ()

	IF @intSVOD_ZB = 1 OR @varKSDEP_LINK IS NULL
		SET @varKSDEP_LINK = dbo.GetOwnDepLink()

	SELECT  @varKSORGNAME = dbo.BK_GET_PRINT_DEP_NAME (LINK)
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @varKSDEP_LINK

	IF @intSVOD_ZB = 1
	BEGIN
		SET @varKSORGNAME = RTRIM (@varKSORGNAME) + ' (ЦБ)'
		SET @varKSDEP_LINK = NULL
	END

	SET @strDATE_NEXT = CONVERT (VARCHAR (10), DATEADD (DAY, 1, @varKSdDate2), 104)
	SET @intREPORT_EMPL = ISNULL (@intREPORT_EMPL, 0)

	DECLARE @ACCT  TABLE (LINK_ACCT [INT])	

	IF LEN (@varKScVal1) > 0
		INSERT INTO @ACCT
		SELECT RECORD
		FROM OBJECT_VAR_ACCT
		WHERE LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO @ACCT
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode (DEFAULT, DEFAULT, DEFAULT, DEFAULT) ACCT
		INNER JOIN dbo.BK_GetValuesTableBySTR (@varKScOtborAccount, DEFAULT) T1 ON (T1.VALUE = ACCT.cSINTH)
		UNION ALL
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode ('201', '05', DEFAULT, DEFAULT) ACCT
		UNION ALL
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode ('201', '35', DEFAULT, DEFAULT) ACCT

	DECLARE @EMP  TABLE (LINK_EMP [INT], EMP_CODE  [VARCHAR] (20), EMP_NAME [VARCHAR] (254) )
	IF LEN(@varKScVal3)>0 BEGIN
		INSERT INTO @EMP
		SELECT OVR.RECORD, D.TAB, D.[NAME_EMPL]
		FROM dbo.OBJECT_VAR_EMPL OVR, dbo.KU_EMPL_PLACING D
		WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@varKSnOtborLink3
	END
	ELSE
	BEGIN
		INSERT INTO @EMP
		SELECT D.LINK, D.TAB, D.[NAME_EMPL]
		FROM dbo.KU_EMPL_PLACING D
		INSERT INTO @EMP VALUES (0, '', '')
	END
	
	--- ОТБОР КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	--- ОТБОР ДОП. КЛАССИФИКАЦИИ --- 
	DECLARE @TAB_DOP_CLASSIF TABLE (LINK_DOP INT, DOP_CODE VARCHAR (20), DOP_NAME VARCHAR (254))
	IF LEN (@cVal_DOP_CL) > 0
		INSERT INTO @TAB_DOP_CLASSIF
		SELECT AP.LINK,
			AP.CODE,
			AP.[NAME]
		FROM dbo.DOP_CLASSIF AP 
		INNER JOIN dbo.OBJECT_VAR_DOP_CLASSIF OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtbor_DOP_CL
	ELSE
		INSERT INTO @TAB_DOP_CLASSIF
		SELECT LINK_AP, AP_CODE, AP_NAME
		FROM dbo.BK_GetTableDictionByAP ('AP2')

	--- ОТБОР КАУ --- 
	DECLARE @TAB_KAU TABLE (LINK_KAU INT, KAU_CODE VARCHAR (20), KAU_NAME VARCHAR (254))
	IF LEN (@cVal_KAU) > 0
		INSERT INTO @TAB_KAU
		SELECT AP.LINK,
			AP.CODE,
			AP.[NAME]
		FROM dbo.KAU AP 
		INNER JOIN dbo.OBJECT_VAR_KAU OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtbor_KAU
	ELSE
		INSERT INTO @TAB_KAU
		SELECT LINK_AP, AP_CODE, AP_NAME
		FROM dbo.BK_GetTableDictionByAP ('KAU')

	--- ОТБОР ПОДРАЗДЕЛЕНИЙ --- 
	DECLARE @TAB_SUB TABLE (LINK INT, CODE VARCHAR (20), [NAME] VARCHAR (254))
	IF LEN (@cVal_SUB) > 0
		INSERT INTO @TAB_SUB
		SELECT AP.LINK,
			AP.CODE,
			AP.[NAME]
		FROM dbo.OBJECT_VAR_SUBDIV_HEAD OVR 
		INNER JOIN dbo.SUBDIVISION (@varKSdDate2) AP ON (AP.LINK = OVR.RECORD)
		WHERE OVR.LINK_UP = @nOtbor_SUB
	ELSE
		INSERT INTO @TAB_SUB
		SELECT LINK_AP, AP_CODE, AP_NAME
		FROM dbo.BK_GetTableDictionByAP ('SUB')

--SELECT * FROM @TAB_SUB

	SET @intGRP_SUB = ISNULL (@intGRP_SUB, 0)

	DECLARE @TABLE1 TABLE (DEP [INT], ACCOUNT [INT], INV [INT], NOMEN [INT], EMP [INT], 
			KBK [INT], KOSGU [INT], AP2 INT, KAU INT, 
			SUBDIV	INT, 
			D_SUMMA [NUMERIC] (20,3), D_QTY [NUMERIC] (20,4),  
			K_SUMMA [NUMERIC] (20,3), K_QTY [NUMERIC] (20,4),  
			IN_SUMMA [NUMERIC] (20,3), IN_QTY [NUMERIC] (20,4),  	
			OUT_SUMMA [NUMERIC] (20,3), OUT_QTY [NUMERIC] (20,4),
			PRICE [NUMERIC] (28,6), PRICE_TYPE [TINYINT])

	INSERT INTO @TABLE1
	SELECT T1.DEP,
		T1.ACCOUNT,
		T1.INV,
		T1.NOMEN,
		CASE
			WHEN @intREPORT_EMPL = 1 THEN T1.EMP
			ELSE 0
		END,
		CASE 
			WHEN @varKSnPRN_KBK = 1 THEN ISNULL (T1.KBK, 0)
			ELSE 0
		END,
		CASE 
			WHEN @varKSnPRN_SGU = 1 THEN ISNULL (T1.SGU, 0)
			ELSE 0
		END,
		CASE 
			WHEN @GRP_DOP_CL = 1 THEN ISNULL (T1.AP2, 0)
			ELSE 0
		END,
		CASE 
			WHEN @intGRP_KAU = 1 THEN ISNULL (T1.KAU, 0)
			ELSE 0
		END,
		CASE 
			WHEN @intGRP_SUB = 1 THEN ISNULL (T1.SUB, 0)
			ELSE 0
		END,
		SUM (T1.D_SUMMA), SUM (T1.D_QTY),
		SUM (T1.K_SUMMA), SUM (T1.K_QTY),
		SUM (T1.IN_SUMMA), SUM (T1.IN_QTY),
		SUM (T1.OUT_SUMMA), SUM (T1.OUT_QTY),
		T1.PRICE,
		T1.PRICE_TYPE
	FROM dbo.BK_GetTableOSVByDate (@varKSdDate1, @varKSdDate2, @varKSDEP_LINK) T1
	INNER JOIN @ACCT AC ON (AC.LINK_ACCT = T1.ACCOUNT)
	INNER JOIN @TAB_KBK K1 ON (K1.LINK_KBK = T1.KBK)
	INNER JOIN @TAB_DOP_CLASSIF DOP ON (DOP.LINK_DOP = T1.AP2)
	INNER JOIN @TAB_KAU KAU ON (KAU.LINK_KAU = T1.KAU)
	GROUP BY  T1.DEP,
		T1.ACCOUNT,
		T1.INV,
		T1.NOMEN,
		CASE
			WHEN @intREPORT_EMPL = 1 THEN T1.EMP
			ELSE 0
		END,
		CASE 
			WHEN @varKSnPRN_KBK = 1 THEN ISNULL (T1.KBK, 0)
			ELSE 0
		END,
		CASE 
			WHEN @varKSnPRN_SGU = 1 THEN ISNULL (T1.SGU, 0)
			ELSE 0
		END,
		CASE 
			WHEN @GRP_DOP_CL = 1 THEN ISNULL (T1.AP2, 0)
			ELSE 0
		END,
		CASE 
			WHEN @intGRP_KAU = 1 THEN ISNULL (T1.KAU, 0)
			ELSE 0
		END,
		CASE 
			WHEN @intGRP_SUB = 1 THEN ISNULL (T1.SUB, 0)
			ELSE 0
		END,
		T1.PRICE,
		T1.PRICE_TYPE
	HAVING @intOBOROT_ONLY = 0
		OR @intOBOROT_ONLY = 1
				AND (SUM (T1.D_SUMMA) <> 0 OR SUM (T1.D_QTY) <> 0
					OR SUM (T1.K_SUMMA) <> 0 OR SUM (T1.K_QTY) <> 0)

-- SELECT * FROM @TABLE1

	SET @strREP_NAME = ''
	IF EXISTS (SELECT * FROM S_ACCOUNTS, @ACCT WHERE LINK_ACCT = LINK AND cSINTH = '101')
		SET @strREP_NAME = 'ОСНОВНЫХ СРЕДСТВ'

	IF EXISTS (SELECT * FROM S_ACCOUNTS, @ACCT WHERE LINK_ACCT = LINK AND cSINTH = '105')
		SET @strREP_NAME = @strREP_NAME + CASE
							WHEN @strREP_NAME = '' THEN ''
							ELSE ', '
						END 
			+ 'МАТЕРИАЛЬНЫХ ЗАПАСОВ'
	
	IF EXISTS (SELECT * FROM S_ACCOUNTS, @ACCT WHERE LINK_ACCT = LINK AND cSINTH = '201')
		SET @strREP_NAME = @strREP_NAME + CASE
							WHEN @strREP_NAME = '' THEN ''
							ELSE ', '
						END 
			+ 'ДЕНЕЖНЫХ ДОКУМЕНТОВ'

	DECLARE @RESULT TABLE  (DEP [INT], ACCOUNT [INT], INV [INT],
			EMP [INT], DOP_LINK INT, KAU INT,
			DEP_CODE [VARCHAR] (20), DEP_NAME [VARCHAR] (254),
			ACCT_GR [VARCHAR] (30), ACCT_CODE [VARCHAR] (60),
			KBK_CODE [VARCHAR] (30), KOSGU_CODE [VARCHAR] (5),
			INV_CODE [VARCHAR] (20), INV_NAME [VARCHAR] (254),
			UM_CODE [VARCHAR] (20), UM_NAME [VARCHAR] (254),
			INV_COST [NUMERIC] (20,4),		
			EMP_CODE [VARCHAR] (20), EMP_NAME [VARCHAR](254),
			DOP_CODE [VARCHAR] (20), DOP_NAME [VARCHAR](254),
			KAU_CODE [VARCHAR] (20), KAU_NAME [VARCHAR](254),

			SUB INT, SUB_CODE VARCHAR (20), SUB_NAME VARCHAR (254),

			D_SUM [NUMERIC] (20,3), D_QTY [NUMERIC] (20,4),	
			K_SUM [NUMERIC] (20,3), K_QTY [NUMERIC] (20,4),	
			IN_SUM [NUMERIC] (20,3), IN_QTY [NUMERIC] (20,4),		
			OUT_SUM [NUMERIC] (20,3), OUT_QTY [NUMERIC] (20,4),	

			ORGNAME [VARCHAR] (254), DATE_NEXT VARCHAR (10),
			REP_NAME [VARCHAR] (254),
			PRICE_TYPE [TINYINT])

	INSERT INTO @RESULT
	SELECT OSV.DEP,
		OSV.ACCOUNT,
		OSV.INV,
		OSV.EMP,
		OSV.AP2,
		OSV.KAU,
		DEP.CODE,
		DEP.[NAME],
		SA.CODE,
		dbo.BK_GetAcctFullCode1 (OSV.ACCOUNT, OSV.KBK, OSV.KOSGU, @varKSnPRN_KBK, @varKSnPRN_SGU),
		ISNULL (KL_KBK.CODE, ''),
		ISNULL (KOSGU.CODE, ''),
		ISNULL (INV.CODE, ISNULL (NOMEN.CODE, '')),	
		ISNULL (INV.[NAME], ISNULL (NOMEN.NAME, '')),
		ISNULL (INV.CODE_UM, ISNULL (NOMEN.CODE_UM, '')),
		ISNULL (INV.NAME_UM, ISNULL (NOMEN.NAME_UM, '')), 
		OSV.PRICE,
		EMP.EMP_CODE,
		EMP.EMP_NAME,
		DOP.DOP_CODE,
		DOP.DOP_NAME,
		KAU.KAU_CODE,
		KAU.KAU_NAME,

		OSV.SUBDIV,
		SUB.CODE,
		SUB.[NAME], 

		OSV.D_SUMMA, OSV.D_QTY,
		OSV.K_SUMMA, OSV.K_QTY,
		OSV.IN_SUMMA, OSV.IN_QTY,
		OSV.OUT_SUMMA,
		OSV.OUT_QTY,
		@varKSORGNAME,
		@strDATE_NEXT,
		@strREP_NAME,
		OSV.PRICE_TYPE
	FROM @TABLE1 OSV
	INNER JOIN @EMP EMP ON (EMP.LINK_EMP = OSV.EMP)
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = OSV.ACCOUNT)
	LEFT OUTER JOIN @TAB_DOP_CLASSIF DOP ON (DOP.LINK_DOP = OSV.AP2)
	LEFT OUTER JOIN @TAB_KAU KAU ON (KAU.LINK_KAU = OSV.KAU)
	LEFT OUTER JOIN dbo.DICTIONARY_DEPARTMENT DEP ON (DEP.LINK = OSV.DEP)
	LEFT OUTER JOIN dbo.INVENTORY_CARD INV ON (INV.LINK = OSV.INV)
	LEFT OUTER JOIN dbo.BV_NOMENCLATURE NOMEN ON (NOMEN.LINK = OSV.NOMEN)
	LEFT OUTER JOIN dbo.KL_KBK ON (KL_KBK.LINK = OSV.KBK)
	LEFT OUTER JOIN dbo.KOSGU ON (KOSGU.LINK = OSV.KOSGU)
	INNER JOIN @TAB_SUB SUB ON (SUB.LINK = OSV.SUBDIV)
	WHERE (OSV.D_SUMMA <> 0) OR (OSV.D_QTY<> 0)
		OR (OSV.K_SUMMA <> 0) OR (OSV.K_QTY <> 0)
		OR (OSV.IN_SUMMA <> 0) OR (OSV.IN_QTY <> 0)
		OR (OSV.OUT_SUMMA <> 0) OR (OSV.OUT_QTY <> 0)

	UPDATE @RESULT SET INV_COST = OUT_SUM / OUT_QTY
	WHERE PRICE_TYPE = 0 AND OUT_QTY <> 0

	IF @intSORT_FIO = 1
		IF @intSORT_INV_NAME = 1
			SELECT * FROM @RESULT
			ORDER BY DEP_CODE, SUB_CODE, EMP_NAME, EMP_CODE, EMP, ACCT_GR, KAU_CODE, DOP_CODE, KBK_CODE, 
				INV_NAME, RIGHT ('00000000000000000000' + INV_CODE, 20), KOSGU_CODE
		ELSE
			SELECT * FROM @RESULT
			ORDER BY DEP_CODE, SUB_CODE, EMP_NAME, EMP_CODE, EMP, ACCT_GR, KAU_CODE, DOP_CODE, KBK_CODE, 
				RIGHT ('00000000000000000000' + INV_CODE, 20), KOSGU_CODE

	ELSE
		IF @intSORT_INV_NAME = 1
			SELECT * FROM @RESULT
			ORDER BY DEP_CODE, SUB_CODE, EMP_CODE, EMP, ACCT_GR, KAU_CODE, DOP_CODE, KBK_CODE, 
				INV_NAME, RIGHT ('00000000000000000000' + INV_CODE, 20), KOSGU_CODE
		ELSE
			SELECT * FROM @RESULT
			ORDER BY DEP_CODE, SUB_CODE, EMP_CODE, EMP, ACCT_GR, KAU_CODE, DOP_CODE, KBK_CODE, 
				RIGHT ('00000000000000000000' + INV_CODE, 20), KOSGU_CODE
END



GO


GRANT EXECUTE ON dbo.[BK_REPORT_OSV_EMPL] TO PUBLIC

GO

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

GO
-- Печать Акта о возврате товарно-материальных ценностей, сданных на хранение --
CREATE PROCEDURE dbo.BK_PRINTDOC_AKT_MX3
	@intLINK_DOC	INT
AS
BEGIN
	DECLARE
		@PAGE_NO	INT,
		@ROW_PAGE	INT,
		@ROW_PAGE1	INT,
		@CUR_ROW	INT,
		
		@QTY_CHAR1	INT

	SELECT
		@ROW_PAGE1	=	36,
		@ROW_PAGE	=	57,
		@CUR_ROW	=	1,
		@PAGE_NO	=	1,
		@QTY_CHAR1	=	13

	CREATE TABLE #TAB1
		(
		TLINK	INT IDENTITY (1, 1),
		DOC_LINK	INT,
		TAB_NO	INT,
		INV_NAME	VARCHAR (254),
		INV_CODE	VARCHAR (30),
		UM_CODE		VARCHAR (30),
		UM_SNAME	VARCHAR (254),
		QTY	NUMERIC (28, 4),
		PRICE NUMERIC (28, 4),
		SUMMA NUMERIC (28, 4),
		COMMENT VARCHAR (254),
		ORDERS	INT,
		PAGE_NO	INT,
		NDS_SUM NUMERIC (28, 4),
		ALL_SUM NUMERIC (28, 4),
		INV_CHAR VARCHAR (254)
		)

	-- Материальные ценности --
	INSERT INTO #TAB1
		(
		DOC_LINK,
		TAB_NO,
		INV_NAME,
		INV_CODE,
		UM_CODE,
		UM_SNAME,
		QTY,
		PRICE,
		SUMMA,
		COMMENT,
		ORDERS,
		PAGE_NO,
		NDS_SUM,
		ALL_SUM,
		INV_CHAR
		)
	SELECT
		DOC_LINK = LINK_UP,
		TAB_NO = 1,
		INV_NAME,
		INV_CODE = ISNULL (INV_CODE, ''),
		UM_CODE,
		UM_SNAME,
		QTY,
		PRICE,
		SUMMA,
		COMMENT = ISNULL (COMMENT, ''),
		ORDERS,
		0 AS PAGE_NO,
		CONVERT (NUMERIC (28, 4), 0) AS NDS_SUM,
		CONVERT (NUMERIC (28, 4), 0) AS ALL_SUM,
		ISNULL (INV_CHAR, '')
	FROM dbo.BK_DOC_TAB_MX3_INV_FN (@intLINK_DOC)
	ORDER BY ORDERS

	IF @@ROWCOUNT = 0
		INSERT INTO #TAB1 (DOC_LINK, TAB_NO, INV_NAME, INV_CODE, UM_CODE, UM_SNAME, QTY, PRICE, SUMMA, COMMENT, ORDERS,
				PAGE_NO, NDS_SUM, ALL_SUM, INV_CHAR)
		SELECT @intLINK_DOC, 1, '', '', '', '', 0, 0, 0, '', 0, 1, 0.00, 0.00, ''

	UPDATE #TAB1
	SET PAGE_NO = @PAGE_NO,
		@CUR_ROW = CASE
						WHEN @PAGE_NO = 1 AND @CUR_ROW > @ROW_PAGE1 OR @PAGE_NO > 1 AND @CUR_ROW > @ROW_PAGE THEN 1
						ELSE
							@CUR_ROW + 
								CASE
									WHEN LEN (INV_CODE) < = @QTY_CHAR1 AND LEN (COMMENT) < = @QTY_CHAR1  THEN 1
									WHEN LEN (INV_CODE) > LEN (COMMENT) THEN @CUR_ROW + LEN (INV_CODE) / @QTY_CHAR1
																			+	CASE
																					WHEN (LEN (ISNULL(INV_CODE, '')) % @QTY_CHAR1) > 0 THEN 1
																					ELSE 0
																				END
									ELSE LEN (COMMENT) / @QTY_CHAR1
										+	CASE
												WHEN (LEN (ISNULL(COMMENT, '')) % @QTY_CHAR1) > 0 THEN 1
												ELSE 0
											END
								END
						END,
		@PAGE_NO = CASE
						WHEN @PAGE_NO = 1 AND @CUR_ROW > @ROW_PAGE1 OR @PAGE_NO > 1 AND @CUR_ROW > @ROW_PAGE THEN @PAGE_NO + 1
						ELSE @PAGE_NO
					END

	-- Услуги --
	INSERT INTO #TAB1	
		(DOC_LINK,
		TAB_NO,
		INV_NAME,
		INV_CODE,
		UM_CODE,
		UM_SNAME,
		QTY,
		PRICE,
		SUMMA,
		COMMENT,
		ORDERS,
		PAGE_NO,
		NDS_SUM,
		ALL_SUM)
	SELECT
		DOC_LINK = T1.LINK_UP,
		TAB_NO = 2,
		T1.INV_NAME,
		INV_CODE = ISNULL (T1.INV_CODE, ''),
		DG.CODE,
		DG.SNAME,
		T1.QTY,
		T1.PRICE,
		T1.SUMMA,
		COMMENT = ISNULL (T1.COMMENT, ''),
		T1.ORDERS,
		@PAGE_NO AS PAGE_NO,
		NDS_SUM = SUMMA_NDS,
		ALL_SUM = SUMMA_ALL
	FROM dbo.BK_DOC_TABLE_MZ_NDS_FN (@intLINK_DOC) T1
	LEFT JOIN dbo.DICTIONARY_DIGIT DG ON (DG.LINK = T1.UM_LINK)
	ORDER BY ORDERS

	IF @@ROWCOUNT = 0
		INSERT INTO #TAB1 (DOC_LINK, TAB_NO, INV_NAME, INV_CODE, UM_CODE, UM_SNAME, QTY, PRICE, SUMMA, COMMENT, ORDERS, PAGE_NO,
			NDS_SUM, ALL_SUM, COMMENT)
		SELECT @intLINK_DOC, 2, '', '', '', '', 0, 0, 0, '', 0, @PAGE_NO, 0.00, 0.00, ''
			
	SELECT
		DOC_LINK1 = DOC.LINK,
		DOC.NOTICE_OP,
		DOC.NUMBER,
		DOC_DATE = DOC.[DATE],
		DOC.COUNT_DAY,
		DEP_NAME1	=	dbo.BK_GET_PRINT_DEP_NAME (DEP1.LINK)
			+ ISNULL (', ' + RTRIM (dbo.GetAddressByDepLink (DEP1.LINK, DEFAULT)), '')
			+ ISNULL (', ' + DEP1.PHONE, ''),
		OKPO1	=	DEP1.OKPO,
		DEP_NAME2	=	dbo.BK_GET_PRINT_DEP_NAME (DEP2.LINK)
			+ ISNULL (', ' + RTRIM (dbo.GetAddressByDepLink (DEP2.LINK, DEFAULT)), '')
			+ ISNULL (', ' + DEP2.PHONE, ''),
		OKPO2	=	DEP2.OKPO,
		OKVED2	=	DEP2.OKVED,
		DOC.NOTICE_OP,
		DOC_COM = DOC.COMMENT,
		OSN_NUM1	=	OSN1.NUMBER,
		OSN_DATE1	=	OSN1.[DATE],
		T1.*
	FROM dbo.DOC_MX3 DOC
	INNER JOIN dbo.DEPARTMENTS DEP1 ON (DEP1.LINK = DOC.DEP_LINK)
	LEFT JOIN dbo.DEPARTMENTS DEP2 ON (DEP2.LINK = DOC.DEP_LINK1)
	LEFT JOIN dbo.BD_OSNOV OSN1 ON (OSN1.LINK = DOC.OSNOV)
	LEFT JOIN #TAB1 T1 ON (T1.DOC_LINK = DOC.LINK)
	WHERE DOC.LINK = @intLINK_DOC
	ORDER BY
		T1.TAB_NO,
		T1.ORDERS
END


GO


GRANT EXECUTE ON dbo.[BK_PRINTDOC_AKT_MX3] TO PUBLIC

GO


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


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

GO

/* ВЕДОМОСТЬ ДВИЖЕНИЯ ПО НА */
CREATE PROCEDURE [dbo].BK_REPORT_VM_OS1
	@dDateB1 datetime,	-- Начало расч. периода --
	@dDateE1 datetime,	-- Конец расч. периода --
	@cVal1 char(1), @nOtborLink1 int,	-- Отбор субсчетов  "Основные средства" --
	@cVal2 char(1), @nOtborLink2 int,	-- Отбор "Материальные ценности" --
	@cVal_KBK char(1), @nOtborLinkKBK int,	-- Отбор КБК --
	@intPRINT_KBK	int,	-- Отображать КБК --
	@intPRINT_SGU	int,	-- Отображать СГУ --
	@strSINTH_ACCT_CODE	VARCHAR (300),
	@cCODE_AP VARCHAR (30),	-- --
        @intSVOD_ZB     int     -- Сводный отчет (ЦБ) --
AS
BEGIN
	DECLARE @intLINK_DEP	INT,
		@cDEP_CODE	VARCHAR (20),
		@cDEP_NAME	VARCHAR (254)

	DECLARE @ACCT_TABLE TABLE (LINK_ACCT INT)
	IF LEN (@cVal1) > 0
		INSERT INTO @ACCT_TABLE
		SELECT RECORD
		FROM dbo.OBJECT_VAR_ACCT
		WHERE LINK_UP = @nOtborLink1
	ELSE
		INSERT INTO @ACCT_TABLE
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode (DEFAULT, DEFAULT, DEFAULT, DEFAULT) ACCT
		INNER JOIN dbo.BK_GetValuesTableBySTR (@strSINTH_ACCT_CODE, DEFAULT) T1
			ON (T1.VALUE = ACCT.cSINTH)

	DECLARE @AP_TABLE TABLE (LINK_AP INT, AP_CODE VARCHAR (20), AP_NAME VARCHAR (254))
	IF LEN (@cVal2) > 0
	BEGIN
		IF @cCODE_AP = 'INVENTORY'
			INSERT INTO @AP_TABLE
			SELECT OV.RECORD,
				INV.CODE,
				INV.[NAME]
			FROM dbo.OBJECT_VAR_INVENTORY OV, dbo.INVENTORY_CARD INV
			WHERE OV.LINK_UP = @nOtborLink2
				AND INV.LINK = OV.RECORD

		IF @cCODE_AP = 'NOMENCLATURE'
			INSERT INTO @AP_TABLE
			SELECT OV.RECORD,
				INV.CODE,
				INV.[NAME]
			FROM dbo.OBJECT_VAR_NOMENCLATURE OV, dbo.BV_NOMENCLATURE INV
			WHERE OV.LINK_UP = @nOtborLink2
				AND INV.LINK = OV.RECORD
	END
	ELSE
	BEGIN
		IF @cCODE_AP = 'INVENTORY'
			INSERT INTO @AP_TABLE
			SELECT INV.LINK,
				INV.CODE,
				INV.[NAME]
			FROM dbo.INVENTORY_CARD INV

		IF @cCODE_AP = 'NOMENCLATURE'
			INSERT INTO @AP_TABLE
			SELECT INV.LINK,
				INV.CODE,
				INV.[NAME]
			FROM dbo.BV_NOMENCLATURE INV
	END

	--- ОТБОР КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

/*
	SELECT @intLINK_DEP = LINK,
		@cDEP_CODE = CODE,
		@cDEP_NAME = [NAME]
	FROM DICTIONARY_DEPARTMENT
	WHERE LINK = COALESCE (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())
*/

	/* -- Параметры организации -- */
	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)
	SET @intLINK_DEP = dbo.BK_GetDepZB ()

	IF @intSVOD_ZB = 1 OR @intLINK_DEP IS NULL
		SET @intLINK_DEP = dbo.GetOwnDepLink()

	SELECT @intLINK_DEP = LINK,
		@cDEP_CODE = CODE,
		@cDEP_NAME = [NAME]
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @intLINK_DEP

	IF @intSVOD_ZB = 1
		SET @cDEP_NAME = RTRIM (@cDEP_NAME) + ' (ЦБ)'

	DECLARE @TABLE_RES TABLE (LINK_DOC INT, DATE_DOC DATETIME, cDATE_DOC VARCHAR (10),
		DOC_NUM VARCHAR (30), DOC_NAME VARCHAR (254),
		ACCT_CODE VARCHAR (20),
		ACCT_CD_D VARCHAR (60), ACCT_CD_K VARCHAR (60),
		AP_CODE VARCHAR (20), AP_NAME VARCHAR (254),
		QTY NUMERIC (28,4), SUMMA NUMERIC (28,4),
		DEP_NAME VARCHAR (254))
 
	INSERT INTO @TABLE_RES
	SELECT G.LINK,
		G.DATE,
		CONVERT (VARCHAR (10), G.DATE, 104),
		G.NUMBER,
		dbo.JurnalProvGetDocKind (G.LINK, G.OBJECT),
		SA1.CODE, 
		dbo.BK_GetAcctFullCode1 (GAP_D.ACCOUNT, GAP_D.KBK, GAP_D.SGU, @intPRINT_KBK, @intPRINT_SGU),
		dbo.BK_GetAcctFullCode1 (GAP_K.ACCOUNT, GAP_K.KBK, GAP_K.SGU, @intPRINT_KBK, @intPRINT_SGU),
		AP.AP_CODE,
		AP.AP_NAME,
		G2.QUANTITY,
		G2.SUMMA,
		@cDEP_NAME
	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)
	INNER JOIN dbo.G_PROV_AP GAP_D ON (GAP_D.LINK_UP = G2.LINK
		AND GAP_D.DB_KR = 0)
	INNER JOIN dbo.G_PROV_AP GAP_K ON (GAP_K.LINK_UP = G2.LINK
		AND GAP_K.DB_KR = 1)
	INNER JOIN @ACCT_TABLE SA ON (SA.LINK_ACCT = GAP_D.ACCOUNT
		OR SA.LINK_ACCT = GAP_K.ACCOUNT)
/*	INNER JOIN @TAB_KBK K1 ON (K1.LINK_KBK = ISNULL (GAP_D.KBK, 0)
		OR K1.LINK_KBK = ISNULL (GAP_K.KBK, 0))
*/	INNER JOIN @AP_TABLE AP ON (AP.LINK_AP = CASE 
							WHEN @cCODE_AP = 'NOMENCLATURE' THEN GAP_D.NOMEN
							WHEN @cCODE_AP = 'INVENTORY' THEN GAP_D.INV
						END
		OR AP.LINK_AP = CASE 
							WHEN @cCODE_AP = 'NOMENCLATURE' THEN GAP_K.NOMEN
							WHEN @cCODE_AP = 'INVENTORY' THEN GAP_K.INV
						END
		)
	INNER JOIN dbo.S_ACCOUNTS SA1 ON (SA1.LINK = SA.LINK_ACCT)
--	WHERE G.DEP = @intLINK_DEP
	WHERE ((@intSVOD_ZB = 1 AND G.DEP IN (SELECT LINK FROM dbo.DEPARTMENTS WHERE ZB = 1 OR [TYPE] = 4))
			OR (@intSVOD_ZB = 0 AND G.DEP = @intLINK_DEP))
		AND G.DATE_PROV BETWEEN @dDateB1 AND @dDateE1
		AND (ISNULL (GAP_D.KBK, 0) IN (SELECT LINK_KBK FROM @TAB_KBK)
			OR ISNULL (GAP_K.KBK, 0) IN (SELECT LINK_KBK FROM @TAB_KBK))

	SELECT * FROM @TABLE_RES
		ORDER BY AP_CODE, ACCT_CODE, DATE_DOC
END


GO


GRANT EXECUTE ON dbo.[BK_REPORT_VM_OS1] TO PUBLIC

GO



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

GO

CREATE PROCEDURE dbo.SD_REP_RL 
	@cYear VARCHAR(4),
	@nMonth INT,
	@cVal1 CHAR(1), @nOtborLink1 int,	
	@nOption1 int,
	@nCheck3 int, /* Разделять Б/Л за счет ФСС и работодателя */
	@nLinkEmpl int = 0,
	@nCheck4 int = 0, /* Отображать источник при печати*/
	@nCheck5 int = 0, /* Печатать пустые р/л*/
	@nCheck7 int = 0, /* Отображать разряд */
	@cVal2 CHAR(1) = '', @nOtborLink2 int = 0,
	@nCheck8 int = 0 /* Выводить Ф.И.О. полностью */,
	@nCheck9 int = 0 /*Выводить наименование отдела вместо кода*/,
	@ALL_MONTH INT = 0	

AS BEGIN

	DECLARE @Month INT, @Year INT, @nYear INT, @ldDate DATETIME
	SET @ldDate = DBO.SalaryCalcPeriod()
	set @nYear = @cYear
	
	SELECT @Month = DATEPART(MONTH, @ldDate), @Year = DATEPART(YEAR, @ldDate)

	IF (@nMonth=0)
		set @nMonth = @Month
	
	IF (@nYear=0)
		set @nYear = @Year

	DECLARE @EDate datetime
	Set @EDate = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@nMonth,convert(int,@nYear)))

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output
	
	DECLARE @start_date DATETIME, @END_DATE DATETIME, @START_YEAR DATETIME
	SELECT @start_date = dbo.ConvertDMY2Date(1, @nMonth, @nYear)
	SELECT @END_DATE = dbo.DateEndOfMonth(@start_date)
	SELECT @START_YEAR = dbo.DateBeginOfYear(@start_date)

	CREATE TABLE #RES (
		LINK_EMPL INT, FIO VARCHAR(254), TN VARCHAR(15), MON TINYINT,
		OKLAD NUMERIC(20,2), FWT INT,
		CODE_PAY VARCHAR(10), NAME_PAY VARCHAR(254), SUM_PAY NUMERIC(20,2),
		CODE_TAX VARCHAR(10), NAME_TAX VARCHAR(254), SUM_TAX NUMERIC(20,2),
		REST_BEG NUMERIC(20,2), REST_END NUMERIC(20,2),
		
		SUM_TOTAL NUMERIC(20,2), DEDUCCT NUMERIC(20,2), NDFL NUMERIC(20,2),
		
		INSUR NUMERIC(20,2), 	
		GAIN NUMERIC(20,2),	
		ORDERS TINYINT
	)

	CREATE TABLE #EMPLS0 (LINK_EMPL INT)
	CREATE TABLE #EMPLS (LINK_EMPL INT)
	CREATE TABLE #EMPLS1 (LINK_EMPL INT, MON TINYINT)
	CREATE TABLE #EMPLS2 (LINK_EMPL INT, MON TINYINT)

	CREATE TABLE #GE (LINK INT)

	IF @nLinkEmpl = 0
	BEGIN

		IF LEN(@cVal1) <> 0 
			INSERT INTO #EMPLS0
			SELECT RECORD FROM dbo.OBJECT_VAR_EMPL WHERE LINK_UP = @nOtborLink1
		ELSE BEGIN
				INSERT INTO #EMPLS0
				SELECT LINK
				FROM dbo.EMPL
				WHERE 
					DEP_LINK = @DEP_LINK
			END
	END
	
	IF @nLinkEmpl > 0
	BEGIN
			INSERT INTO #EMPLS0 
			SELECT @nLinkEmpl
	END
	
	IF @cVal2 = '1' --Сотрудники из групп
	BEGIN
		INSERT INTO #GE (LINK)
		SELECT GE.LINK_EMPL 
		FROM 
			dbo.GROUPS_EMPL G
			INNER JOIN dbo.OBJECT_VAR_GROUPS_EMPL O ON G.LINK = O.RECORD
			INNER JOIN dbo.GROUPS_EMPL_REF GE ON GE.[LINK_GROUP] = G.LINK
		WHERE
			O.LINK_UP = @nOtborLink2
			
		INSERT INTO #EMPLS (LINK_EMPL)
		SELECT LINK_EMPL
		FROM #EMPLS0 E INNER JOIN #GE G ON E.LINK_EMPL = G.LINK
	END	
	ELSE
		INSERT INTO #EMPLS (LINK_EMPL)
		SELECT LINK_EMPL
		FROM #EMPLS0 E



	CREATE TABLE #T1( Link_Empl INT, MON TINYINT, TYP_OPER INT, WAY_CALC INT, summa NUMERIC(20,2) )
	CREATE TABLE #T2( Link_Empl INT, MON TINYINT, TYP_OPER INT, WAY_CALC INT, summa NUMERIC(20,2) )
	CREATE TABLE #T3(LINK_EMPL INT, MON TINYINT, SUMMA NUMERIC(20,2))

	CREATE TABLE #RES1 (
		LINK_EMPL INT, MON TINYINT,
		[DAYS] NUMERIC(15,2), PERC NUMERIC(15,2),
		CODE_PAY VARCHAR(20), NAME_PAY VARCHAR(254), SUM_PAY NUMERIC(20,2),
		CODE_TAX VARCHAR(20), NAME_TAX VARCHAR(254), SUM_TAX NUMERIC(20,2),
		ORDERS TINYINT,VKR_CODE VARCHAR(30),VKR_NAME VARCHAR(400))

	CREATE TABLE #SALARY_JURNAL_CALCULAT (
		[LINK_EMPL] int,
		[MON] TINYINT,
		[LINK_PAYS] int,
		[CODE_PAYS] varchar(20),
		[NAME_PAYS] varchar(254),
		[SNAME_PAYS] varchar(254),
		[WAY_CALC] tinyint,
		[MONTH_BEGIN] int,
		[YEAR_BEGIN] int,
		[MONTH_END] int,
		[YEAR_END] int,
		[PERIOD_BEGIN] datetime,
		[PERIOD_END] datetime,
		[PERC] numeric(15, 2),
		[DAYS] numeric(38, 2),
		[summa] numeric(38, 2),
		[LINK_DOC] int NULL,
		[CODE_DOC] varchar(30),
		[DATE1] datetime,
		[DATE2] datetime,
		[TYP_OPER] tinyint,
		[LINK_EKR] int,
		[CODE_EKR] char(4),
		[VKR_CODE] varchar(30),
		[VKR_NAME] varchar(400))

	CREATE TABLE #REST_B1(LINK_EMPL INT, [MON] TINYINT,
		BEG_PAY NUMERIC(20,2), BEG_TAX NUMERIC(20,2), BEG_R NUMERIC(20,2), 
		END_PAY NUMERIC(20,2), END_TAX NUMERIC(20,2),	
	)
	CREATE TABLE #REST_B(LINK_EMPL INT, [MON] TINYINT, REST_BEG NUMERIC(20,2), REST_D NUMERIC(20,2))		

	CREATE TABLE #SD_EMPL (
		[LINK] int,
		[MON] TINYINT,
		[FIO] varchar(254),
		[TAB] varchar(10),
		[SUBDIV_CODE] varchar(254),
		[post_name] varchar(254),
		[DATE_BEGIN] datetime,
		[DATE_END] datetime,
		[SACK] int,
		[NUM_STAKE] numeric(3, 2),
		[STATUS] VARCHAR (20))	

	DECLARE @BUF_ID VARCHAR(20), @LINK_EMPL2 INT
	DECLARE @SQL VARCHAR(1000)
	CREATE TABLE #OKLAD (LINK_EMPL INT, MON TINYINT, LINK_SOVM INT, SUMMA NUMERIC(18,2) )		

	CREATE TABLE #NORM_DAYS_TABLE (LINK_EMPL INT, MON TINYINT, DAY_NORM INT)

	---
	DECLARE @PAR1 INT
	SET @PAR1 = CASE WHEN @nLinkEmpl = 0 THEN -1 ELSE @nLinkEmpl END
		
	
	----
	SELECT DISTINCT
		[LINK] = SD.LINK_UP,
		[TYP_PAYMENT] = SD.TYP_PAYMENT
	INTO #DOCUMENTS_DED_PR
	FROM dbo.SDOC_VEDOM SD

	---
	set @nCheck3 = Coalesce(@nCheck3,0)

	CREATE TABLE #SA_EMPLS_W (LINK INT, LINK_EMPL INT, MON TINYINT, RAZR INT, SYST_PAY TINYINT, FOT TINYINT)	

	DECLARE @DATE_01 DATETIME
	DECLARE @Cur1 CURSOR, @NUM TINYINT
	SET @Cur1 = CURSOR FORWARD_ONLY
	FOR select NUM from dbo.MONTHS WHERE NUM <= @nMonth AND NUM >= (CASE WHEN @ALL_MONTH = 1 THEN 1 ELSE @nMonth END) order by NUM
	
	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @NUM
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN

			SET @DATE_01 = DATEADD(DAY, -1, dbo.ConvertDMY2Date(1,@NUM,convert(int,@nYear)))

			INSERT INTO #T1
			SELECT T.LinkEmpl, @NUM, T.TYP_OPER, T.WAY_CALC, T.summa
			FROM #EMPLS E INNER JOIN dbo.SALARY_TAX_DED_Sum_ALL_TABLE(
											@START_YEAR, 
											@DATE_01, 
											DEFAULT ) T on E.LINK_EMPL = T.LinkEmpl
			
			SET @DATE_01 = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@NUM,convert(int,@nYear)))

			INSERT INTO #T2 (Link_Empl, MON, TYP_OPER, WAY_CALC, summa)
			SELECT T.LinkEmpl, @NUM, T.TYP_OPER, T.WAY_CALC, T.summa
			FROM 
				#EMPLS E INNER JOIN dbo.SALARY_TAX_DED_Sum_ALL_TABLE(
											@START_YEAR, 
											@DATE_01, 
											DEFAULT) T on E.LINK_EMPL = T.LinkEmpl

			INSERT INTO #T3
			SELECT 
				SJ.LINK_EMPL, @NUM, SUM(SJ.summa) 
			FROM
				#EMPLS E 
				INNER JOIN dbo.CALCULATE_JURNAL SJ on E.LINK_EMPL = SJ.LINK_EMPL
				INNER JOIN (SELECT LINK_PAYS FROM dbo.NDFL_GroupTax() ) T ON T.LINK_PAYS = SJ.LINK_PAYS
			WHERE   
				SJ.LINK_DEP = @DEP_LINK
				AND SJ.PERIOD_BEGIN >= @START_YEAR AND SJ.PERIOD_END <= @DATE_01
			GROUP BY 
				SJ.LINK_EMPL
	
			SET @DATE_01 = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@NUM,convert(int,@nYear)))

			INSERT INTO #SA_EMPLS_W (link, link_empl, MON, RAZR, SYST_PAY, FOT)
			select link, link_empl, @NUM, RAZR, SYST_PAY, FOT 
			from [dbo].[SA_EMPLS_W_FN](DEFAULT,@DATE_01,DEFAULT,@DEP_LINK)
			
			---
			INSERT INTO #SALARY_JURNAL_CALCULAT(
				LINK_EMPL, MON, LINK_PAYS, CODE_PAYS, NAME_PAYS, SNAME_PAYS, WAY_CALC, 
				MONTH_BEGIN, YEAR_BEGIN, MONTH_END, YEAR_END, PERIOD_BEGIN, PERIOD_END, 
				PERC, [DAYS], summa, LINK_DOC, CODE_DOC, DATE1, DATE2, TYP_OPER, LINK_EKR, CODE_EKR, VKR_CODE, VKR_NAME)
			SELECT 
				SJC.LINK_EMPL,
				MON = @NUM,	
				SJC.[LINK_PAYS],
				[CODE_PAYS] = P.CODE,
				[NAME_PAYS] = P.NAME,
				[SNAME_PAYS] = P.[SNAME] + CASE WHEN ISNULL(@nCheck7,0) = 1 AND COALESCE(EP.FOT,0) = 2 AND COALESCE(EP.RAZR,0) > 0 THEN ' ' + CONVERT(VARCHAR(3),EP.RAZR) + 'р.' ELSE '' END,
				P.[WAY_CALC],
				[MONTH_BEGIN] = MONTH(SJC.PERIOD_BEGIN),
				[YEAR_BEGIN] = YEAR(SJC.PERIOD_BEGIN),
				[MONTH_END] = MONTH(SJC.PERIOD_END),
				[YEAR_END] = YEAR(SJC.PERIOD_END),
				[PERIOD_BEGIN] = dbo.DateBeginOfMonth(SJC.PERIOD_BEGIN),
				[PERIOD_END] = dbo.DateEndOfMonth(SJC.PERIOD_END),
				[PERC] = SJC.PROCENT,
				[DAYS] = CASE WHEN P.RL_TIME = 1 THEN SUM(case when COALESCE(EP.SYST_PAY,1) = 1 OR P.RL_DAYS = 1 then SJC.[DAYS] else SJC.[HOURS] end) ELSE NULL END,
				summa = sum(SJC.[SUMMA]),
 				[LINK_DOC] = (CASE WHEN doc.so_code IN ('DOCUMENTS_ADD_ARCHE', 'DOCUMENTS_ADD_FURLOUGH','DOCUMENTS_CALC_TRAVEL','DOCUMENTS_CALC_AVG','DOCUMENTS_DED_PAYROLL') THEN LINK_DOC ELSE 0 END),
 				[CODE_DOC] = (CASE WHEN doc.so_code IN ('DOCUMENTS_ADD_ARCHE', 'DOCUMENTS_ADD_FURLOUGH','DOCUMENTS_CALC_TRAVEL','DOCUMENTS_CALC_AVG','DOCUMENTS_DED_PAYROLL') THEN doc.so_code ELSE '' END),
				[DATE1] = (CASE WHEN doc.so_code IN ('DOCUMENTS_ADD_ARCHE', 'DOCUMENTS_ADD_FURLOUGH','DOCUMENTS_CALC_TRAVEL','DOCUMENTS_CALC_AVG','DOCUMENTS_DED_PAYROLL') THEN SJC.DATE_BEGIN ELSE dbo.DateBeginOfMonth(SJC.DATE_BEGIN) END),
				[DATE2] = (CASE WHEN doc.so_code IN ('DOCUMENTS_ADD_ARCHE', 'DOCUMENTS_ADD_FURLOUGH','DOCUMENTS_CALC_TRAVEL','DOCUMENTS_CALC_AVG','DOCUMENTS_DED_PAYROLL') THEN SJC.DATE_END ELSE dbo.DateEndOfMonth(SJC.DATE_END) END),
				[TYP_OPER] = P.OBJECT,
				[LINK_EKR] = (case when P.OBJECT = 1 AND @nCheck3 = 1 THEN COALESCE(SJC.LINK_EKR,P.LINK_EKR) ELSE null end),
				[CODE_EKR] = (case when P.OBJECT = 1 AND @nCheck3 = 1 THEN EKR.CODE ELSE '' end),
				[VKR_CODE] = (case when @nCheck4 = 1 THEN FIN.[CODE] ELSE '' end),
				[VKR_NAME] = (case when @nCheck4 = 1 THEN FIN.[NAME] ELSE '' end)
			FROM 
				#EMPLS E 
				INNER JOIN dbo.CALCULATE_JURNAL SJC ON SJC.LINK_EMPL = E.LINK_EMPL
				INNER JOIN dbo.PAYS P ON SJC.LINK_PAYS = P.LINK	
				LEFT JOIN #SA_EMPLS_W EP ON EP.MON = @NUM AND EP.link_empl = SJC.LINK_EMPL AND EP.link = COALESCE(SJC.LINK_SOVM,0)
				LEFT JOIN (Select distinct doc_link = d.link, so_link = so.link, so_code = rtrim(SO.CODE) from dbo.sdoc d inner join dbo.s_objects so on d.object = so.link) DOC
					on DOC.doc_link = SJC.LINK_DOC
				LEFT JOIN dbo.SAL_SFIN FIN on SJC.LINK_VKR = FIN.LINK
				LEFT JOIN dbo.KOSGU EKR on COALESCE(SJC.LINK_EKR,P.LINK_EKR) = EKR.LINK
			WHERE 
				P.OBJECT <> 3 
				AND MONTH(SJC.PERIOD_BEGIN) = @NUM 
				AND YEAR(SJC.PERIOD_BEGIN) = @nYear 
				AND SJC.LINK_DEP = @DEP_LINK
				AND (SJC.LINK_EMPL = @nLinkEmpl OR @nLinkEmpl = 0)
			group by 
				SJC.LINK_EMPL,COALESCE(EP.SYST_PAY,0), SJC.[LINK_PAYS], P.CODE, P.[SNAME], [RAZR], P.NAME, FOT,
				MONTH(SJC.PERIOD_BEGIN),YEAR(SJC.PERIOD_BEGIN),MONTH(SJC.PERIOD_END),YEAR(SJC.PERIOD_END),
				dbo.DateBeginOfMonth(SJC.PERIOD_BEGIN), dbo.DateEndOfMonth(SJC.PERIOD_END), 
				(CASE WHEN doc.so_code IN ('DOCUMENTS_ADD_ARCHE', 'DOCUMENTS_ADD_FURLOUGH','DOCUMENTS_CALC_TRAVEL','DOCUMENTS_CALC_AVG','DOCUMENTS_DED_PAYROLL') THEN SJC.DATE_BEGIN ELSE dbo.DateBeginOfMonth(SJC.DATE_BEGIN) END),
				(CASE WHEN doc.so_code IN ('DOCUMENTS_ADD_ARCHE', 'DOCUMENTS_ADD_FURLOUGH','DOCUMENTS_CALC_TRAVEL','DOCUMENTS_CALC_AVG','DOCUMENTS_DED_PAYROLL') THEN SJC.DATE_END ELSE dbo.DateEndOfMonth(SJC.DATE_END) END),
				SJC.PROCENT, 
				P.OBJECT, [WAY_CALC], 
				(case when P.OBJECT = 1 AND @nCheck3 = 1 THEN EKR.CODE ELSE '' end), 
				(case when P.OBJECT = 1 AND @nCheck3 = 1 THEN COALESCE(SJC.LINK_EKR,P.LINK_EKR) ELSE null end), 
				(CASE WHEN doc.so_code IN ('DOCUMENTS_ADD_ARCHE', 'DOCUMENTS_ADD_FURLOUGH','DOCUMENTS_CALC_TRAVEL','DOCUMENTS_CALC_AVG','DOCUMENTS_DED_PAYROLL') THEN LINK_DOC ELSE 0 END),
				(CASE WHEN doc.so_code IN ('DOCUMENTS_ADD_ARCHE', 'DOCUMENTS_ADD_FURLOUGH','DOCUMENTS_CALC_TRAVEL','DOCUMENTS_CALC_AVG','DOCUMENTS_DED_PAYROLL') THEN doc.so_code ELSE '' END),
				(case when @nCheck4 = 1 THEN FIN.[CODE] ELSE '' end),
				(case when @nCheck4 = 1 THEN FIN.[NAME] ELSE '' end),
				P.RL_TIME
		
			--
			IF @nCheck3 = 1
			UPDATE #SALARY_JURNAL_CALCULAT
				Set 
					CODE_PAYS = rtrim(ltrim(CODE_PAYS)) + (case rtrim(ltrim(CODE_EKR)) when '211' then 'Р' when '213' then 'Ф' else '' end)
				where link_ekr is not null and way_calc in (13,20) and 	TYP_OPER = 1

			
			
			INSERT INTO #RES1
			SELECT 
				SJC.LINK_EMPL,
				@NUM,
				SJC.[DAYS], 
				SJC.PERC,
				CASE WHEN TYP_OPER = 1 THEN LTRIM(RTRIM(CODE_PAYS)) ELSE '' END,
				CASE WHEN TYP_OPER = 1 THEN 
						LTRIM(RTRIM(SNAME_PAYS)) + SPACE(1) +
						case when code_doc in ('DOCUMENTS_ADD_ARCHE', 'DOCUMENTS_ADD_FURLOUGH','DOCUMENTS_CALC_TRAVEL','DOCUMENTS_CALC_AVG') then
								'(' + convert(varchar(5),date1,104) + '-' + convert(varchar(5),date2,104) + ')'
						else
							case  when date1 <> period_begin then
									'(за ' + dbo.PrintRLGetMonthYear(date1) 
									+ case when (year(date1) * 100 + Month(date1)) = (year(date2) * 100 + Month(date2)) then '' 
										else '-' + dbo.PrintRLGetMonthYear(date2) end+ ')' 
							else '' 
							end --when date1 <> period_begin then
						end
				ELSE '' 
				END,
				CASE WHEN TYP_OPER = 1 THEN SUMMA ELSE 0 END,
				CASE WHEN TYP_OPER = 2 THEN LTRIM(RTRIM(CODE_PAYS)) ELSE '' END,
				CASE WHEN 
					TYP_OPER = 2 THEN 
						LTRIM(RTRIM(SNAME_PAYS)) + SPACE(1) 
						+ case 
							when date1 <> period_begin 
								then '(за ' + dbo.PrintRLGetMonthYear(date1) + ')' 
							else '' 
						end			
					ELSE '' 
				END,
				CASE WHEN TYP_OPER = 2 THEN SUMMA ELSE 0 END,
				CASE 
					WHEN TYP_OPER = 1 THEN 1
					WHEN TYP_OPER = 2 AND CODE_DOC <> 'DOCUMENTS_DED_PAYROLL'  THEN 2
					WHEN TYP_OPER = 2 AND CODE_DOC = 'DOCUMENTS_DED_PAYROLL' AND (SELECT TYP_PAYMENT FROM #DOCUMENTS_DED_PR DDP WHERE DDP.LINK =  LINK_DOC) = 2  THEN 3
					WHEN TYP_OPER = 2 AND CODE_DOC = 'DOCUMENTS_DED_PAYROLL' AND (SELECT TYP_PAYMENT FROM #DOCUMENTS_DED_PR DDP WHERE DDP.LINK =  LINK_DOC) = 3  THEN 4
					WHEN TYP_OPER = 2 AND CODE_DOC = 'DOCUMENTS_DED_PAYROLL' AND (SELECT TYP_PAYMENT FROM #DOCUMENTS_DED_PR DDP WHERE DDP.LINK =  LINK_DOC) = 1  THEN 5

					ELSE 7  
				END,
				SJC.VKR_CODE,
				SJC.VKR_NAME
			FROM 
				#SALARY_JURNAL_CALCULAT SJC
			WHERE 
				TYP_OPER <> 3
				AND MONTH_BEGIN = @NUM
				AND YEAR_BEGIN = @nYear 				

			INSERT INTO #RES1
			SELECT 
				LINK_EMPL, @NUM, 0, 0, 
				'', 'Итого', SUM(CASE WHEN ORDERS = 1 THEN SUM_PAY ELSE 0 END),
				'', '', SUM(CASE WHEN ORDERS between 2 and 5 THEN SUM_TAX ELSE 0 END),
				6,'',''
			FROM #RES1
			WHERE MON = @NUM
			GROUP BY LINK_EMPL				


			INSERT INTO #EMPLS1
			SELECT LINK_EMPL, @NUM FROM #T1 WHERE MON = @NUM AND WAY_CALC = 0
			UNION
			SELECT LINK_EMPL, @NUM FROM #T2 WHERE MON = @NUM AND WAY_CALC = 0 
			UNION
			SELECT s.LINK_EMPL, @NUM FROM #EMPLS E left join SAL_REMAIN s on s.LINK_EMPL = E.LINK_EMPL WHERE YEAR_SAL = @nYear
			UNION
			SELECT LINK_EMPL, @NUM FROM #RES1 WHERE MON = @NUM 
			

				
			INSERT INTO #REST_B1
			SELECT LINK_EMPL, @NUM,
				[BEG_PAY] = ISNULL((SELECT SUMMA FROM #T1 T1 WHERE MON = @NUM AND DF.LINK_EMPL = T1.LINK_EMPL AND T1.TYP_OPER = 1 AND T1.WAY_CALC = 0), 0.00),
				[BEG_TAX] = ISNULL((SELECT SUMMA FROM #T1 T1 WHERE MON = @NUM AND  DF.LINK_EMPL = T1.LINK_EMPL AND T1.TYP_OPER = 2 AND T1.WAY_CALC = 0), 0.00),
				[BEG_R] = ISNULL( (SELECT SUM(SUMMA) FROM SAL_REMAIN DSR WHERE YEAR_SAL = @nYear AND DSR.LINK_EMPL = DF.LINK_EMPL), 0.0),
				[END_PAY] = ISNULL((SELECT SUMMA FROM #T2 T1 WHERE MON = @NUM AND  DF.LINK_EMPL = T1.LINK_EMPL AND T1.TYP_OPER = 1 AND T1.WAY_CALC = 0), 0.00),
				[END_TAX] = ISNULL((SELECT SUMMA FROM #T2 T1 WHERE MON = @NUM AND  DF.LINK_EMPL = T1.LINK_EMPL AND T1.TYP_OPER = 2 AND T1.WAY_CALC = 0), 0.00)
			FROM #EMPLS1 DF
			WHERE MON = @NUM

			INSERT INTO #REST_B
			SELECT 
				LINK_EMPL, @NUM,
				BEG_PAY - BEG_TAX + BEG_R AS REST_BEG,
				END_PAY - END_TAX + BEG_R AS REST_D
			FROM #REST_B1
			WHERE MON = @NUM

			INSERT INTO #EMPLS2
			SELECT LINK_EMPL, @NUM FROM #REST_B WHERE MON = @NUM AND REST_BEG <> 0.00
			UNION
			SELECT LINK_EMPL, @NUM FROM #RES1 WHERE MON = @NUM

			INSERT INTO #SD_EMPL ([LINK], [MON], [FIO], [TAB], [SUBDIV_CODE], [post_name], [DATE_BEGIN], [DATE_END], [SACK], [NUM_STAKE], [STATUS])	
			SELECT LINK, @NUM,
					FIO = CASE WHEN ISNULL(@nCheck8,0) = 0 THEN FIO ELSE LEFT(LTRIM(RTRIM(ISNULL(LTRIM(RTRIM(E.FM)) + ' ' + LTRIM(RTRIM(E.IM)) + ' ' + LTRIM(RTRIM(E.OT)),'Не заполнено'))),100) END, 
					TAB, 
					SUBDIV_CODE = CASE WHEN ISNULL(@nCheck9,0) = 0 THEN SUBDIV_CODE ELSE LTRIM(RTRIM(SUBDIV_NAME)) END,
					post_name, DATE_BEGIN, DATE_END, SACK, NUM_STAKE = STAKE,
					[STATUS] = case when E.STATUS_EMPL = 1 THEN 'Основной' 
									when E.STATUS_EMPL = 2 THEN 'Совместитель' 
									ELSE 'Внешний совместитель' END 
					
			FROM dbo.SD_EMPL_FN(@PAR1,@DATE_01, DEFAULT, @DEP_LINK) E
		
			---
			INSERT INTO #EMPLS2
			SELECT LINK, @NUM
			FROM #SD_EMPL E 
				INNER JOIN #EMPLS O ON O.LINK_EMPL = E.LINK --Уже отобранные сотрудники
			WHERE 
				@nCheck5 = 1 
				AND (@Year * 100 + @NUM) BETWEEN (YEAR(DATE_BEGIN)*100 + MONTH(DATE_BEGIN)) AND COALESCE((YEAR(DATE_END)*100 + MONTH(DATE_END)), (@Year * 100 + @NUM))
				AND LINK NOT IN (SELECT LINK_EMPL FROM #EMPLS2)
				AND E.SACK = 0 --Не выводить уволенных	
			
			----
			EXEC DBO.GETRANDSTR 20, @BUF_ID OUT

			SET @SQL = '
			INSERT INTO DBO.BUFFER (ID, LINK)
			SELECT DISTINCT ''' + @BUF_ID + ''', LINK_EMPL FROM #EMPLS2'

			EXEC (@SQL)
			
			INSERT INTO #OKLAD (LINK_EMPL, MON, LINK_SOVM, SUMMA)
			SELECT LINK_EMPL, @NUM, LINK_SOVM, SUMMA FROM DBO.SA_OKLAD_EMPL_FN(@DATE_01,DEFAULT,0,@BUF_ID,@DEP_LINK)	

			SET @SQL = '
				DELETE FROM DBO.BUFFER WHERE ID = ''' + @BUF_ID + ''''
			EXEC (@SQL)

			----
			INSERT INTO #NORM_DAYS_TABLE (LINK_EMPL, MON, DAY_NORM)
			SELECT LINK_EMPL, @NUM, DAY_NORM FROM dbo.NORM_DAYS_TABLE(@NUM, @nYear)							
					
		END
	
		FETCH NEXT FROM @Cur1 INTO @NUM
	END
	
	CLOSE @Cur1
	DEALLOCATE @Cur1


	---
	SET @LINK_EMPL2 = CASE WHEN @nLinkEmpl > 0 THEN @nLinkEmpl ELSE -1 END

	CREATE TABLE #RES0 (
		[ID] INT IDENTITY,
		LINK_EMPL1 INT, FIO VARCHAR(254), TN VARCHAR(15), [STATUS] VARCHAR (20), MON TINYINT, SUBDIV VARCHAR(254),POST VARCHAR(50),
		OKLAD NUMERIC(20,2), FWT INT,
		REST_BEG NUMERIC(20,2), REST_D NUMERIC(20,2),
		
		SUM_TOTAL NUMERIC(20,2), 
		DEDUCT NUMERIC(20,2), 	
		NDFL NUMERIC(20,2),	
		
		INSUR NUMERIC(20,2), 	
		GAIN NUMERIC(20,2),	
		NUM INT
	)

	----
	INSERT INTO #RES0(
		LINK_EMPL1, FIO, TN, [STATUS], MON, SUBDIV, POST,
		OKLAD, FWT,
		REST_BEG, REST_D,
		
		SUM_TOTAL, 
		DEDUCT, 	
		NDFL,	
		
		INSUR, 	
		GAIN,	
		NUM
	)
	SELECT 
		[LINK_EMPL] = ISNULL(EP.LINK,NULL),
		[FIO] = LTRIM(RTRIM(FIO)),
		[TN] = EP.TAB,
		[STATUS] = EP.[STATUS] ,
		EP.MON,
		[SUBDIV] =EP.subdiv_code,
		[POST] = convert(varchar(50),EP.post_name),
		[OKLAD] = O.SUMMA * EP.NUM_STAKE, --OKL.OKLAD,
		[FWT] = ND.DAY_NORM,
		[REST_BEG] = ISNULL(RB.REST_BEG, 0.00),
		[REST_D] = ISNULL(RB.REST_D, 0.00),
		[SUM_TOTAL] = ISNULL(T3.SUMMA, 0),
		[DEDUCT] = ISNULL((SELECT SUM(SUMMA) 
					FROM dbo.SAL_DED_MONTH 
					WHERE LINK_EMPL = EP.LINK AND YEAR(DATE_DED) = YEAR(@END_DATE)
					AND DATE_DED <= dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,EP.MON,convert(int,@nYear))) AND TYPE IN (1, 2)),0),
		[NDFL] = 
			ISNULL((SELECT SUM(SUMMA) FROM #T2 T1 WHERE EP.MON = T1.MON AND EP.LINK = T1.LINK_EMPL AND T1.TYP_OPER = 2 AND T1.WAY_CALC IN(4, 5, 6)), 0.00),
		[INSUR] = 
			ISNULL((SELECT SUM(SUMMA) FROM #T2 T1 WHERE EP.MON = T1.MON AND EP.LINK = T1.LINK_EMPL AND T1.TYP_OPER = 3 AND T1.WAY_CALC = 6), 0.00),
		[GAIN]  = 
			ISNULL((SELECT SUM(SUMMA) FROM #T2 T1 WHERE EP.MON = T1.MON AND EP.LINK = T1.LINK_EMPL AND T1.TYP_OPER = 3 AND T1.WAY_CALC = 7), 0.00),
		0
	FROM 
		#EMPLS2 E --отбор сотрудников
		INNER JOIN #SD_EMPL EP ON EP.LINK = E.LINK_EMPL AND EP.MON = E.MON	--сотрудники
		LEFT OUTER JOIN #REST_B RB ON EP.LINK = RB.LINK_EMPL AND EP.MON = RB.MON --Входящие остатки
		LEFT OUTER JOIN #T3 T3 ON EP.LINK = T3.LINK_EMPL AND EP.MON = T3.MON --доход с начала года
		LEFT JOIN #OKLAD O ON O.LINK_EMPL = EP.LINK AND EP.MON = O.MON
		LEFT JOIN #NORM_DAYS_TABLE ND ON EP.LINK = ND.LINK_EMPL AND EP.MON = ND.MON
	order by 
		 (CASE @nOption1 
			WHEN 1 THEN COALESCE(EP.TAB,'яяяяя') 
			WHEN 2 THEN COALESCE(EP.subdiv_code,'яяяяя') 
			WHEN 3 THEN COALESCE(EP.subdiv_code,'яяяяя')
			ELSE COALESCE(EP.FIO,'яяяяя')  
		END),
		 (CASE @nOption1 
			WHEN 2 THEN COALESCE(EP.TAB,'яяяяя') 
			WHEN 3 THEN COALESCE(EP.FIO,'яяяяя') 
			ELSE 'яяяяя'  
		END),
		EP.MON
	
	---
	UPDATE #RES0 SET NUM = CEILING(CAST([ID] AS FLOAT ) / 2.0)
	---

	IF @nCheck4  = 1
	BEGIN

		CREATE TABLE #VKR_EMPL_CUR (EMPL_LINK INT, MON TINYINT, VKR_ALL VARCHAR(400))
		DECLARE @EMPL_CUR CURSOR, @vkr_empl_link INT, @vkr_empl_MON INT

		SET @EMPL_CUR = CURSOR FAST_FORWARD FOR
			SELECT DISTINCT LINK_EMPL, MON FROM #RES1
		
		OPEN @EMPL_CUR
		FETCH NEXT FROM @EMPL_CUR INTO @vkr_empl_link, @vkr_empl_MON
		WHILE (@@FETCH_STATUS = 0)	
		BEGIN
			DECLARE @VKR_EMPL_CUR CURSOR
			SET @VKR_EMPL_CUR = CURSOR FAST_FORWARD FOR
				SELECT DISTINCT VKR_CODE, VKR_NAME FROM #RES1 WHERE LINK_EMPL = @vkr_empl_link AND MON = @vkr_empl_MON AND RTRIM(VKR_CODE)<>'' AND VKR_CODE IS NOT NULL
			
			DECLARE @VKR_ALL VARCHAR(400), @VKR_CODE VARCHAR(30), @VKR_NAME VARCHAR(120)
			SET @VKR_ALL = ''
			OPEN @VKR_EMPL_CUR
			FETCH NEXT FROM @VKR_EMPL_CUR INTO @VKR_CODE, @VKR_NAME
			WHILE (@@FETCH_STATUS = 0)
			BEGIN
				SET @VKR_ALL = @VKR_ALL + RTRIM(@VKR_CODE) + ' - '  + RTRIM(SUBSTRING(@VKR_NAME,1,30)) + ', ' + CHAR(10)
				FETCH NEXT FROM @VKR_EMPL_CUR INTO @VKR_CODE, @VKR_NAME
			END
			CLOSE @VKR_EMPL_CUR
			DEALLOCATE @VKR_EMPL_CUR

			IF LTRIM(RTRIM(COALESCE(@VKR_ALL,''))) <> ''
				SET @VKR_ALL = SUBSTRING(@VKR_ALL, 1, LEN(@VKR_ALL)-3)
			ELSE
				SET @VKR_ALL = ''
				
			INSERT #VKR_EMPL_CUR VALUES (@vkr_empl_link, @vkr_empl_MON, @VKR_ALL)
			FETCH NEXT FROM @EMPL_CUR INTO @vkr_empl_link, @vkr_empl_MON
		END
		CLOSE @EMPL_CUR
		DEALLOCATE @EMPL_CUR

		IF EXISTS (SELECT * FROM #RES0)  
			select 
				R0.ID, R0.LINK_EMPL1, R0.FIO, R0.TN, R0.[STATUS], R0.MON, R0.SUBDIV, R0.POST, R0.OKLAD, R0.FWT, R0.REST_BEG, R0.REST_D, R0.SUM_TOTAL, R0.DEDUCT, R0.NDFL, R0.INSUR, R0.GAIN, R0.NUM,
				R1.LINK_EMPL, R1.DAYS, R1.PERC, R1.CODE_PAY, R1.NAME_PAY, R1.SUM_PAY, R1.CODE_TAX, R1.NAME_TAX, R1.SUM_TAX, R1.ORDERS, R1.VKR_CODE, R1.VKR_NAME,
				CONVERT(VARCHAR(300),VEC.VKR_ALL) AS VKR_ALL,
				CASE 
					WHEN ORDERS = 1 THEN NAME_PAY
					WHEN ORDERS = 2 THEN NAME_TAX
					WHEN ORDERS = 3 THEN Rtrim(NAME_TAX) + ' (Аванс)'
					WHEN ORDERS = 4 THEN Rtrim(NAME_TAX) + ' (Межрасч. выплаты)'
					WHEN ORDERS = 5 THEN Rtrim(NAME_TAX) + ' (Зарплата)'
					WHEN ORDERS = 6 THEN 'Итого'
					ELSE NAME_TAX
				END AS [NAME]
			from #RES0 R0 LEFT OUTER JOIN #RES1 R1 ON R0.MON = R1.MON AND R0.LINK_EMPL1 = R1.LINK_EMPL 
				LEFT JOIN #VKR_EMPL_CUR VEC ON R1.MON = VEC.MON AND R1.LINK_EMPL = VEC.EMPL_LINK
			ORDER BY
			 (CASE @nOption1 
				WHEN 1 THEN COALESCE(TN,'яяяяя') 
				WHEN 2 THEN COALESCE(subdiv,'яяяяя') 
				WHEN 3 THEN COALESCE(subdiv,'яяяяя')
				ELSE COALESCE(FIO,'яяяяя')  
			END),
			 (CASE @nOption1 
				WHEN 2 THEN COALESCE(TN,'яяяяя') 
				WHEN 3 THEN COALESCE(FIO,'яяяяя') 
				ELSE 'яяяяя'  
			END),
			R0.ID, R0.LINK_EMPL1, ORDERS, CODE_PAY, CODE_TAX
		ELSE 
		
			SELECT ID = 0, LINK_EMPL1 = 0, FIO = '' , TN = '', [STATUS] = '', MON = NULL, SUBDIV = NULL, POST= NULL,OKLAD= NULL, FWT= NULL, REST_BEG= NULL,  
				REST_D= NULL, SUM_TOTAL= NULL,  DEDUCT= NULL, NDFL= NULL, INSUR= NULL, GAIN= NULL, NUM= NULL,
				LINK_EMPL = NULL, DAYS = NULL, PERC= NULL, CODE_PAY= NULL, NAME_PAY= NULL, SUM_PAY= NULL, CODE_TAX= NULL, NAME_TAX= NULL, 
				SUM_TAX= NULL, ORDERS= NULL,  VKR_CODE= NULL, VKR_NAME= NULL,
				VKR_ALL = NULL,[NAME]= NULL
				

	END	
	ELSE
	BEGIN
		
		IF EXISTS (SELECT * FROM #RES0)  
			select 
				R0.ID, R0.LINK_EMPL1, R0.FIO, R0.TN, R0.[STATUS], R0.MON, R0.SUBDIV, R0.POST, R0.OKLAD, R0.FWT, R0.REST_BEG, R0.REST_D, R0.SUM_TOTAL, R0.DEDUCT, R0.NDFL, R0.INSUR, R0.GAIN, R0.NUM,
				R1.LINK_EMPL, R1.DAYS, R1.PERC, R1.CODE_PAY, R1.NAME_PAY, R1.SUM_PAY, R1.CODE_TAX, R1.NAME_TAX, R1.SUM_TAX, R1.ORDERS, R1.VKR_CODE, R1.VKR_NAME,
				'' as VKR_ALL,
				CASE 
					WHEN ORDERS = 1 THEN NAME_PAY
					WHEN ORDERS = 2 THEN NAME_TAX
					WHEN ORDERS = 3 THEN Rtrim(NAME_TAX) + ' (Аванс)'
					WHEN ORDERS = 4 THEN Rtrim(NAME_TAX) + ' (Межрасч. выплаты)'
					WHEN ORDERS = 5 THEN Rtrim(NAME_TAX) + ' (Зарплата)'
					WHEN ORDERS = 6 THEN 'Итого'
					ELSE isnull(NAME_TAX,'')
				END AS [NAME]
			from #RES0 R0 LEFT OUTER JOIN #RES1 R1 ON R0.MON = R1.MON AND R0.LINK_EMPL1 = R1.LINK_EMPL
			ORDER BY
			 (CASE @nOption1 
				WHEN 1 THEN COALESCE(TN,'яяяяя') 
				WHEN 2 THEN COALESCE(subdiv,'яяяяя') 
				WHEN 3 THEN COALESCE(subdiv,'яяяяя')
				ELSE COALESCE(FIO,'яяяяя')  
			END),
			 (CASE @nOption1 
				WHEN 2 THEN COALESCE(TN,'яяяяя') 
				WHEN 3 THEN COALESCE(FIO,'яяяяя') 
				ELSE 'яяяяя'  
			END),
			R0.ID, R0.LINK_EMPL1, ORDERS, CODE_PAY, CODE_TAX
		ELSE 
		
			SELECT ID = 0, LINK_EMPL1 = 0, FIO = '' , TN = '', [STATUS] = '', MON = NULL, SUBDIV = NULL, POST= NULL,OKLAD= NULL, FWT= NULL, REST_BEG= NULL,  
				REST_D= NULL, SUM_TOTAL= NULL,  DEDUCT= NULL, NDFL= NULL, INSUR= NULL, GAIN= NULL, NUM= NULL,
				LINK_EMPL = NULL, DAYS = NULL, PERC= NULL, CODE_PAY= NULL, NAME_PAY= NULL, SUM_PAY= NULL, CODE_TAX= NULL, NAME_TAX= NULL, 
				SUM_TAX= NULL, ORDERS= NULL,  VKR_CODE= NULL, VKR_NAME= NULL,
				VKR_ALL = NULL,[NAME]= NULL	
			
	END
END

GO


GRANT EXECUTE ON dbo.[SD_REP_RL] TO PUBLIC

GO

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

GO

/* © Кейсистемс (Keysystems), 2010 Процедура формирования строк и значений формы 0503125 */

CREATE PROCEDURE dbo.RT_CALC_0503125M_ITOG_2011
@Void int,--@table int,
@LSF int
AS

if exists (select * from tempdb.dbo.sysobjects where id = object_id(N'[tempdb].[dbo].[#res]')) begin
select 0
return
end

declare @cAccount varchar(9),  -- девять знаков: [1] - код вида деятельности [2..6] - счёт(синт+ан) [7..9] - СГУ
@cSource char(1),
@cSinth char(3),
@cAnalit char(2),
@cSGU char(3),
@iLinkAccount int,
@dBeginDate datetime,
@dEndDate datetime,
@iThisDep int,
@iCorrDep int,
@i int,
@j int,
@jj int,
@iLink_col int,
@code_row varchar(50),
@float_val numeric(20,4),
@str_val varchar(250),
@cVidForm varchar(250),
@cVidFormCode int,
@iLink_Table int,
@code_form varchar(50)

declare @table2 table(nn int IDENTITY(1,1),Name_bp varchar(254), ppp char(3), el_bud char(2), okato char(8), KBK varchar(50), Code_Acc varchar(9), summa_db numeric(20,4), summa_kr numeric(20,4),korr_acc varchar(9), dnd tinyint, link varchar(254), key_prov
int, tabsource tinyint)

-- вытаскиваем данные из сохранённой формы
set @cAccount = ltrim(rtrim(replace(dbo.RN_GET_ATR_VALUE(@LSF,'REPORTS_ATR_ACC_2011'),'.','')))
set @cSource = substring(@cAccount,1,1) -- вид деятельности
set @cSinth = substring(@cAccount,2,3)  -- синтетический счёт
set @cAnalit = substring(@cAccount,5,2) -- аналитическая составляющая
set @cSGU = substring(@cAccount,7,3)    -- СГУ

set @cVidForm = ltrim(rtrim(dbo.RN_GET_ATR_VALUE(@LSF,'REPORTS_ATR_NAFO')))
set @cVidFormCode = -1
select @cVidFormCode = link from dbo.RT_VIEW_NAFO_125 where [Name] = @cVidForm

select @code_form = rtrim(code) from dbo.report_forms where link_form = (select link_form from dbo.report_saved_forms where link_saved_form = @LSF)

-- определяем период (если в январе формируем, то берём весь предыдущий год не включая 31 декабря)
select @dBeginDate = Begin_Date from dbo.report_saved_forms where link_saved_form = @LSF
-- set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then (@dBeginDate - (datepart(dd,@dBeginDate))) - 1 else @dBeginDate - (datepart(dd,@dBeginDate)) end
-- set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')
set @dEndDate = case when datepart(mm,(@dBeginDate - (datepart(dd,@dBeginDate)))) = 12 then @dBeginDate - 1 else @dBeginDate end
set @dBeginDate = convert(datetime,convert(char(4),YEAR(@dEndDate))+'-01'+'-01'+' 00:00:00.000')

-- получаем линк указанного счёта
select @iLinkAccount = link from dbo.s_accounts
where cSource = @cSource
and cSinth = @cSinth
and cAnalit = @cAnalit

-- линк организации которая собственно формирует справку
select @iThisDep = Link_Organization from dbo.report_saved_forms where link_saved_form = @LSF

set @j = 0
declare @table TINYINT
set @table = 1
while @table !> 3 begin
select @iLink_Table = link_table from dbo.report_tables where link_form = (select top 1 link_form from dbo.report_saved_forms where link_saved_form = @LSF) and Orders = @table
if @table in (1,3) begin
insert into @table2 (Name_bp, ppp, okato, el_bud, KBK, Code_acc, summa_db, summa_kr, korr_acc, dnd, link, key_prov, tabsource)
select
coalesce(rd1.Str_Val,''),
substring(coalesce(rd2.Str_Val,''),1,3),
substring(coalesce(rd3.Str_Val,''),1,8),
substring(coalesce(rd4.Str_Val,''),1,2),
case
WHEN  right(rtrim(@cAccount),8) in ('30406000')
THEN '00000000000000000'
when @table = 1 and right(rtrim(@cAccount),8) in ('20551560','20551660')
then right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),10)+'0000000000',14)
when @table = 1 and right(rtrim(@cAccount),8) in ('40110180','40110151','40120251','20651560','20651660','20651000')
then right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),10)+'00000000000000',14)
when @table = 1 and right(rtrim(@cAccount),8) not in ('40110180','40110151','40120251','20551560','20551660','20651560','20651660','20651000')
then right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),3)+'00000000000000',14)
when @table = 3 and right(rtrim(@cAccount),8) in ('30111000','30131000','30141000','30151000','30121000', '30113000')
then right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),14)+'00000000000000',14)
when @table = 3 and right(rtrim(@cAccount),8) in ('30111810','30131810', '30111710', '30113810', '30113710')
then right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),10)+'00000000000000',14)
else right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+left(left(ltrim(coalesce(rd6.Str_Val,'')),4)+'00000000000000',14)
end,
case WHEN right(rtrim(@cAccount),8) in ('30406000')
THEN CASE WHEN isnull(rd7.Float_Val,0.00) <> 0
THEN LEFT(@cAccount,6) + '830'
ELSE LEFT(@cAccount,6) + '730' END 
ELSE @cAccount
END,
isnull(rd7.Float_Val,0.00),
isnull(rd8.Float_Val,0.00),
substring(coalesce(rd9.Str_Val,''),1,9),
case when cast(rtrim(isnull(rd10.Str_Val,'')) as varchar) not in (0,1) then NULL else cast(rtrim(isnull(rd10.Str_Val,'')) as varchar) end,
srows.Code_Row,
null,
@table
from (
select Code_Row from #report_dinamics
where link_sf = @LSF and right(rtrim(Code_Row),1) like '[0-9]' and link_col in (select link_col from dbo.report_coloumns where link_table = @iLink_Table)
group by Code_Row
) as srows
left join #report_dinamics as rd1 on rd1.link_sf = @LSF and rd1.Code_Row = srows.Code_Row and 1 = (select Orders from dbo.report_coloumns where link_col = rd1.link_col) and rd1.link_col = (select link_col from dbo.report_coloumns where Orders = 1 and Link_Table = @iLink_Table)
left join #report_dinamics as rd2 on rd2.link_sf = @LSF and rd2.Code_Row = srows.Code_Row and 2 = (select Orders from dbo.report_coloumns where link_col = rd2.link_col) and rd2.link_col = (select link_col from dbo.report_coloumns where Orders = 2 and Link_Table = @iLink_Table)
left join #report_dinamics as rd3 on rd3.link_sf = @LSF and rd3.Code_Row = srows.Code_Row and 3 = (select Orders from dbo.report_coloumns where link_col = rd3.link_col) and rd3.link_col = (select link_col from dbo.report_coloumns where Orders = 3 and Link_Table = @iLink_Table)
left join #report_dinamics as rd4 on rd4.link_sf = @LSF and rd4.Code_Row = srows.Code_Row and 4 = (select Orders from dbo.report_coloumns where link_col = rd4.link_col) and rd4.link_col = (select link_col from dbo.report_coloumns where Orders = 4 and Link_Table = @iLink_Table)
left join #report_dinamics as rd5 on rd5.link_sf = @LSF and rd5.Code_Row = srows.Code_Row and 5 = (select Orders from dbo.report_coloumns where link_col = rd5.link_col) and rd5.link_col = (select link_col from dbo.report_coloumns where Orders = 5 and Link_Table = @iLink_Table)
left join #report_dinamics as rd6 on rd6.link_sf = @LSF and rd6.Code_Row = srows.Code_Row and 6 = (select Orders from dbo.report_coloumns where link_col = rd6.link_col) and rd6.link_col = (select link_col from dbo.report_coloumns where Orders = 6 and Link_Table = @iLink_Table)
left join #report_dinamics as rd7 on rd7.link_sf = @LSF and rd7.Code_Row = srows.Code_Row and 7 = (select Orders from dbo.report_coloumns where link_col = rd7.link_col) and rd7.link_col = (select link_col from dbo.report_coloumns where Orders = 7 and Link_Table = @iLink_Table)
left join #report_dinamics as rd8 on rd8.link_sf = @LSF and rd8.Code_Row = srows.Code_Row and 8 = (select Orders from dbo.report_coloumns where link_col = rd8.link_col) and rd8.link_col = (select link_col from dbo.report_coloumns where Orders = 8 and Link_Table = @iLink_Table)
left join #report_dinamics as rd9 on rd9.link_sf = @LSF and rd9.Code_Row = srows.Code_Row and 9 = (select Orders from dbo.report_coloumns where link_col = rd9.link_col) and rd9.link_col = (select link_col from dbo.report_coloumns where Orders = 9 and Link_Table = @iLink_Table)
left join #report_dinamics as rd10 on rd10.link_sf = @LSF and rd10.Code_Row = srows.Code_Row and 10 = (select Orders from dbo.report_coloumns where link_col = rd10.link_col) and rd10.link_col = (select link_col from dbo.report_coloumns where Orders = 10
and Link_Table = @iLink_Table)

-- исключение, добавить сумму по '30406000'
INSERT @table2 (Name_bp, ppp, el_bud, okato, KBK, Code_Acc, summa_db, summa_kr,
       korr_acc, dnd, link, key_prov, tabsource)
SELECT Name_bp, ppp, el_bud, okato, KBK, SUBSTRING(Code_Acc,1,6)+'730', 0, summa_kr,
       korr_acc, dnd, link, key_prov, tabsource FROM @table2 WHERE SUBSTRING(Code_acc,2,8) = '30406830' AND summa_kr<>0

UPDATE @table2
SET summa_kr = 0
WHERE SUBSTRING(Code_acc,2,8) = '30406830' AND summa_kr<>0
--select * From @table2
end
else BEGIN
   
   
   
insert into @table2 (Name_bp, ppp, okato, el_bud, KBK, Code_Acc, summa_db, summa_kr, korr_acc, dnd, link, key_prov, tabsource)
select
coalesce(rd1.Str_Val,''),
substring(coalesce(rd2.Str_Val,''),1,3),
substring(coalesce(rd3.Str_Val,''),1,8),
substring(coalesce(rd4.Str_Val,''),1,2),
--right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+right('0000'+rtrim(coalesce(rd6.Str_Val,'')),4) + '0000000000',
right('000'+rtrim(coalesce(rd5.Str_Val,'')),3)+right('0000'+rtrim(coalesce(rd6.Str_Val,'')),4) +
case
when (  (@cSinth = '401' and @cAnalit = '10' and @cSGU = '151') or
(@cSinth = '401' and @cAnalit = '20' and @cSGU = '251') or
(@cSinth = '205' and @cAnalit = '51' and (@cSGU = '560' or @cSGU = '660')) or
/*(@cSinth = '206' and @cAnalit = '51' and (@cSGU = '560' or @cSGU = '660')) or*/
(@cSinth = '207' and @cAnalit = '31' and @cSGU = '540') or
(@cSinth = '207' and @cAnalit = '21' and @cSGU = '540') or
(@cSinth = '301' and @cAnalit in ('11','21','31', '13') and @cSGU in ('710','810')) or
(@cSinth = '302' and @cAnalit = '51' and @cSGU = '830'))
then right('0000000'+rtrim(coalesce(rd7.Str_Val,'')),7) + '000'
else '0000000000'
end,
case WHEN right(rtrim(@cAccount),8) in ('30406000')
THEN CASE WHEN isnull(rd9.Float_Val,0.00) <> 0
THEN LEFT(@cAccount,6) + '830'
ELSE LEFT(@cAccount,6) + '730' END 
ELSE @cAccount
END,
isnull(rd9.Float_Val,0.00),
isnull(rd10.Float_Val,0.00),
substring(coalesce(rd11.Str_Val,''),1,9),
case when cast(rtrim(isnull(rd12.Str_Val,'')) as varchar) not in (0,1) then NULL else cast(rtrim(isnull(rd12.Str_Val,'')) as varchar) end,
srows.Code_Row,
null,
@table
from (
select Code_Row from #report_dinamics
where link_sf = @LSF and right(rtrim(Code_Row),1) like '[0-9]' and link_col in (select link_col from dbo.report_coloumns where link_table = @iLink_Table)
group by Code_Row
) as srows
left join #report_dinamics as rd1 on rd1.link_sf = @LSF and rd1.Code_Row = srows.Code_Row and 1 = (select Orders from dbo.report_coloumns where link_col = rd1.link_col) and rd1.link_col = (select link_col from dbo.report_coloumns where Orders = 1 and Link_Table = @iLink_Table)
left join #report_dinamics as rd2 on rd2.link_sf = @LSF and rd2.Code_Row = srows.Code_Row and 2 = (select Orders from dbo.report_coloumns where link_col = rd2.link_col) and rd2.link_col = (select link_col from dbo.report_coloumns where Orders = 2 and Link_Table = @iLink_Table)
left join #report_dinamics as rd3 on rd3.link_sf = @LSF and rd3.Code_Row = srows.Code_Row and 3 = (select Orders from dbo.report_coloumns where link_col = rd3.link_col) and rd3.link_col = (select link_col from dbo.report_coloumns where Orders = 3 and Link_Table = @iLink_Table)
left join #report_dinamics as rd4 on rd4.link_sf = @LSF and rd4.Code_Row = srows.Code_Row and 4 = (select Orders from dbo.report_coloumns where link_col = rd4.link_col) and rd4.link_col = (select link_col from dbo.report_coloumns where Orders = 4 and Link_Table = @iLink_Table)
left join #report_dinamics as rd5 on rd5.link_sf = @LSF and rd5.Code_Row = srows.Code_Row and 5 = (select Orders from dbo.report_coloumns where link_col = rd5.link_col) and rd5.link_col = (select link_col from dbo.report_coloumns where Orders = 5 and Link_Table = @iLink_Table)
left join #report_dinamics as rd6 on rd6.link_sf = @LSF and rd6.Code_Row = srows.Code_Row and 6 = (select Orders from dbo.report_coloumns where link_col = rd6.link_col) and rd6.link_col = (select link_col from dbo.report_coloumns where Orders = 6 and Link_Table = @iLink_Table)
left join #report_dinamics as rd7 on rd7.link_sf = @LSF and rd7.Code_Row = srows.Code_Row and 7 = (select Orders from dbo.report_coloumns where link_col = rd7.link_col) and rd7.link_col = (select link_col from dbo.report_coloumns where Orders = 7 and Link_Table = @iLink_Table)
left join #report_dinamics as rd8 on rd8.link_sf = @LSF and rd8.Code_Row = srows.Code_Row and 8 = (select Orders from dbo.report_coloumns where link_col = rd8.link_col) and rd8.link_col = (select link_col from dbo.report_coloumns where Orders = 8 and Link_Table = @iLink_Table)
left join #report_dinamics as rd9 on rd9.link_sf = @LSF and rd9.Code_Row = srows.Code_Row and 9 = (select Orders from dbo.report_coloumns where link_col = rd9.link_col) and rd9.link_col = (select link_col from dbo.report_coloumns where Orders = 9 and Link_Table = @iLink_Table)
left join #report_dinamics as rd10 on rd10.link_sf = @LSF and rd10.Code_Row = srows.Code_Row and 10 = (select Orders from dbo.report_coloumns where link_col = rd10.link_col) and rd10.link_col = (select link_col from dbo.report_coloumns where Orders = 10 and Link_Table = @iLink_Table)
left join #report_dinamics as rd11 on rd11.link_sf = @LSF and rd11.Code_Row = srows.Code_Row and 11 = (select Orders from dbo.report_coloumns where link_col = rd11.link_col) and rd11.link_col = (select link_col from dbo.report_coloumns where Orders = 11
and Link_Table = @iLink_Table)
left join #report_dinamics as rd12 on rd12.link_sf = @LSF and rd12.Code_Row = srows.Code_Row and 12 = (select Orders from dbo.report_coloumns where link_col = rd12.link_col) and rd12.link_col = (select link_col from dbo.report_coloumns where Orders = 12
and Link_Table = @iLink_Table)
end
set @table = @table + 1
end
update @table2 set link = cast(nn as varchar(10)), key_prov = nn -- для уникальности записей собраных с трёх таблиц. Ибо пользователю доверять нельзя!

update @table2  -- устанавливаем признак Денежные/Неденежные рассчёты | неденежные считаем все с СГУ 310,320,330,340 и сотые корреспондирующие счета
set dnd = case
when dnd not in (1,0)
then
(case
when
right(left(korr_acc,6),5) in ('21002','30405') or
right(korr_acc,3) in ('510','610')
then 1 -- денежные рассчёты
else 0 -- не денежные рассчёты
end)
else dnd
end

select @j = count(*) from @table2

if (@j > 0)begin -- если кол-во полученных строк больше нуля, то...
-- формирование итоговых строчек для 304.04 счёта
--select * from @table2
-- 30404000 ####################################################################################################

if (@cSinth = '304' and (@cAnalit = '04' OR @cAnalit = '06') and @cSGU = '000') begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (KBK,Code_Acc,summa_db,summa_kr,link)
select KBK,Code_Acc,coalesce(SUM(summa_db),0),coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+'ИП' from @table2
group by KBK,Code_Acc
-- итоговые по неденежным
insert into @table2 (KBK,Code_Acc,summa_db,summa_kr,korr_acc,link)
select KBK,Code_Acc,coalesce(coalesce(SUM(summa_db),0),0),coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_db,summa_kr,link)
select coalesce(coalesce(SUM(summa_db),0),0),coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
insert into @table2 (KBK,Code_Acc,summa_db,summa_kr,korr_acc,link)
select KBK,Code_Acc,coalesce(coalesce(SUM(summa_db),0),0),coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_db,summa_kr,link)
select coalesce(SUM(summa_db),0),coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_db,summa_kr,link)
select coalesce(SUM(summa_db),0),coalesce(SUM(summa_kr),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 40120241 ####################################################################################################

-- формирование итоговых строчек для счёта 40120241
if (@cSinth = '401' and @cAnalit = '20' and @cSGU = '241'/*@cVidFormCode = 2*/)begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (ppp,KBK,Code_Acc,summa_db,link)
select ppp,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+'ИП' from @table2
group by ppp,KBK,Code_Acc
-- итоговые по неденежным
insert into @table2 (ppp,KBK,Code_Acc,summa_db,korr_acc,link)
--        select ppp,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
select ppp,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,KBK,Code_Acc,korr_acc

-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
insert into @table2 (ppp,KBK,Code_Acc,summa_db,korr_acc,link)
--        select ppp,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИД' from @table2
select ppp,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,KBK,Code_Acc,korr_acc

-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 40110180 ####################################################################################################

-- формирование итоговых строчек для счёта 40110180
if (@cSinth = '401' and @cAnalit = '10' and @cSGU = '180' /*and @cVidFormCode = 3*/)begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (ppp,KBK,Code_Acc,summa_kr,link)
select ppp,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+'ИП' from @table2
group by ppp,KBK,Code_Acc
-- итоговые по неденежным
insert into @table2 (ppp,KBK,Code_Acc,summa_kr,korr_acc,link)
--        select ppp,Numb_Acc,case when ABS(coalesce(SUM(summa_db),0)) > 0.0 then -coalesce(SUM(summa_db),0) else coalesce(SUM(summa_kr),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
select ppp,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
insert into @table2 (ppp,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,KBK,Code_Acc,korr_acc

-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 20731540 ####################################################################################################

-- формирование итоговых строчек для счётов 20702540
if (@cSinth = '207' and @cAnalit in ('11','21','31') and @cSGU = '540') begin
-- итоговые. в том числе по номеру (коду) счета
/* insert into @table2 (el_bud,okato,Code_Acc,summa_db,link)
select el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by el_bud,okato,Code_Acc*/
insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_db,link)
select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp, el_bud,okato,Code_Acc
-- итоговые по неденежным
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select ppp,el_bud,okato,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select ppp,el_bud,okato,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИД' from @table2
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 40120251 ####################################################################################################

if (@cSinth = '401' and @cAnalit = '20' and @cSGU = '251') begin
-- итоговые. в том числе по номеру (коду) счета
/* insert into @table2 (el_bud,okato,Code_Acc,summa_db,link)
select el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by el_bud,okato,Code_Acc*/
if @code_form like '425_' begin
insert into @table2 (/*ppp,*/el_bud,okato,Code_Acc,summa_db,link)
select /*ppp,*/el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by /*ppp, */el_bud,okato,Code_Acc
end
else begin
insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_db,link)
select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp,el_bud,okato,Code_Acc
end
-- итоговые по неденежным
--insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select ppp,el_bud,okato,left(KBK,6)+'00000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000'+right(KBK,3)+Code_Acc+korr_acc+'ИН' as link
from @table2
where dnd = 0 and tabsource = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select ppp,el_bud,okato,left(KBK,7)+'0000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000'+right(KBK,3)+Code_Acc+korr_acc+'ИН' as link from @table2
where dnd = 0 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0 and tabsource = 3
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select ppp,el_bud,okato,left(KBK,6)+'00000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000'+right(KBK,3)+Code_Acc+korr_acc+'ИД' as link
from @table2
where dnd = 1 and tabsource = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select ppp,el_bud,okato,left(KBK,7)+'0000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000'+right(KBK,3)+Code_Acc+korr_acc+'ИД' as link from @table2
where dnd = 1 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1 and tabsource = 3
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end


-- 20651560(660) ####################################################################################################

if (@cSinth = '206' and @cAnalit = '51' and (@cSGU = '560' or @cSGU = '660'))begin
-- итоговые. в том числе по номеру (коду) счета
if @code_form like '425_' begin
insert into @table2 (el_bud,okato,Code_Acc,summa_db,link)
select el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by el_bud,okato,Code_Acc
end
else BEGIN

insert into @table2 (ppp, el_bud,okato,Code_Acc,summa_db,link)
select ppp, el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp, el_bud,okato,Code_Acc

end
-- итоговые по неденежным
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select ppp,el_bud,okato,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,6)+'00000000000' as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
where dnd = 0 and tabsource = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select ppp,el_bud,okato,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0 and tabsource <> 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select ppp,el_bud,okato,left(KBK,7)+'0000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000'+right(KBK,3)+Code_Acc+korr_acc+'ИД' as link from @table2
where dnd = 1 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc
end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,6)+'00000000000' as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr) ,0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000000'+Code_Acc+korr_acc+'ИД' as link from @table2
where dnd = 1 and tabsource = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1 and tabsource <> 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 30212830 ####################################################################################################

if (@cSinth = '302' and @cAnalit = '51' and @cSGU = '830')begin
-- итоговые. в том числе по номеру (коду) счета
if @code_form like '425_' begin
insert into @table2 (el_bud,okato,Code_Acc,summa_db,link)
select el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by el_bud,okato,Code_Acc
end
else begin
insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_db,link)     select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp,el_bud,okato,Code_Acc
end
-- итоговые по неденежным
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
--        select ppp,el_bud,okato,Numb_Acc,case when ABS(coalesce(SUM(summa_kr),0)) > 0.0 then -coalesce(SUM(summa_kr),0) else coalesce(SUM(summa_db),0) end,korr_acc,cast(MAX(key_prov) as varchar(10))+Numb_Acc+korr_acc+'ИН' from @table2
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,SUM(Q.summa_db),Q.korr_acc,max(Q.link) from
(select ppp,el_bud,okato,left(KBK,7)+'0000000'+right(KBK,3) as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa_db,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000'+right(KBK,3)+Code_Acc+korr_acc+'ИД' as link from @table2
where dnd = 1 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1 and tabsource <> 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 20551000,20651000,20731000 ####################################################################################################

if (@code_form like '%125_' AND 
(@cSinth = '206' and @cAnalit = '51' and @cSGU = '000'))
BEGIN
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_db,link, kbk)
select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+'ИП', KBK 
from @table2
group by ppp,el_bud,okato,Code_Acc, KBK

-- общая итоговая строчка
if exists(select * from @table2 where right(link,2) = 'ИП') 
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where right(link,2) = 'ИП'

END

if (
(@cSinth = '205' and @cAnalit = '51' and @cSGU = '000' /*and @cVidFormCode = 9*/)-- or @cVidFormCode = 11)) or
or (@code_form like '425_' and @cSinth = '206' and @cAnalit = '51' and @cSGU = '000'/*and @cVidFormCode = 9*/)-- or @cVidFormCode = 5)) or
OR (@cSinth = '207' and @cAnalit = '31' and @cSGU = '000'/*and @cVidFormCode = 9*/)
or (@cSinth = '207' and @cAnalit = '21' and @cSGU = '000')
or (@cSinth = '207' and @cAnalit = '11' and @cSGU = '000'))begin-- or @cVidFormCode = 6 or @cVidFormCode = 13)))begin
-- итоговые. в том числе по номеру (коду) счета

insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_db,link)
select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' 
from @table2
group by ppp,el_bud,okato,Code_Acc


-- общая итоговая строчка
if exists(select * from @table2 where right(link,2) = 'ИП') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where right(link,2) = 'ИП'
end
end

-- 301X1000 ####################################################################################################
if (@cSinth = '301' and @cAnalit in ('21','31','41') and @cSGU = '000') or
(@cSinth = '302' and @cAnalit = '51' and @cSGU = '000' AND @code_form LIKE '%125%') begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp,el_bud,okato,KBK,Code_Acc
-- общая итоговая строчка
if exists(select * from @table2 where right(link,2) = 'ИП') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'Итого' from @table2
where right(link,2) = 'ИП'
end
end

if (@cSinth = '302' and @cAnalit in ('51') and @cSGU = '000') 
-- итоговые. в том числе по номеру (коду) счета
IF @code_form LIKE '%425%'
   insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_kr,link)
   select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
   group by ppp,el_bud,okato,Code_Acc


-- 301X1000 ####################################################################################################
if (@cSinth = '301' and @cAnalit in ('11','13') and @cSGU = '000') 
-- итоговые. в том числе по номеру (коду) счета
IF @code_form LIKE '%125%'
   insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,link)
   select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
   group by ppp,el_bud,okato,KBK,Code_Acc
ELSE
   insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_kr,link)
   select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
   group by ppp,el_bud,okato,Code_Acc

	   
-- общая итоговая строчка
if exists(select * from @table2 where right(link,2) = 'ИП') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'Итого' from @table2
where right(link,2) = 'ИП'
end
end


-- 40110151 ####################################################################################################
-- формирование итоговых строчек для счётов 40101151
if (@cSinth = '401' and @cAnalit = '10' and @cSGU = '151' /*and @cVidFormCode = 10*/) begin
--  -- сначала извращаемся над кбк в соответствии с письмом от 19.12.2008
--  update @table2
--  set KBK = case when tabsource = 1 then left(KBK,6)+'00000000000' else KBK end
-- итоговые. в том числе по номеру (коду) счета
if @code_form like '425_' begin
insert into @table2 (el_bud,okato,Code_Acc,summa_kr,link)
select el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by el_bud,okato,Code_Acc
end
else begin
insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_kr,link)
select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp,el_bud,okato,Code_Acc
end
-- итоговые по неденежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,6)+'00000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
where dnd = 0 and tabsource = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
where dnd = 0 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0 and tabsource = 3
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end

-- подитоговые для денежных
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,6)+'00000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000000'+Code_Acc+korr_acc+'ИД' as link from @table2
where dnd = 1 and tabsource = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИД' as link from @table2
where dnd = 1 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1 and tabsource = 3
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 20551560(660) ####################################################################################################

if (@cSinth = '205' and @cAnalit = '51' and (@cSGU = '560' or @cSGU = '660')) begin
-- итоговые. в том числе по номеру (коду) счета
if @code_form like '425_' begin
insert into @table2 (el_bud,okato,Code_Acc,summa_kr,link)
select el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by el_bud,okato,Code_Acc
end
else begin
insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_kr,link)
select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp,el_bud,okato,Code_Acc
end
-- итоговые по неденежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,6)+'00000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,6)+'00000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
where dnd = 0 and tabsource = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc
end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0 and tabsource = 1     group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
where dnd = 0 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0 and tabsource = 3
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc


-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 20731640,20711640 ####################################################################################################

-- формирование итоговых строчек для счётов 20702640
if ((@cSinth = '207' and @cAnalit = '31' and @cSGU = '640') or
(@cSinth = '207' and @cAnalit = '11' and @cSGU = '640'))begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (ppp,el_bud,okato,Code_Acc,summa_kr,link)
select ppp,el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by ppp,el_bud,okato,Code_Acc
-- итоговые по неденежным
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end


-- 30111810 ####################################################################################################
-- формирование итоговых строчек для счётов 30101710
if (@cSinth = '301' and @cAnalit in ('11','21','31','13') and @cSGU in ('810')) begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (el_bud,okato,Code_Acc,summa_db,link)
select el_bud,okato,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by el_bud,okato,Code_Acc
-- итоговые по неденежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
where dnd = 0 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0 and tabsource <> 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИД' as link from @table2
where dnd = 1 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1 and tabsource <> 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_db,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 30111710 ####################################################################################################
-- формирование итоговых строчек для счётов 30101710
if (@cSinth = '301' and @cAnalit in ('11','21','31','13') and @cSGU in ('710')) begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (el_bud,okato,Code_Acc,summa_kr,link)
select el_bud,okato,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+'ИП' from @table2
group by el_bud,okato,Code_Acc
-- итоговые по неденежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИН' as link from @table2
where dnd = 0 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0 and tabsource <> 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
if @code_form like '425_' begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,sum(Q.summa),Q.korr_acc,max(Q.link)
from
(select ppp,el_bud,okato,left(KBK,7)+'0000000000' as KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0) as summa,korr_acc,cast(MAX(key_prov) as varchar(10))+left(KBK,7)+'0000000000'+Code_Acc+korr_acc+'ИД' as link from @table2
where dnd = 1 and tabsource = 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc) as Q
group by Q.ppp,Q.el_bud,Q.okato,Q.KBK,Q.Code_Acc,Q.korr_acc

insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1 and tabsource <> 2
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc

end
else begin
insert into @table2 (ppp,el_bud,okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select ppp,el_bud,okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by ppp,el_bud,okato,KBK,Code_Acc,korr_acc
end
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- формирование итоговых строчек для счётов 021100560, 021200560
if ((@cSinth = '211' or @cSinth = '212') and @cAnalit = '00' and (@cSGU = '560' or @cSGU = '660') /*and @cVidFormCode = 15*/)begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (okato,Code_Acc,summa_db,link)
select okato, Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),cast(MAX(key_prov) as varchar(10))+coalesce(okato,'')+'ИП' from @table2
group by okato, Code_Acc
-- итоговые по неденежным
insert into @table2 (okato,KBK,Code_Acc,summa_db,korr_acc,link)
select okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
insert into @table2 (okato,KBK,Code_Acc,summa_db,korr_acc,link)
select okato,KBK,Code_Acc,coalesce(SUM(summa_db),0)-coalesce(SUM(summa_kr),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_db,link)
select coalesce(SUM(summa_db),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

-- 30800730,30900730,30800830,30900830 ####################################################################################################
-- формирование итоговых строчек для счётов 030800730 и 030900730
if ((@cSinth = '308' or @cSinth = '309') and @cAnalit = '00' and (@cSGU = '730' or @cSGU = '830') /*and @cVidFormCode = 16*/)begin
-- итоговые. в том числе по номеру (коду) счета
insert into @table2 (okato,Code_Acc,summa_kr,link)
select okato, Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),cast(MAX(key_prov) as varchar(10))+coalesce(okato,'')+'ИП' from @table2
group by okato, Code_Acc
-- итоговые по неденежным
insert into @table2 (okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИН' from @table2
where dnd = 0
group by okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым неденежным
if exists(select * from @table2 where right(link,2) = 'ИН') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_неденежные_рассчёты' from @table2
where right(link,2) = 'ИН'
end
-- итоговые по денежным
insert into @table2 (okato,KBK,Code_Acc,summa_kr,korr_acc,link)
select okato,KBK,Code_Acc,coalesce(SUM(summa_kr),0)-coalesce(SUM(summa_db),0),korr_acc,cast(MAX(key_prov) as varchar(10))+KBK+Code_Acc+korr_acc+'ИД' from @table2
where dnd = 1
group by okato,KBK,Code_Acc,korr_acc
-- итоговая строчка суммы по итоговым денежным
if exists(select * from @table2 where right(link,2) = 'ИД') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'итог_денежные_рассчёты' from @table2
where right(link,2) = 'ИД'
end
-- общая итоговая строчка
if exists(select * from @table2 where left(link,5) = 'итог_') begin
insert into @table2 (summa_kr,link)
select coalesce(SUM(summa_kr),0),'Итого' from @table2
where left(link,5) = 'итог_'
end
end

delete from @table2 where right(link,1) like '[0-9]'
----------------------------------------- Делаем кодовое значение более коротким (на базе nn)
select @j = MIN(nn) from @table2

update @table2
set link = rtrim(cast((nn - @j) as varchar)) + right(link,2)
where right(link,2) in ('ИД','ИН')
-----------------------------------------
if not exists(select * from @table2 where right(link,2) = 'ИД')
insert into @table2 (link) values ('ИД')

if not exists(select * from @table2 where right(link,2) = 'ИН')
insert into @table2 (link) values ('ИН')

if not exists(select * from @table2 where rtrim(link) = 'итог_денежные_рассчёты')
insert into @table2 (link) values ('итог_денежные_рассчёты')

if not exists(select * from @table2 where rtrim(link) = 'итог_неденежные_рассчёты')
insert into @table2 (link) values ('итог_неденежные_рассчёты')

select @j = MIN(nn) from @table2
select @jj = MAX(nn) from @table2

delete from dbo.report_dinamics where Link_SF = @LSF and Link_Col in (select link_col from dbo.report_coloumns where link_table = (select link_table from dbo.report_tables where link_form = (select top 1 link_form from dbo.report_saved_forms where link_saved_form = @LSF) and Orders = 4)) -- удаление всех строк из таблицы Итоги
delete from #report_dinamics where Link_SF = @LSF and Link_Col in (select link_col from dbo.report_coloumns where link_table = (select link_table from dbo.report_tables where link_form = (select top 1 link_form from dbo.report_saved_forms where link_saved_form = @LSF) and Orders = 4)) -- удаление всех строк из таблицы Итоги

while @j <= @jj begin
set @i = 1
while @i < 9 begin
select @iLink_col = link_col from dbo.report_coloumns where Orders = @i and Link_Table = (select link_table from dbo.report_tables where Orders = 4/*итоги*/ and link_form = (select link_form from dbo.report_saved_forms where link_saved_form = @LSF))
select
@code_row = rtrim(link),
@float_val =
(case when @i in (1,2,3,4,5,8) then 0.0000
when @i = 6 then coalesce(summa_db,0.0000)
when @i = 7 then coalesce(summa_kr,0.0000)
end),
@str_val =
(case when @i in (6,7) then ''
when @i = 1 then cast(coalesce(Name_bp,'') as varchar (250))
when @i = 2 then cast(coalesce(ppp,'') as varchar (250))
when @i = 3 then cast(coalesce(okato,'') as varchar (250))
when @i = 4 then cast(coalesce(el_bud,'') as varchar (250))
when @i = 5 then cast(coalesce(KBK,'')+coalesce(Code_acc,'') as varchar (250))
when @i = 8 then cast(coalesce(korr_acc,'') as varchar (250))
end)
from @table2
where nn = @j


if @code_row in ('ИД','ИН','итог_денежные_рассчёты','итог_неденежные_рассчёты') and @float_val = 0.0
insert into dbo.report_dinamics (link_sf,link_col,Code_row,float_val,str_val) values (@LSF,@iLink_col,@code_row,@float_val,@str_val)

insert into #report_dinamics (link_sf,link_col,Code_row,float_val,str_val)
values (@LSF,@iLink_col,@code_row,@float_val,@str_val)


set @i = @i + 1
end
set @j = @j + 1
end
----------------------------------------------------------------------------
select 0




GO


GRANT EXECUTE ON dbo.[RT_CALC_0503125M_ITOG_2011] TO PUBLIC

GO


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


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

GO
CREATE PROCEDURE dbo.BK_SAVE_DOC_MX3_INV_TABLE
	@intLINK_ROW	INT = NULL OUTPUT,
	@LINK_UP	INT,
	@ORDERS	INT,

	@INV_TYPE VARCHAR(30),
	@INV 	INT, 

	@QTY NUMERIC (28, 4) = 0, 
	@PRICE NUMERIC (28, 4) = 0, 
	@SUMMA NUMERIC (28, 4) = 0,
	
	@COMMENT	VARCHAR (254) = '',
	@INV_CHAR	VARCHAR (254) = ''
AS
BEGIN
	DECLARE
		@ERROR	tinyint,
		@trancount	int,
		@intOBJ_LINK	INT

	SET @trancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON

	EXECUTE @ERROR = dbo.X_UPDATE_OUT_TABLE_ROW_C
		@intLINK_ROW OUTPUT,
		@LINK_UP,
		'DOC_MX3_INV_TABLE',
		@ORDERS
		
	IF @ERROR <> 0
		RETURN @ERROR

	-- МЦ --
	EXECUTE @ERROR = dbo.BK_UPDATE_OUT_TABLE_INV_TYPE
		@intLINK_ROW,
		@INV_TYPE,
		@INV
		
	IF @ERROR <> 0
		RETURN @ERROR

	-- Суммы --
	EXECUTE @ERROR = dbo.BK_UPDATE_OUT_TABLE_MZ_CHARGE
		@intLINK_UP	=	@intLINK_ROW,
		@intACCOUNT	=	NULL,
		@intNOMEN	=	NULL,
		@nQTY_REST	=	0,
		@nQTY	=	@QTY,
		@nSUMMA	=	@SUMMA,
		@nPRICE	=	@PRICE,
		@nPRICE_FACT	=	0,
		@nSUM_REST	= 0

	IF @ERROR <> 0
		RETURN @ERROR

	--- Примечание ---
	SET @intOBJ_LINK = dbo.GetObjLink ('DOC_MX3_INV_T_COMMENT')
	EXECUTE @ERROR = dbo.X_UPDATE_OUT_TABLE_STRING
		@intLINK_ROW,
		@intOBJ_LINK,
		@COMMENT
		
	IF @ERROR <> 0
		RETURN @ERROR

	--- Характеристика ---
	SET @intOBJ_LINK = dbo.GetObjLink ('DOC_MX3_INV_T_INV_CHAR')
	EXECUTE @ERROR = dbo.X_UPDATE_OUT_TABLE_STRING
		@intLINK_ROW,
		@intOBJ_LINK,
		@INV_CHAR
		
	IF @ERROR <> 0
		RETURN @ERROR

	IF @@TRANCOUNT > @trancount
		COMMIT TRAN

	RETURN 0
END

GO

GRANT EXECUTE ON dbo.[BK_SAVE_DOC_MX3_INV_TABLE] 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].[events_rms_set_processed]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[events_rms_set_processed]
GO

/*
Назначение: Пометка о обработке событий категории "Сервис обмена"
Входные параметры:
  @nLink int = null, -- link события в таблице RMS_MESSAGES

*/

CREATE PROCEDURE [dbo].[events_rms_set_processed]
  @nLink int = null

AS
  SET NOCOUNT ON
 
  update e 
    set processed = 1
  from dbo.sys_events_rms e 
  where link_msg = @nLink and @nLink is not null

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


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

GO

/* --- НАКОПИТЕЛЬНАЯ ВЕДОМОСТЬ ПО ПРИХОДУ ПРОДУКТОВ ПИТАНИЯ --- */
CREATE PROCEDURE dbo.PK_REPORT_ACCEPT_FEEDING
	@dDATE_WORK	DATETIME,
	@dDATE_WORK_END	DATETIME = NULL,
	@intLINK_MOL	INT,
	@cVal_KBK CHAR (1), @nOtborLinkKBK INT	/* Отбор по ВКР */,
	@cVal_Dep CHAR (1), @nOtborLinkDEP INT	/* Отбор учреждений */,
	@cVal_DOP char(1), @nOtborLinkDOP int	/* Отбор по доп. классификации */

AS
BEGIN
	DECLARE @dDATE_BEGIN	DATETIME,
		@cMONTH_NAME	VARCHAR (20),
		@cDEP_NAME	VARCHAR (254),
		@cDEP_OKPO	VARCHAR (20),
		@intDEP_LINK	INT,
		@TAB_SUPPLER	VARCHAR (100),
		@TAB_INVENTORY	VARCHAR (100),
		@strEXEC	VARCHAR (4000),
		@intCOUNTER		INT,
		@cCOUNTER		VARCHAR (10),
		@intMAX_REC		INT,
		@intCOUNT_COLROW	INT

	SET @dDATE_BEGIN = dbo.DateBeginOfMonth (@dDATE_WORK)
	SELECT @cMONTH_NAME = MON FROM MONTHS WHERE NUM = MONTH (@dDATE_WORK)

	IF @dDATE_WORK_END IS NOT NULL
	BEGIN
		SET @dDATE_BEGIN = @dDATE_WORK
		SET @dDATE_WORK = @dDATE_WORK_END
	END

	SELECT @intDEP_LINK = LINK,
		@cDEP_NAME = [NAME],
		@cDEP_OKPO = OKPO 
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = COALESCE (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())

	--- ОТБОР ПО КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	--- ОТБОР ОРГАНИЗАЦИЙ ---
	DECLARE @TAB_DEP TABLE (LINK_DEP INT, DEP_CODE  VARCHAR(20), DEP_NAME VARCHAR(254) )
	IF LEN(@cVal_Dep)>0 BEGIN
		INSERT INTO @TAB_DEP
		SELECT OVR.RECORD, D.CODE, D.[NAME]
		FROM dbo.OBJECT_VAR_DEPARTMENT OVR, dbo.DICTIONARY_DEPARTMENT D
		WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP = @nOtborLinkDEP
	END
	ELSE
	BEGIN
		INSERT INTO @TAB_DEP
		SELECT LINK_AP, AP_CODE, AP_NAME
		FROM dbo.BK_GetTableDictionByAP ('DEP')
	END
	
	--- ОТБОР ПО доп классификации --- 
	DECLARE @TAB_DOP TABLE (LINK_DOP INT, DOP_CODE VARCHAR (20))
	IF LEN (@cVal_DOP) > 0
		INSERT INTO @TAB_DOP
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.DOP_CLASSIF AP 
		INNER JOIN dbo.OBJECT_VAR_DOP_CLASSIF OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkDOP
	ELSE
		INSERT INTO @TAB_DOP
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('AP2')



	/* --- ПРОВОДКИ ДЕБЕТОВЫЕ --- */
	CREATE TABLE #TABLE_PROV (DOC_PROV DATETIME, MDAY TINYINT, NDOC VARCHAR (30),
		EMP INT, NOMEN INT, K_DEP INT, 
		QTY NUMERIC (28,4), SS NUMERIC (28,4))

	INSERT INTO #TABLE_PROV
	SELECT GP.DATE_PROV,
		DAY (GP.DATE_PROV),
		GP.NUMBER,
		GP.DT_EMP,
		GP.DT_NOMEN,
		GP.KT_DEP,
		GP.QUANTITY,
		GP.SUMMA
	FROM dbo.AProvByBufferConditionsShort (@dDATE_BEGIN, @dDATE_WORK, DEFAULT, DEFAULT) GP
	INNER JOIN dbo.BK_GetAcctTableByCode ('105', '02, 12, 22, 32, 42', DEFAULT, DEFAULT) AC
				ON (AC.LINK = GP.DT_ACCOUNT)
	INNER JOIN dbo.S_ACCOUNTS SA_K ON (SA_K.LINK = KT_ACCOUNT
			AND SA_K.cSINTH IN ('106', '107', '302', '208', '401'))
	INNER JOIN @TAB_KBK T1 ON (T1.LINK_KBK = GP.DT_VKR)
	INNER JOIN @TAB_DEP T2 ON (T2.LINK_DEP = GP.KT_DEP)
	INNER JOIN @TAB_DOP T3 ON (T3.LINK_DOP = GP.DT_AP2)
	WHERE GP.DT_EMP = @intLINK_MOL
		AND GP.DEP_LINK = @intDEP_LINK

	EXEC X_GET_TABLE_NAME @TAB_SUPPLER OUTPUT
	EXEC X_GET_TABLE_NAME @TAB_INVENTORY OUTPUT

	/* --- Поставщики --- */
	EXEC M_CROSS_TABLE 'K_DEP', 'MDAY, NDOC',
				'INT#VARCHAR (30)',
				'SS',
				'NUMERIC (28,4)',
				'SUM (SS) AS SS',
				'#TABLE_PROV',
				@TAB_SUPPLER

	/* --- Продукты --- */
	EXEC M_CROSS_TABLE 'NOMEN', 'MDAY, NDOC',
				'INT#VARCHAR (30)',
				'QTY, SS',
				'NUMERIC (28,4)#NUMERIC (28,4)',
				'SUM (QTY) AS QTY, SUM (SS) AS SS',
				'#TABLE_PROV',
				@TAB_INVENTORY

	/* --- Готовим для вывода --- */
	SET @intMAX_REC = 11
	SELECT @intCOUNTER = COUNT (*) FROM (SELECT MDAY, NDOC
						FROM #TABLE_PROV
						GROUP BY MDAY, NDOC) S1
	SET @intCOUNTER = ISNULL (@intCOUNTER, 0)
	SET @intCOUNT_COLROW = @intCOUNTER
	WHILE @intCOUNTER < @intMAX_REC
	BEGIN
		SET @intCOUNTER = @intCOUNTER + 1
		SET @cCOUNTER = LTRIM (STR (@intCOUNTER))
	
 		SET @strEXEC = 'ALTER TABLE ' + @TAB_SUPPLER		
			+ ' ADD MDAY_' + @cCOUNTER + ' INT '
			+ ', NDOC_' + @cCOUNTER + '_' + @cCOUNTER + ' [VARCHAR] (30)'
			+ ', SS_' + @cCOUNTER + '_' + @cCOUNTER + ' [NUMERIC] (28,4)'
		EXECUTE (@strEXEC)

 		SET @strEXEC = 'ALTER TABLE ' + @TAB_INVENTORY		
			+ ' ADD MDAY_' + @cCOUNTER + ' INT '
			+ ', NDOC_' + @cCOUNTER + '_' + @cCOUNTER + ' [VARCHAR] (30)'
			+ ', QTY_' + @cCOUNTER + '_' + @cCOUNTER + ' [NUMERIC] (28,4)'
			+ ', SS_' + @cCOUNTER + '_' + @cCOUNTER + ' [NUMERIC] (28,4)'
		EXECUTE (@strEXEC)
	END 

	SET @strEXEC = 'ALTER TABLE ' + @TAB_SUPPLER + ' ADD S_TOTAL NUMERIC (28,4)'
	EXEC (@strEXEC)

	SET @strEXEC = 'UPDATE ' + @TAB_SUPPLER
		+ ' SET S_TOTAL = ISNULL ((SELECT SUM (T2.SS) FROM #TABLE_PROV T2 GROUP BY T2.K_DEP HAVING T2.K_DEP = T1.K_DEP), 0)' 
		+ ' FROM ' + @TAB_SUPPLER + ' T1 '
	EXEC (@strEXEC)

	/* --- Вывод данных --- */
	SET @strEXEC = 'SELECT ISNULL (T2.CODE, '''') AS K_DEP_CD, ISNULL (T2.NAME, '''') AS K_DEP_NM, T1.* FROM '
		+ @TAB_SUPPLER + ' T1 LEFT OUTER JOIN DICTIONARY_DEPARTMENT T2 '
		+ ' ON (T2.LINK = T1.K_DEP)'
	exec (@strEXEC)

	SET @strEXEC = 'SELECT ISNULL (T2.CODE, '''') AS INV_CODE, ISNULL (T2.NAME, '''') AS INV_NAME, '
		+ 'ISNULL (T2.NAME_UM, '''') AS UM_NAME, T1.* FROM ' + @TAB_INVENTORY
		+ ' T1 LEFT OUTER JOIN BV_NOMENCLATURE T2 '
		+ ' ON (T2.LINK = T1.NOMEN)'
	exec (@strEXEC)

	/* --- Шапка документа --- */
	SELECT ISNULL (@cDEP_NAME, '') AS DEP_NAME,
		ISNULL (@cDEP_OKPO, '') AS DEP_OKPO,
		ISNULL (@cMONTH_NAME, '') AS MONTH_NAME,
		ISNULL (YEAR (@dDATE_WORK), 0) AS DYEAR,
		ISNULL (dbo.SD_GetEmplName (@intLINK_MOL), '') AS EMP_NAME,
		ISNULL ((SELECT POST_NAME FROM KU_EMPL_PLACING WHERE LINK = @intLINK_MOL), '') AS EMP_POST

	EXEC ('DROP TABLE ' + @TAB_SUPPLER)
	EXEC ('DROP TABLE ' + @TAB_INVENTORY)
END



GO


GRANT EXECUTE ON dbo.[PK_REPORT_ACCEPT_FEEDING] 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(30)

DECLARE @varKStrancount int, @varKSERROR as INT

DECLARE @CODE_OBJECT VARCHAR(254), @LINK_EKR_DEFAULT int

DECLARE @Cur CURSOR, @SRC VARCHAR(30), @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(30), @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
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

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

/*
Назначение: Отсылка сообщения RMS сервису

Входные параметры: 
		@msgLink int - линк сообщения
		@lcReport int - отображать результат (1) или нет (отлично от 1)

Пример вызова: 	
		exec dbo.rms_sendmessage(23)

возвращает:
	Возвращает выборку данных в виде

---------------------------------------------
|result int   |response varchar(8000)       |
---------------------------------------------
|1 или 0      |Ошибка или ответ RMS сервиса |
---------------------------------------------

	result = 0, успешная отправка и прием сообщения от сервиса (НЕ ОЗНАЧАЕТ ЧТО ОТВЕТ ОТ СЕРВИСА ПОЛОЖИТЕЛЬНЫЙ! ОТВЕТ СЕРВИСА СМОТРЕТЬ В ПОЛЕ response.)
	result = 1, ошибка отправки сообщения сервису. В поле response будет текст ошибки.
	
	
Автор: Рогожин И.Н.
*/

create procedure [dbo].[RMS_SENDMESSAGE]
	@msgLink int
	,@lcReport int = 1
as
begin
	declare @virtAddress varchar(255), @servAddress varchar(255), @response varchar(8000), @ret int, @bitOnLine bit, @bitOpened bit
	set @ret = 0
	if object_id('rms_CONTACTS') is not null
	begin
		if object_id('rms_CONTACT_PROPERTIES') is not null
		begin
			select @virtAddress = c.address from rms_CONTACTS c where c.myself = 1
			select @servAddress = cp.value from rms_CONTACT_PROPERTIES cp where cp.name = 'SERVICE.LOCAL_URL' and cp.contact_link = (select c.link from rms_CONTACTS c where c.service = 1)
			if not (@virtAddress is null or @virtAddress = '')
			begin
				if not (@servAddress is null or @servAddress = '')
				begin
					--select @bitOnLine = c.on_line from rms_CONTACTS c where c.myself = 1
					--if ISNULL(@bitOnLine,0)=1
					--begin
					--	select @bitOpened = c.opened from rms_CONTACTS c where c.myself = 1
					--	if ISNULL(@bitOpened,0)=1
					--	begin
							exec @ret = master..xp_rms_sendmessage @servAddress, @virtAddress, @msgLink, @response output
					--	end	else
					--	begin
					--		set @response = 'Необходимо открыть (Open) канал '''+@virtAddress+'''. Обратитесь к системному администратору для настройки сервисной шины обмена сообщениями.'
					--		set @ret = 1
					--	end
					--end	else
					--begin
					--	set @response = 'Необходимо запустить (Run) канал '''+@virtAddress+'''. Обратитесь к системному администратору для настройки сервисной шины обмена сообщениями.'
					--	set @ret = 1
					--end
				end else
				begin
					set @response = 'Невозможно найти адрес сервера! Проверьте таблицу rms_CONTACT_PROPERTIES.'
					set @ret = 1
				end
			end else
			begin
				set @response = 'Невозможно определить адрес клиента! Проверьте таблицу rms_CONTACTS.'
				set @ret = 1
			end
		end else
		begin
			set @response = 'Таблица rms_CONTACT_PROPERTIES не существует!'
			set @ret = 1
		end
	end else
	begin
		set @response = 'Таблица rms_CONTACTS не существует!'
		set @ret = 1
	end
	if ISNULL(@lcReport,1) = 1
		select @ret as result, @response as response
	else
	begin
		if @ret<>0
		begin
			raiserror(@response,16,1)
		end
	end
end

GO



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

GO


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

CREATE PROCEDURE [dbo].BK_REPORT_SV_EMPL_Z
	@varKSdDate1	DATETIME	,
	@varKScVal1 char(1), @varKSnOtborLink1 int	,
	@varKScVal2 char(1), @varKSnOtborLink2 int	,
	@cVal_KBK char(1), @nOtborLinkKBK int,	-- Отбор КБК --
	@varKSnPRN_KBK INT				,
	@varKSnPRN_SGU INT				,
	@intREPORT_EMPL INT,
        @intSVOD_ZB     int     -- Сводный отчет (ЦБ) --				
AS
BEGIN
	DECLARE	@varKSDIC_EMP	INT,
		@varKSDEP_LINK	INT,
		@varKSORGNAME	VARCHAR(254),
		@dDATE_REST	DATETIME	

	/* -- Параметры организации -- */
	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)
	SET @varKSDEP_LINK = dbo.BK_GetDepZB ()

	IF @intSVOD_ZB = 1 OR @varKSDEP_LINK IS NULL
		SET @varKSDEP_LINK = dbo.GetOwnDepLink()

	SELECT @varKSDEP_LINK = LINK,
		@varKSORGNAME = [NAME]
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @varKSDEP_LINK

	IF @intSVOD_ZB = 1
		SET @varKSORGNAME = RTRIM (@varKSORGNAME) + ' (ЦБ)'

	DECLARE @ACCT TABLE (LINK_ACCT [INT])
	IF LEN (@varKScVal1) > 0
		INSERT INTO @ACCT
		SELECT RECORD
		FROM OBJECT_VAR_ACCT
		WHERE LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO @ACCT
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode (DEFAULT, DEFAULT, DEFAULT, 1) ACCT

	DECLARE @EMP TABLE (LINK_EMP [INT], EMP_CODE  [VARCHAR] (20), EMP_NAME [VARCHAR] (254) )
	IF LEN(@varKScVal2)>0 BEGIN
		INSERT INTO @EMP
			SELECT OVR.RECORD, D.TAB, D.[NAME_EMPL]
			FROM OBJECT_VAR_EMPL OVR, KU_EMPL_PLACING D
			WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@varKSnOtborLink2
	END
	ELSE
	BEGIN
		INSERT INTO @EMP
			SELECT D.LINK, D.TAB, D.[NAME_EMPL] FROM KU_EMPL_PLACING D
		INSERT INTO @EMP VALUES (0, '', 'Не указан')
	END

		--- ОТБОР КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	SET @dDATE_REST = DATEADD (DAY, 1, @varKSdDate1)

	DECLARE @TABLE1 TABLE (DEP [INT], ACCOUNT [INT], INV [INT], NOMEN [INT], TMC [INT], EMP [INT],
			KBK [INT], KOSGU [INT],
			SUMMA [NUMERIC] (20,2), QTY [NUMERIC] (20,2))  

	INSERT INTO @TABLE1
	SELECT ISNULL (T1.DEP, 0),
		T1.ACCOUNT,
		ISNULL (T1.INV, 0),
		ISNULL (T1.NOMEN, 0),
		ISNULL (T1.TMC, 0),
		CASE
			WHEN @intREPORT_EMPL = 1 THEN ISNULL (T1.EMP, 0)
			ELSE 0
		END,
		CASE
			WHEN @varKSnPRN_KBK = 1 THEN ISNULL (T1.KBK, 0)
			ELSE 0
		END,
		CASE
			WHEN @varKSnPRN_SGU = 1 THEN ISNULL (T1.SGU, 0)
			ELSE 0
		END,
		SUM (T1.D_SUMMA), SUM (T1.D_QuantiTY)
	FROM dbo.ARestTableByDate (@dDATE_REST, DEFAULT) T1
	INNER JOIN @ACCT AC ON (AC.LINK_ACCT = T1.ACCOUNT)
	INNER JOIN @TAB_KBK T2 ON (T2.LINK_KBK = ISNULL (T1.KBK, 0))
--	WHERE T1.DEP_LINK = @varKSDEP_LINK
	WHERE (@intSVOD_ZB = 1
			AND T1.DEP_LINK IN (SELECT LINK FROM dbo.DEPARTMENTS WHERE ZB = 1 OR [TYPE] = 4))
		OR (@intSVOD_ZB = 0 AND T1.DEP_LINK = @varKSDEP_LINK)
	GROUP BY  ISNULL (T1.DEP, 0),
		T1.ACCOUNT,
		ISNULL (T1.INV, 0),
		ISNULL (T1.NOMEN, 0),
		ISNULL (T1.TMC, 0),
		CASE
			WHEN @intREPORT_EMPL = 1 THEN ISNULL (T1.EMP, 0)
			ELSE 0
		END,
		CASE
			WHEN @varKSnPRN_KBK = 1 THEN ISNULL (T1.KBK, 0)
			ELSE 0
		END,
		CASE
			WHEN @varKSnPRN_SGU = 1 THEN ISNULL (T1.SGU, 0)
			ELSE 0
		END

	DECLARE @RESULT TABLE (DEP [INT], ACCOUNT [INT], INV [INT], EMP [INT],
			DEP_CODE [VARCHAR] (20), DEP_NAME [VARCHAR] (254),
			ACCT_GR [VARCHAR] (20), ACCT_CODE [VARCHAR] (60), 
			INV_CODE [VARCHAR] (20), INV_NAME [VARCHAR] (254),
			UM_CODE [VARCHAR] (20), UM_NAME [VARCHAR] (254),
			PRICE [NUMERIC] (20,3),		
			EMP_CODE [VARCHAR] (20), EMP_NAME [VARCHAR] (254),
			SUMMA [NUMERIC] (20,2), QTY [NUMERIC] (20,2),
			PLACE_CODE VARCHAR (10), PLACE_NAME VARCHAR (254), 
			ORGNAME [VARCHAR] (254),
			REP_NAME [VARCHAR] (254),
			SORT1 VARCHAR (30),
			PRN_PLACE INT)

	INSERT INTO @RESULT
	SELECT 
--		T1.DEP,
		0,
		T1.ACCOUNT,
		T1.INV,
		T1.EMP,
--		DEP.DEP_CODE,
--		DEP.DEP_NAME,
		'', '',
		SA.CODE,
		dbo.BK_GetAcctFullCode1 (T1.ACCOUNT, T1.KBK, T1.KOSGU, @varKSnPRN_KBK, @varKSnPRN_SGU),
		ISNULL (INV.CODE, ISNULL (NOMEN.CODE, ISNULL (TMC.CODE, ''))),	
		ISNULL (INV.[NAME], ISNULL (NOMEN.[NAME], ISNULL (TMC.[NAME], ''))),	
		'',	
		ISNULL (INV.[NAME_UM], ISNULL (NOMEN.[NAME_UM], ISNULL (TMC.[REF_NAME_D], ''))),
		ISNULL (INV.BALANCE, 0),
		EMP.EMP_CODE,
		EMP.EMP_NAME,
		T1.SUMMA, T1.QTY,
		'', '',
		@varKSORGNAME,
		'МАТЕРИАЛЬНЫХ ЦЕННОСТЕЙ НА ЗАБАЛАНСОВЫХ СЧЕТАХ',
		'',
		0
	FROM @TABLE1 T1
	INNER JOIN @EMP EMP ON (EMP.LINK_EMP = T1.EMP)
--	INNER JOIN @DEP DEP ON (DEP.DEP = T1.DEP)
	INNER JOIN S_ACCOUNTS SA ON (SA.LINK = T1.ACCOUNT)
	LEFT OUTER JOIN dbo.INVENTORY_CARD INV ON (INV.LINK = T1.INV)
	LEFT OUTER JOIN dbo.BV_NOMENCLATURE NOMEN ON (NOMEN.LINK = T1.NOMEN)
	LEFT OUTER JOIN dbo.DICTIONARY_TMC TMC ON (TMC.LINK = T1.TMC)
	WHERE (T1.SUMMA <> 0) OR (T1.QTY <> 0)

	UPDATE @RESULT SET PRICE = SUMMA / QTY
	WHERE PRICE = 0 AND QTY <> 0

	SELECT * FROM @RESULT
	ORDER BY DEP_CODE, EMP_CODE, ACCT_GR, ACCT_CODE,
		RIGHT ('00000000000000000000' + INV_CODE, 20)
END



GO


GRANT EXECUTE ON dbo.[BK_REPORT_SV_EMPL_Z] 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 '20160101', '20160131', 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') LIKE '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(4)', 
			'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
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[KU_ORDER_CONFIRM]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KU_ORDER_CONFIRM]

GO

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

CREATE   PROCEDURE [dbo].KU_ORDER_CONFIRM
	@LINK int,
	@Status int = 1
AS
	DECLARE @trancount int, @SQLError int, @RowCount int, @txt varchar(254), @event varchar(254), @otype int, @MSG VARCHAR(254)
	SET @trancount = @@TRANCOUNT
	SET IMPLICIT_TRANSACTIONS ON
	BEGIN TRAN
	COMMIT TRAN

	SET @txt = case when @Status=1 then 'Утверждение' else 'Отмена' end + ' приказа'
	SELECT 
		@event = '№ '+rtrim(number)+' от '+convert(varchar(10), [date], 104)+' '''+rtrim(comment)+'''', @otype = type,
		@MSG = LEFT(@txt + ' ' + '№ '+rtrim(number)+' от '+convert(varchar(10), [date], 104)+' '''+rtrim(ot.name)+'''', 254)
		FROM orders O INNER JOIN dbo.ORDER_TYPES ot ON O.[TYPE] = ot.CODE WHERE link=@LINK

IF @otype NOT IN (1, 101) BEGIN
	IF @Status<>1 and exists(SELECT * FROM vacation WHERE order_link=@LINK and flag_jc=1)
	BEGIN
		ROLLBACK
		RETURN 106
	END

	IF @Status<>1 and exists(SELECT * FROM travel WHERE order_link=@LINK and flag_jc=1 )
	BEGIN
		ROLLBACK
		RETURN 106
	END

	IF @Status<>1 and exists(SELECT * from dbo.DIS_FACE_1 WHERE order_link = @LINK AND flag_jc = 1)
	BEGIN
		ROLLBACK
		RETURN 106
	END	
END

	IF @otype in (3, 103) AND @Status = 1 BEGIN
		SELECT	LINK, EMPL_LINK, DIS_DATE
		INTO	#TEMP_DIS
		FROM	ITEM_DIS_FACE WHERE ORDER_LINK = @LINK

		DECLARE @MSG_DIS VARCHAR(255)
		DECLARE @DIS_LINK INT, @DIS_EMPL_LINK INT, @DIS_DATE DATETIME
		WHILE EXISTS(SELECT * FROM #TEMP_DIS) BEGIN

			SELECT TOP 1 @DIS_LINK = LINK, @DIS_EMPL_LINK = EMPL_LINK, @DIS_DATE = DIS_DATE FROM #TEMP_DIS

			DELETE FROM #TEMP_DIS WHERE LINK = @DIS_LINK
			SET @MSG_DIS = ''
			-- проверка наличия отпуска на момент увольнения
			IF EXISTS(   
				SELECT	*
				FROM	ITEM_VACATION IV LEFT JOIN ITEM_VACATION_BREAK IVB ON IV.LINK = IVB.VAC_LINK AND IVB.ACTIVE = 1
				WHERE	IV.EMPL_LINK = @DIS_EMPL_LINK AND IV.ACTIVE = 1
						AND (@DIS_DATE < CASE WHEN ISNULL(IVB.DATE_BREAK,0) = 0 THEN IV.DATE_END
											   ELSE CASE WHEN ISNULL(IVB.LEN_KAL_DAYS,0) = 0 THEN IVB.DATE_BREAK - 1
														 ELSE DATEADD(DAY,IVB.LEN_KAL_DAYS,IV.DATE_END) 
													END 
										  END)
					) BEGIN

				SET	@MSG_DIS = 'Невозможно уволить сотрудника в период его отпуска' + CHAR(10) + CHAR(10)
				SELECT	TOP 1
						@MSG_DIS = @MSG_DIS + 'Приказ № ' + RTRIM(number) + ' от ' + CONVERT(VARCHAR(10),DATE,104) + ' г. (' + RTRIM(FIO) + ')'
				FROM	VACATION
				WHERE	EMPL_LINK = @DIS_EMPL_LINK AND ACTIVE = 1 AND @DIS_DATE <= DATE_END

				DELETE FROM #TEMP_DIS
			END
		END
		DROP TABLE #TEMP_DIS

		IF LEN(RTRIM(@MSG_DIS)) > 0 BEGIN
			RAISERROR(@MSG_DIS, 11, 1)
			ROLLBACK
			RETURN 666
		END
	
	END

	IF @otype = 24	
		IF @Status<>1 and exists(SELECT TE.LINK FROM DBO.STO_TAR_EMPL TE WHERE TE.ORDER_LINK = @LINK)
		BEGIN
			ROLLBACK
			RETURN 106
		END

	UPDATE orders SET status = @Status WHERE link=@LINK
	SELECT @SQLError = @@ERROR, @RowCount = @@ROWCOUNT
	IF @SQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
	IF @RowCount = 0
	BEGIN
		ROLLBACK
		RETURN 2
	END

	UPDATE ITEM_CHANGE_FM SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_DIS_FACE SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_ENCOUR SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_MOVE SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_ORDER_UNDO SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_TRAVEL SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_TRAVEL_LONG SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_VACATION SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_VACATION_BREAK SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_VACATION_DIS SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_ENCOUR SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_PENALTY SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_PENALTY_CANCEL SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_SUBST SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_FREE SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_WELFARE SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_COMB SET active = @Status WHERE order_link=@LINK
	UPDATE ITEM_CHANGE_OKLAD_STAFF SET active = @Status WHERE order_link=@LINK
	

	DECLARE @item_link int, @empl_link int, @date_begin datetime, @date_end datetime, @type int, @compens tinyint 
	DECLARE @cur CURSOR 

	IF @otype in (4, 104, 15) and dbo.sa_get_option_by_code('TABEL_OPTIONS_OTP_AVTO_OTP') = 1   BEGIN
		SET @cur = CURSOR FAST_FORWARD FOR
			SELECT link, empl_link, date_begin, date_end, type_link, compens FROM item_vacation WHERE order_link=@link
		OPEN @cur
		FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type ,@compens 
		WHILE @@fetch_status=0 BEGIN
			IF @compens = 0 
  		    begin 
			  exec dbo.SA_SET_DAYS_IN_TABELS @empl_link, @date_begin, @date_end, @MSG
			END
			FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type, @compens 
			IF @otype IN (4,104)AND @type IN (SELECT VV.LINK FROM VACATION_VID VV INNER JOIN TYP_DAYS TD ON VV.TYPE_LINK = TD.LINK WHERE TD.WORK_D = 7) 
				AND @compens = 0  
			BEGIN
				UPDATE EMPL
				SET NOTWORK =	CASE WHEN @Status = 1 THEN 1
						     ELSE 0
						END
				WHERE EMPL.LINK = @empl_link
			END
		
		END
		CLOSE @cur
		DEALLOCATE @cur
	END

	IF @otype in (11,16) and dbo.sa_get_option_by_code('TABEL_OPTIONS_OTP_AVTO_OTP') = 1 BEGIN
		SET @cur = CURSOR FAST_FORWARD FOR
			SELECT ivb.link, ivb.empl_link, ivb.DATE_BREAK, date_end, type_link, IVB.LEN_KAL_DAYS, IVB.BREAK_WORK_DAYS FROM item_vacation iv inner join item_vacation_break ivb on ivb.vac_link = iv.link WHERE ivb.order_link=@link
		OPEN @cur
		DECLARE @BREAK_WORK_DAYS INT		-- КОЛИЧЕСТВО КАЛЕНДАРНЫХ ДНЕЙ ОТЗЫВА
		DECLARE @LEN_KAL_DAYS INT			-- КОЛИЧЕСТВО КАЛЕНДАРНЫХ ДНЕЙ ПРОДЛЕНИЯ
		FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type, @LEN_KAL_DAYS, @BREAK_WORK_DAYS
		WHILE @@fetch_status=0 BEGIN
			if @BREAK_WORK_DAYS = 0
				-- ОТЗЫВ ИЗ ОТПУСКА
				exec dbo.SA_SET_DAYS_IN_TABELS @empl_link, @date_begin, @date_end, @MSG
			else 	begin
				-- ОТЗЫВ ИЗ ОТПУСКА НА НЕСКОЛЬКО ДНЕЙ
				SET @date_end = @date_end + @LEN_KAL_DAYS
				exec dbo.SA_SET_DAYS_IN_TABELS @empl_link, @date_begin, @date_end, @MSG
			end
			FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type, @LEN_KAL_DAYS, @BREAK_WORK_DAYS
		END
		CLOSE @cur
		DEALLOCATE @cur
	END

	IF @otype in (12) and dbo.sa_get_option_by_code('TABEL_OPTIONS_OTP_AVTO_OTP') = 1 BEGIN
		SET @cur = CURSOR FAST_FORWARD FOR
			SELECT ivb.link, ivb.empl_link, iv.date_begin, ivb.NEW_DATE_END, type_link FROM item_vacation iv inner join item_vacation_dis ivb on ivb.vac_link = iv.link WHERE ivb.order_link=@link
		OPEN @cur
		FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type
		WHILE @@fetch_status=0 BEGIN
			exec dbo.SA_SET_DAYS_IN_TABELS @empl_link, @date_begin, @date_end, @MSG
			FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type
		END
		CLOSE @cur
		DEALLOCATE @cur
	END


	IF @otype in (5, 105) and dbo.sa_get_option_by_code('TABEL_OPTIONS_OTP_AVTO_COM') = 1 BEGIN
		SET @cur = CURSOR FAST_FORWARD FOR
			SELECT link, empl_link, date_begin, date_end, type_link FROM item_travel WHERE order_link=@link
		OPEN @cur
		FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type
		WHILE @@fetch_status=0 BEGIN
			exec dbo.SA_SET_DAYS_IN_TABELS @empl_link, @date_begin, @date_end, @MSG
			FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type
		END
		CLOSE @cur
		DEALLOCATE @cur
	END

	IF @otype in (13) and dbo.sa_get_option_by_code('TABEL_OPTIONS_OTP_AVTO_COM') = 1 BEGIN
		SET @cur = CURSOR FAST_FORWARD FOR
			SELECT ivb.link, ivb.empl_link, iv.date_begin, ivb.NEW_DATE_END, type_link FROM item_travel iv inner join item_travel_long ivb on ivb.TRAVEL_LINK = iv.link WHERE ivb.order_link=@link
		OPEN @cur
		FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type
		WHILE @@fetch_status=0 BEGIN
			exec dbo.SA_SET_DAYS_IN_TABELS @empl_link, @date_begin, @date_end, @MSG
			FETCH NEXT FROM @cur INTO @item_link, @empl_link, @date_begin, @date_end, @type
		END
		CLOSE @cur
		DEALLOCATE @cur
	END

	-- КОПИРОВАНИЕ СВЕДЕНИЙ О ПРЕДЫДУЩИХ МЕСТАХ РАБОТЫ ПРИ ВТОРИЧНОМ ПРИЕМЕ НА РАБОТУ
	IF @otype in (1,101) BEGIN
		DECLARE NEW_FAC_CUR CURSOR FOR SELECT EMPL_LINK, DATE_BEGIN FROM ITEM_MOVE WHERE ORDER_LINK = @LINK
		DECLARE @OLDWORK_LINK INT
		OPEN NEW_FAC_CUR
		FETCH NEXT FROM NEW_FAC_CUR INTO @EMPL_LINK, @DATE_BEGIN
		DECLARE @EMPL_OLDWORK TABLE(LINK INT IDENTITY(1,1),LINK_OLD INT, EMPL_LINK INT,DATE_BEGIN DATETIME,DATE_END DATETIME,DEP VARCHAR(254),PLACE VARCHAR(254),POST VARCHAR(254),REASON VARCHAR(254))
		DECLARE @EMPL_WORK TABLE(LINK INT IDENTITY(1,1), MOVE_LINK INT, EMPL_LINK INT, DATE_BEGIN DATETIME, DATE_END DATETIME, DEP VARCHAR(254), PLACE VARCHAR(254), POST VARCHAR(254), REASON VARCHAR(254))
		DECLARE @I INT, @J INT
		DECLARE @OLDWORK_NEW_LINK INT
		DECLARE @EMPL_OLD_LINK INT
		--
		DECLARE	@DEP VARCHAR(254)
		DECLARE @DATE_DIS DATETIME
		DECLARE	@OLD_LINK INT
		DECLARE	@OLD_NEW_LINK INT
		DECLARE @REAS_DIS VARCHAR(254)
		--
		SET @I = 1
		WHILE @@FETCH_STATUS = 0 BEGIN
			IF @Status = 1 and not exists(select * from empl_oldwork where empl_link = @empl_link) BEGIN
				SET @EMPL_OLD_LINK = (	SELECT	TOP 1 LINK
							FROM	KU_EMPL_PLACING
							WHERE	PERS_LINK IN (SELECT PERS_LINK FROM EMPL WHERE LINK = @EMPL_LINK)
								AND STATUS = 1
								AND LINK != @EMPL_LINK
							ORDER BY DATE_BEGIN DESC
						      )
				-- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * --
				-- занесение в предыдущие места работы сведений о предыдущих местах работы --
				-- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * --
				IF EXISTS(SELECT * FROM EMPL_OLDWORK WHERE EMPL_LINK = @EMPL_OLD_LINK AND DATE_BEGIN <= @DATE_BEGIN) BEGIN
					INSERT INTO @EMPL_OLDWORK
					SELECT LINK, EMPL_LINK,DATE_BEGIN,DATE_END,DEP,PLACE,POST,REASON FROM EMPL_OLDWORK WHERE EMPL_LINK = @EMPL_OLD_LINK AND DATE_BEGIN <= @DATE_BEGIN
					SET @J = @@IDENTITY
					WHILE @I <= @J BEGIN
						INSERT INTO EMPL_OLDWORK(EMPL_LINK,DATE_BEGIN,DATE_END,DEP,PLACE,POST,REASON)
						SELECT @EMPL_LINK,DATE_BEGIN,DATE_END,DEP,PLACE,POST,REASON FROM @EMPL_OLDWORK WHERE LINK = @I
						SET @OLDWORK_NEW_LINK = @@IDENTITY
						INSERT OLDWORK_KOEF(OLDWORK_LINK,EXPIR_LINK,KOEF)
						SELECT @OLDWORK_NEW_LINK,EXPIR_LINK,KOEF FROM OLDWORK_KOEF WHERE OLDWORK_LINK = (SELECT LINK_OLD FROM @EMPL_OLDWORK WHERE LINK = @I)
						SET @I = @I + 1
					END
				END
				-- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * --
				-- занесение в предыдущие места работы сведений о приемах и переводах в текущей организации --
				-- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * -- * --
				IF EXISTS (SELECT * FROM DIS_FACE  WHERE EMPL_LINK = @EMPL_OLD_LINK AND ACTIVE = 1) BEGIN
					SET @DEP = (SELECT NAME FROM DEPARTMENTS WHERE LINK = (SELECT DEP_LINK FROM EMPL WHERE LINK = @EMPL_OLD_LINK))
					SELECT @DATE_DIS = dis_date, @REAS_DIS = RTRIM(reason_name) FROM DIS_FACE WHERE EMPL_LINK = @EMPL_OLD_LINK AND ACTIVE = 1
					INSERT	INTO @EMPL_WORK
					SELECT	LINK, EMPL_LINK, DATE_BEGIN, DATE_END, @DEP, '', ISNULL(POST_NAME,''), @REAS_DIS
					FROM	KU_ONLY_MOVES
					WHERE	EMPL_LINK = @EMPL_OLD_LINK
					ORDER	BY EMPL_LINK, DATE_BEGIN
					--
					UPDATE	@EMPL_WORK
					SET	DATE_END = @DATE_DIS
					WHERE	LINK = (SELECT COUNT(*) FROM @EMPL_WORK)
					--	
					SET @OLD_LINK = 1
					WHILE EXISTS(SELECT * FROM @EMPL_WORK WHERE LINK = @OLD_LINK) BEGIN
						INSERT INTO EMPL_OLDWORK(EMPL_LINK, DATE_BEGIN, DATE_END, DEP, PLACE, POST, REASON)
						SELECT @EMPL_LINK, DATE_BEGIN, DATE_END, DEP, PLACE, POST, REASON FROM @EMPL_WORK WHERE LINK = @OLD_LINK
						SET @OLD_NEW_LINK = @@IDENTITY
						INSERT OLDWORK_KOEF(OLDWORK_LINK, EXPIR_LINK, KOEF)
						SELECT @OLD_NEW_LINK, EXPIR_LINK, KOEF FROM MOVE_KOEF WHERE MOVE_LINK = (SELECT MOVE_LINK FROM @EMPL_WORK WHERE LINK = @OLD_LINK)
						SET @OLD_LINK = @OLD_LINK + 1
					END
				END
			END
			FETCH NEXT FROM NEW_FAC_CUR INTO @EMPL_LINK, @DATE_BEGIN
		END
		CLOSE NEW_FAC_CUR
		DEALLOCATE NEW_FAC_CUR
	END

	EXEC WF_GENERATEEVENT @txt, @event, null, 'ORDERS', @LINK
	IF @@TRANCOUNT > @trancount
		COMMIT TRAN
	RETURN 0








GO


GRANT EXECUTE ON dbo.[KU_ORDER_CONFIRM] TO PUBLIC

GO



GO

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

GO

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

CREATE PROCEDURE dbo.BK_REPORT_OSV_EMPL_Z
	@varKSdDate1	DATETIME,
	@varKSdDate2	DATETIME,
	@varKScVal1 char(1), @varKSnOtborLink1 int,
	@varKScVal3 char(1), @varKSnOtborLink3 int,
	@cVal_KBK char(1), @nOtborLinkKBK int,	-- Отбор КБК --
	@varKSnPRN_KBK INT,
	@varKSnPRN_SGU INT,
	@intREPORT_EMPL INT,
        @intSVOD_ZB     int,     -- Сводный отчет (ЦБ) --	
	@intSORT_FIO	INT = 0,	-- Сортировать по ФИО -- 
	@intSORT_INV_NAME	INT = 0,		-- Сортировать по Наименованию  -- 
	@intGRP_DOP	INT = 0		-- Группировать по доп. класс-ции --
AS
BEGIN
	DECLARE	@varKSDEP_LINK	INT,
		@varKSDIC_EMP	INT,
		@varKSORGNAME	VARCHAR(254),
		@strDATE_NEXT	VARCHAR (10)

	-- Параметры организации -- 
	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)
	SET @varKSDEP_LINK = dbo.BK_GetDepZB ()

	IF @intSVOD_ZB = 1 OR @varKSDEP_LINK IS NULL
		SET @varKSDEP_LINK = dbo.GetOwnDepLink()

	SELECT @varKSDEP_LINK = LINK,
		@varKSORGNAME = [NAME]
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @varKSDEP_LINK

	IF @intSVOD_ZB = 1
		SET @varKSORGNAME = RTRIM (@varKSORGNAME) + ' (ЦБ)'

	SET @strDATE_NEXT = CONVERT (VARCHAR (10), DATEADD (DAY, 1, @varKSdDate2), 104)

	DECLARE @ACCT  TABLE (LINK_ACCT [INT])	

	IF LEN (@varKScVal1) > 0
		INSERT INTO @ACCT
		SELECT RECORD
		FROM OBJECT_VAR_ACCT
		WHERE LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO @ACCT
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode (DEFAULT, DEFAULT, DEFAULT, 1) ACCT
	
	DECLARE @EMP  TABLE (LINK_EMP [INT], EMP_CODE  [VARCHAR] (20), EMP_NAME [VARCHAR] (254) )
	IF LEN(@varKScVal3)>0 BEGIN
		INSERT INTO @EMP
			SELECT OVR.RECORD, D.TAB, D.[NAME_EMPL]
			FROM OBJECT_VAR_EMPL OVR, KU_EMPL_PLACING D
			WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@varKSnOtborLink3
	END
	ELSE
	BEGIN
		INSERT INTO @EMP
			SELECT D.LINK, D.TAB, D.[NAME_EMPL] FROM KU_EMPL_PLACING D
		INSERT INTO @EMP VALUES (0, '', '')
	END

		--- ОТБОР КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	DECLARE @TABLE1 TABLE (DEP [INT], ACCOUNT [INT], INV [INT], NOMEN [INT], TMC [INT], EMP [INT], 
			KBK [INT], KOSGU [INT],
			D_SUMMA [NUMERIC] (20,2), D_QTY [NUMERIC] (20,2),  
			K_SUMMA [NUMERIC] (20,2), K_QTY [NUMERIC] (20,2),  
			IN_SUMMA [NUMERIC] (20,2), IN_QTY [NUMERIC] (20,2),  	
			OUT_SUMMA [NUMERIC] (20,2), OUT_QTY [NUMERIC] (20,2))  	

	INSERT INTO @TABLE1
	SELECT T1.DEP,
		T1.ACCOUNT,
		T1.INV,
		T1.NOMEN,
		T1.TMC,
		CASE
			WHEN @intREPORT_EMPL = 1 THEN ISNULL (T1.EMP, 0)
			ELSE 0
		END,
		CASE 
			WHEN @varKSnPRN_KBK = 1 THEN ISNULL (T1.KBK, 0)
			ELSE 0
		END,
		CASE 
			WHEN @varKSnPRN_SGU = 1 THEN ISNULL (T1.SGU, 0)
			ELSE 0
		END,
		SUM (T1.D_SUMMA), SUM (T1.D_QTY),
		SUM (T1.K_SUMMA), SUM (T1.K_QTY),
		SUM (T1.IN_SUMMA), SUM (T1.IN_QTY),
		SUM (T1.OUT_SUMMA), SUM (T1.OUT_QTY)
	FROM dbo.BK_GetTableOSVByDate (@varKSdDate1, @varKSdDate2, DEFAULT) T1
	INNER JOIN @ACCT AC ON (AC.LINK_ACCT = T1.ACCOUNT)
	INNER JOIN @TAB_KBK T2 ON (T2.LINK_KBK = T1.KBK)
	WHERE @intSVOD_ZB = 1
		OR (@intSVOD_ZB = 0 AND T1.DEP_LINK = @varKSDEP_LINK)
	GROUP BY  T1.DEP,
		T1.ACCOUNT,
		T1.INV,
		T1.NOMEN,
		T1.TMC,
		CASE
			WHEN @intREPORT_EMPL = 1 THEN ISNULL (T1.EMP, 0)
			ELSE 0
		END,
		CASE 
			WHEN @varKSnPRN_KBK = 1 THEN ISNULL (T1.KBK, 0)
			ELSE 0
		END,
		CASE 
			WHEN @varKSnPRN_SGU = 1 THEN ISNULL (T1.SGU, 0)
			ELSE 0
		END

	DECLARE @RESULT TABLE  (DEP [INT], ACCOUNT [INT], INV [INT], EMP [INT],
			DEP_CODE [VARCHAR] (20), DEP_NAME [VARCHAR] (254),
			ACCT_GR [VARCHAR] (30), ACCT_CODE [VARCHAR] (60),
			INV_CODE [VARCHAR] (20), INV_NAME [VARCHAR] (254),
			UM_CODE [VARCHAR] (20), UM_NAME [VARCHAR] (254),
			INV_COST [NUMERIC] (20,3),		
			EMP_CODE [VARCHAR] (20), EMP_NAME [VARCHAR](254),
			DOP_CODE [VARCHAR] (20), DOP_NAME [VARCHAR](254),
			KAU_CODE [VARCHAR] (20), KAU_NAME [VARCHAR](254),
			SUB INT, SUB_CODE VARCHAR (20), SUB_NAME VARCHAR (254),
			D_SUM [NUMERIC] (20,2), D_QTY [NUMERIC] (20,2),	
			K_SUM [NUMERIC] (20,2), K_QTY [NUMERIC] (20,2),	
			IN_SUM [NUMERIC] (20,2), IN_QTY [NUMERIC] (20,2),		
			OUT_SUM [NUMERIC] (20,2), OUT_QTY [NUMERIC] (20,2),	
			ORGNAME [VARCHAR] (254), DATE_NEXT VARCHAR (10),
			REP_NAME [VARCHAR] (254))

	INSERT INTO @RESULT
	SELECT OSV.DEP,
		OSV.ACCOUNT,
		OSV.INV,
		OSV.EMP,
		DEP.CODE,
		DEP.[NAME],
		SA.CODE,
		dbo.BK_GetAcctFullCode1 (OSV.ACCOUNT, OSV.KBK, OSV.KOSGU, @varKSnPRN_KBK, @varKSnPRN_SGU),
		ISNULL (INV.CODE, ISNULL (NOMEN.CODE, ISNULL (TMC.CODE,''))),
		ISNULL (INV.[NAME], ISNULL (NOMEN.[NAME], ISNULL (TMC.[NAME], ''))),
		COALESCE (INV.CODE_UM, INV.CODE_UM, TMC.REF_CODE_D, ''),
		COALESCE (INV.NAME_UM, INV.NAME_UM, TMC.REF_NAME_D, ''), 
		0,
		EMP.EMP_CODE,
		EMP.EMP_NAME,
		'', '',
		'', '',		-- КАУ --
		0, '', '',	-- Подразделение --
		OSV.D_SUMMA, OSV.D_QTY,
		OSV.K_SUMMA, OSV.K_QTY,
		OSV.IN_SUMMA, OSV.IN_QTY,
		OSV.OUT_SUMMA,
		OSV.OUT_QTY,
		@varKSORGNAME,
		@strDATE_NEXT,
		'МАТЕРИАЛЬНЫХ ЦЕННОСТЕЙ НА ЗАБАЛАНСОВЫХ СЧЕТАХ'
	FROM @TABLE1 OSV
	INNER JOIN @EMP EMP ON (EMP.LINK_EMP = OSV.EMP)
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = OSV.ACCOUNT)
	LEFT OUTER JOIN dbo.DICTIONARY_DEPARTMENT DEP ON (DEP.LINK = OSV.DEP)
	LEFT OUTER JOIN dbo.INVENTORY_CARD INV ON (INV.LINK = OSV.INV)
	LEFT OUTER JOIN dbo.BV_NOMENCLATURE NOMEN ON (NOMEN.LINK = OSV.NOMEN)
	LEFT OUTER JOIN dbo.DICTIONARY_TMC TMC ON (TMC.LINK = OSV.TMC)
	WHERE (OSV.D_SUMMA <> 0) OR (OSV.D_QTY<> 0)
		OR (OSV.K_SUMMA <> 0) OR (OSV.K_QTY <> 0)
		OR (OSV.IN_SUMMA <> 0) OR (OSV.IN_QTY <> 0)
		OR (OSV.OUT_SUMMA <> 0) OR (OSV.OUT_QTY <> 0)

	UPDATE @RESULT SET INV_COST = OUT_SUM / OUT_QTY
	WHERE OUT_QTY <> 0

	IF @intSORT_FIO = 1
		IF @intSORT_INV_NAME = 1
			SELECT * FROM @RESULT
			ORDER BY DEP_CODE, EMP_NAME, EMP_CODE, EMP, ACCT_GR,
				INV_NAME, RIGHT ('00000000000000000000' + INV_CODE, 20)
		ELSE
			SELECT * FROM @RESULT
			ORDER BY DEP_CODE, EMP_NAME, EMP_CODE, EMP, ACCT_GR, 
				RIGHT ('00000000000000000000' + INV_CODE, 20)

	ELSE
		IF @intSORT_INV_NAME = 1
			SELECT * FROM @RESULT
			ORDER BY DEP_CODE, EMP_CODE, EMP, ACCT_GR,
				INV_NAME, RIGHT ('00000000000000000000' + INV_CODE, 20)
		ELSE
			SELECT * FROM @RESULT
			ORDER BY DEP_CODE, EMP_CODE, EMP, ACCT_GR, 
				RIGHT ('00000000000000000000' + INV_CODE, 20)

END


GO


GRANT EXECUTE ON dbo.[BK_REPORT_OSV_EMPL_Z] TO PUBLIC

GO




GO
--текст
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

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

GO



-- rev 1.8
CREATE procedure [dbo].[RMSCreateMessage]
  @msgLink        int             = null output 
 ,@GUID           nvarchar(255)   = null output 
 ,@Type           nvarchar(50)    = null   
 ,@Name           nvarchar(255)   = null   
 ,@Subject        nvarchar(1024)  = null   
 ,@Recipients     nvarchar(2000)  = null   
 ,@Priority       int             = 0
 ,@Status         nvarchar(50)    = 'NEW'  
 ,@Class          nvarchar(50)    = null
 ,@Async          int             = null
 ,@Ttl            datetime        = null
 ,@Body_name      nvarchar(255)   = null
 ,@Body_type      nvarchar(255)   = null
 ,@Body_filesize  int             = null
 ,@Body_value     nvarchar(max)   = null
 ,@PName          nvarchar(255)   = null   
 ,@PValue         nvarchar(max)   = null   
 ,@P2Name         nvarchar(255)   = null   
 ,@P2Value        nvarchar(max)   = null
 ,@P3Name         nvarchar(255)   = null
 ,@P3Value        nvarchar(max)   = null
 ,@P4Name         nvarchar(255)   = null
 ,@P4Value        nvarchar(max)   = null
 ,@P5Name         nvarchar(255)   = null
 ,@P5Value        nvarchar(max)   = null   
 ,@CName          nvarchar(255)   = null   
 ,@CValue         nvarchar(max)   = null   
 ,@CType          nvarchar(255)   = null 
 ,@C2Name         nvarchar(255)   = null   
 ,@C2Value        nvarchar(max)   = null
 ,@C2Type         nvarchar(255)   = null
 ,@C3Name         nvarchar(255)   = null
 ,@C3Value        nvarchar(max)   = null
 ,@C3Type         nvarchar(255)   = null
 ,@C4Name         nvarchar(255)   = null
 ,@C4Value        nvarchar(max)   = null
 ,@C4Type         nvarchar(255)   = null
 ,@C5Name         nvarchar(255)   = null
 ,@C5Value        nvarchar(max)   = null   
 ,@C5Type         nvarchar(255)   = null
 ,@cPropTable     varchar(100)    = ''      
 ,@cContTable     varchar(100)    = ''      
 ,@CorrGuid	      uniqueidentifier = null   
 ,@SyncMode       int             = 0       
                                            
 
as 
begin
  set nocount on
  
  if @GUID is null
    set @GUID = convert(nvarchar(255), newid())
  
  if exists (select * from dbo.sysobjects where id = object_id(N'dbo.RMS_MESSAGES') and OBJECTPROPERTY(id, N'IsUserTable') = 1) 
  begin  
    insert dbo.rms_messages(guid, direction, type, name, subject, date_time, recipients, priority, CORR_GUID, Class, Async, Ttl, Body_name, Body_type, Body_filesize, Body_value)
    select @GUID, 'OUT', @Type, @Name, @Subject, getdate(), @Recipients, @Priority, @CorrGuid, @Class, @Async, @Ttl, @Body_name, @Body_type, @Body_filesize, @Body_value 
    
    select top 1 @msgLink = m.link from dbo.rms_messages m
    where m.guid = @GUID and m.direction = 'OUT'
  end
  else
    return
  
  declare @nPropExists int
  set @nPropExists = case when exists (select * from dbo.sysobjects where id = object_id(N'dbo.RMS_MESSAGE_PROPERTIES') and OBJECTPROPERTY(id, N'IsUserTable') = 1) then 1 else 0 end
  declare @nContExists int
  set @nContExists = case when exists (select * from dbo.sysobjects where id = object_id(N'dbo.RMS_MESSAGE_CONTENTS') and OBJECTPROPERTY(id, N'IsUserTable') = 1) then 1 else 0 end
  
  declare @cSql nvarchar(4000)
  
  if len(@cPropTable)>0 and @nPropExists > 0
  begin
    declare @ptypeexists int 
    set @ptypeexists = case when isnull(col_length('tempdb..'+@cPropTable, 'type'), 0) > 0 then 1 else 0 end
  
    set @cSql = 'insert dbo.rms_message_properties (message_link, name, value' + case when @ptypeexists>0 then ', type' else '' end + ')
    select '+convert(varchar(30),@msgLink)+', t.name, t.value' + case when @ptypeexists>0 then ', t.type' else '' end + '
    from '+@cPropTable+' t'
    
    exec sp_executesql @cSql
  end
  
  if len(@cContTable)>0 and @nContExists > 0
  begin
    declare @ctypeexists int 
    set @ctypeexists = case when isnull(col_length('tempdb..'+@cContTable, 'type'), 0) > 0 then 1 else 0 end
    
    set @cSql = 'insert dbo.rms_message_contents (message_link, name, value' + case when @ctypeexists>0 then ', type' else '' end + ')
    select '+convert(varchar(30),@msgLink)+', t.name, t.value' + case when @ctypeexists>0 then ', t.type' else '' end + '
    from '+@cContTable+' t'
    
    exec sp_executesql @cSql
  end
    
  if len(@cPropTable)=0 and @nPropExists > 0
  begin
    if @PName is not null and @PValue is not null
      insert dbo.rms_message_properties (message_link, name, value)
      select @msgLink, @PName, @PValue

    if @P2Name is not null and @P2Value is not null
      insert dbo.rms_message_properties (message_link, name, value)
      select @msgLink, @P2Name, @P2Value
      
    if @P3Name is not null and @P3Value is not null
      insert dbo.rms_message_properties (message_link, name, value)
      select @msgLink, @P3Name, @P3Value
      
    if @P4Name is not null and @P4Value is not null
      insert dbo.rms_message_properties (message_link, name, value)
      select @msgLink, @P4Name, @P4Value
      
    if @P5Name is not null and @P5Value is not null
      insert dbo.rms_message_properties (message_link, name, value)
      select @msgLink, @P5Name, @P5Value                  
  end
  
  if len(@cContTable)=0 and @nContExists > 0
  begin
    if @CName is not null and @CValue is not null
      insert dbo.rms_message_contents (message_link, name, value, type)
      select @msgLink, @CName, @CValue, @CType

    if @C2Name is not null and @C2Value is not null
      insert dbo.rms_message_contents (message_link, name, value, type)
      select @msgLink, @C2Name, @C2Value, @C2Type
      
    if @C3Name is not null and @C3Value is not null
      insert dbo.rms_message_contents (message_link, name, value, type)
      select @msgLink, @C3Name, @C3Value, @C3Type
      
    if @C4Name is not null and @C4Value is not null
      insert dbo.rms_message_contents (message_link, name, value, type)
      select @msgLink, @C4Name, @C4Value, @C4Type
      
    if @C5Name is not null and @C5Value is not null
      insert dbo.rms_message_contents (message_link, name, value, type)
      select @msgLink, @C5Name, @C5Value, @C5Type
  end
  
  update r
    set status = @Status
  from dbo.rms_messages r
  where r.link = @msgLink and @SyncMode&1 = 0

  if @SyncMode&1 > 0 
  begin
    exec [dbo].[RMS_SENDMESSAGE] @msgLink = @msgLink, @lcReport = 0
  end
  
  
	if object_id('[dbo].[sys_events_rms]') is not null
	  INSERT[dbo].[SYS_EVENTS_RMS](LINK_MSG, GUID, DIRECTION, TYPE, NAME, SUBJECT, DATETIME, SENDER, RECIPIENTS, PRIORITY, STATUS, STATUS_DATE, STATUS_INFO)
    SELECT LINK, GUID, DIRECTION, TYPE, NAME, SUBJECT, DATE_TIME, SENDER, RECIPIENTS, PRIORITY, STATUS, STATUS_DATE, convert(nvarchar(4000), left(STATUS_INFO,4000))
    FROM dbo.rms_messages where link = @msgLink
      
end


GO


GRANT EXECUTE ON dbo.[RMSCreateMessage] TO PUBLIC

GO


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


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

GO


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

CREATE PROCEDURE dbo.BK_REPORT_OSV_AO_PERSON1
	@varKSdDate1	DATETIME,
	@varKSdDate2	DATETIME,
	@varKScVal1 char(1), @varKSnOtborLink1 int,
	@varKScVal2 char(1), @varKSnOtborLink2 int,
	@cVal_KBK char(1), @nOtborLinkKBK int,	-- Отбор КБК --
	@varKSPrnKBK INT,
	@varKSPrnSGU INT,
	@intSVOD_ZB	int,	-- Сводный отчет (ЦБ)--
	@intGRP_DOP	INT,
	@cVal_DOP char(1), @nOtbor_DOP int,	-- Отбор Доп.кл-ции --
	@varKScOtborAccount	VARCHAR (100)
AS
BEGIN
	DECLARE	@varKSDEP_LINK	INT,
		@varKSORGNAME	VARCHAR(254) 

	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)	/* -- Сводный отчет по ЦБ -- */
	SET @varKSDEP_LINK = dbo.BK_GetDepZB ()
				
	IF @intSVOD_ZB = 1 OR @varKSDEP_LINK IS NULL 	/* -- Сводный отчет по ЦБ (собственные реквизиты организации) -- */
		SET @varKSDEP_LINK = dbo.GetOwnDepLink ()

	SELECT @varKSORGNAME = [NAME]
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @varKSDEP_LINK

	IF @intSVOD_ZB = 1
		SET @varKSORGNAME = RTRIM (@varKSORGNAME) + ' (ЦБ)'
	
	-- Отбор субсчетов --
	DECLARE @ACCT TABLE (LINK_ACCT INT)
	IF LEN (@varKScVal1) > 0
		INSERT INTO @ACCT
		SELECT RECORD
		FROM dbo.OBJECT_VAR_ACCT
		WHERE LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO @ACCT
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode (DEFAULT, DEFAULT, DEFAULT, DEFAULT) ACCT
		INNER JOIN dbo.BK_GetValuesTableBySTR (@varKScOtborAccount, DEFAULT) T1 ON (T1.VALUE = ACCT.cSINTH)

	-- Отбор сотрудников --
	DECLARE @EMP TABLE (LINK_EMP INT, EMP_CODE  VARCHAR(20), EMP_NAME VARCHAR(254) )
	IF LEN(@varKScVal2)>0 BEGIN
		INSERT INTO @EMP
		SELECT OVR.RECORD, D.TAB, D.[NAME_EMPL]
		FROM dbo.OBJECT_VAR_EMPL OVR, dbo.KU_EMPL_PLACING D
		WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@varKSnOtborLink2
	END
	ELSE
	BEGIN
		INSERT INTO @EMP
		SELECT D.LINK, D.TAB, D.[NAME_EMPL]
		FROM dbo.KU_EMPL_PLACING D
		INSERT INTO @EMP VALUES (0, '', 'Не указан')
	END

	--- ОТБОР ПО КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	--- ОТБОР ДОП. КЛАССИФИКАЦИИ --- 
	DECLARE @TAB_DOP_CLASSIF TABLE (LINK_DOP INT, DOP_CODE VARCHAR (20), DOP_NAME VARCHAR (254))
	IF LEN (@cVal_DOP) > 0 AND @intGRP_DOP = 1
		INSERT INTO @TAB_DOP_CLASSIF
		SELECT AP.LINK,
			AP.CODE,
			AP.NAME
		FROM dbo.DOP_CLASSIF AP 
		INNER JOIN dbo.OBJECT_VAR_DOP_CLASSIF OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtbor_DOP
	ELSE
		INSERT INTO @TAB_DOP_CLASSIF
		SELECT LINK_AP, AP_CODE, AP_NAME
		FROM dbo.BK_GetTableDictionByAP ('AP2')

	-- ОСВ --
	DECLARE @TABLE1 TABLE (DEP INT, ACCOUNT INT, EMP INT,
			KBK INT, KOSGU INT, DOP INT, 
			D_SUMMA NUMERIC (20,2), D_QTY NUMERIC (20,2),  
			K_SUMMA NUMERIC (20,2), K_QTY NUMERIC (20,2),  
			IN_SUMMA NUMERIC (20,2), IN_QTY NUMERIC (20,2),  	
			OUT_SUMMA NUMERIC (20,2), OUT_QTY NUMERIC (20,2))  	

	INSERT INTO @TABLE1
	SELECT
--		T1.DEP,
		0,
		T1.ACCOUNT,
		T1.EMP,
		CASE 
			WHEN @varKSPrnKBK = 1 THEN T1.KBK
			ELSE 0
		END,
		CASE 
			WHEN @varKSPrnSGU = 1 THEN T1.SGU
			ELSE 0
		END,
		CASE 
			WHEN @intGRP_DOP = 1 THEN T1.AP2
			ELSE 0
		END,
		SUM (T1.D_SUMMA), SUM (T1.D_QTY),
		SUM (T1.K_SUMMA), SUM (T1.K_QTY),
		SUM (T1.IN_SUMMA), SUM (T1.IN_QTY),
		SUM (T1.OUT_SUMMA), SUM (T1.OUT_QTY)
	FROM dbo.BK_GetTableOSVByDate (@varKSdDate1, @varKSdDate2, DEFAULT) T1
	INNER JOIN @ACCT AC ON (AC.LINK_ACCT = T1.ACCOUNT)
	INNER JOIN @TAB_KBK T2 ON (T2.LINK_KBK = T1.KBK)
	INNER JOIN @TAB_DOP_CLASSIF DOP ON (DOP.LINK_DOP = T1.AP2)
	WHERE (@intSVOD_ZB = 1)
		OR (@intSVOD_ZB = 0 AND T1.DEP_LINK = @varKSDEP_LINK)
	GROUP BY
--		T1.DEP,
		T1.ACCOUNT,
		T1.EMP,
		CASE 
			WHEN @varKSPrnKBK = 1 THEN T1.KBK
			ELSE 0
		END,
		CASE 
			WHEN @varKSPrnSGU = 1 THEN T1.SGU
			ELSE 0
		END,
		CASE 
			WHEN @intGRP_DOP = 1 THEN T1.AP2
			ELSE 0
		END

	DECLARE @RESULT TABLE (DEP INT, ACCOUNT INT, EMP INT,
			DEP_CODE VARCHAR (20), DEP_NAME VARCHAR (254),
			ACCT_GR VARCHAR (30), ACCT_CODE VARCHAR (60),
			EMP_CODE VARCHAR (20), EMP_NAME VARCHAR (254),
			DOP_CODE VARCHAR (20), DOP_NAME VARCHAR (254),
			D_SUM NUMERIC (20,2), D_QTY NUMERIC (20,2),	
			K_SUM NUMERIC (20,2), K_QTY NUMERIC (20,2),	
			DIN_SUM NUMERIC (20,2), DIN_QTY NUMERIC (20,2),		
			KIN_SUM NUMERIC (20,2), KIN_QTY NUMERIC (20,2),		
			DOUT_SUM NUMERIC (20,2), DOUT_QTY NUMERIC (20,2),	
			KOUT_SUM NUMERIC (20,2), KOUT_QTY NUMERIC (20,2),	
			ORGNAME VARCHAR (254))

	INSERT INTO @RESULT
	SELECT OSV.DEP,
		OSV.ACCOUNT,
		OSV.EMP,
		ISNULL (DEP.CODE, ''),
		ISNULL (DEP.[NAME],'Не указан'),
		SA.CODE,
		dbo.BK_GetAcctFullCode1 (OSV.ACCOUNT, OSV.KBK, OSV.KOSGU, @varKSPrnKBK, @varKSPrnSGU),
		EMP.EMP_CODE,
		EMP.EMP_NAME,
		DOP.DOP_CODE,
		DOP.DOP_NAME,
		OSV.D_SUMMA, OSV.D_QTY,
		OSV.K_SUMMA, OSV.K_QTY,
		CASE
			WHEN SA.S_ACTIVE  = 1 AND SA.S_PASSIVE = 0 THEN OSV.IN_SUMMA
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 1 AND SA.S_PASSIVE = 0 THEN OSV.IN_QTY
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 0 AND SA.S_PASSIVE = 1 THEN OSV.IN_SUMMA
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 0 AND SA.S_PASSIVE = 1 THEN OSV.IN_QTY
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 1 AND SA.S_PASSIVE = 0 THEN OSV.OUT_SUMMA
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 1 AND SA.S_PASSIVE = 0 THEN OSV.OUT_QTY
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 0 AND SA.S_PASSIVE = 1 THEN OSV.OUT_SUMMA
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 0 AND SA.S_PASSIVE = 1 THEN OSV.OUT_QTY
			ELSE 0
		END,
		@varKSORGNAME AS ORGNAME
	FROM @TABLE1 OSV
	INNER JOIN @EMP EMP ON (EMP.LINK_EMP = OSV.EMP)
	INNER JOIN @TAB_DOP_CLASSIF DOP ON (DOP.LINK_DOP = OSV.DOP)
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = OSV.ACCOUNT)
	LEFT OUTER JOIN dbo.DICTIONARY_DEPARTMENT DEP ON (DEP.LINK = OSV.DEP)
	WHERE (OSV.D_SUMMA <> 0) OR (OSV.D_QTY<> 0)
		OR (OSV.K_SUMMA <> 0) OR (OSV.K_QTY <> 0)
		OR (OSV.IN_SUMMA <> 0) OR (OSV.IN_QTY <> 0)
		OR (OSV.OUT_SUMMA <> 0) OR (OSV.OUT_QTY <> 0)

	SELECT *,
		ISNULL (@intGRP_DOP, 0) AS DOP_GR
	FROM @RESULT ORDER BY DEP_CODE, EMP_CODE, DOP_CODE, ACCT_GR, ACCT_CODE

END



GO


GRANT EXECUTE ON dbo.[BK_REPORT_OSV_AO_PERSON1] TO PUBLIC

GO




GO

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

GO

CREATE    PROCEDURE [dbo].SALARY_BASE_SUM_PAY_MONTH_DIF_PERIODS 
/*Для расчетов по больничным листам*/
 @RefPay 	int,
 @linkEmpl	 int,
 @Month	int,
 @Year	int,
 @MODE INT = 0 --определяет вид операции @RefPay, для которого ищется база - начисление(0) или отчисление(1)
AS  
declare @dDate1 datetime, @dDate2 datetime

DECLARE @Status INT
SELECT @Status = [STATUS] FROM dbo.ITEM_MOVE WHERE ACTIVE = 1 AND EMPL_LINK = @linkEmpl	-->>NEW

CREATE TABLE #SJC (LINK_PAYS INT, WAY_CALC TINYINT, CODE_PAYS VARCHAR(10), NAME_PAYS VARCHAR(60), SUMMA NUMERIC(18,2), 
					LINK_INC INT, LINK_VKR INT, DATE1 DATETIME, DATE2 DATETIME,
					LINK_DOC INT, LINK_EMPL INT, PERIOD_BEGIN DATETIME)

CREATE TABLE #GROUP_PAYS (PAY_LINK INT, PERIOD INT, KOEF NUMERIC(18,10), LINK_GRP INT)
INSERT INTO #GROUP_PAYS (PAY_LINK, PERIOD, KOEF, LINK_GRP)
SELECT PAY_LINK, PERIOD, KOEF, LINK_GRP FROM dbo.group_pays(@RefPay)

IF @MODE = 0
	INSERT INTO #SJC (LINK_PAYS, WAY_CALC, CODE_PAYS, NAME_PAYS, SUMMA, LINK_INC, LINK_VKR, DATE1, DATE2, LINK_DOC, LINK_EMPL, PERIOD_BEGIN)
	SELECT SJ.LINK_PAYS, SJ.WAY_CALC, SJ.CODE_PAYS, SJ.NAME_PAYS, SJ.SUMMA, SJ.LINK_INC, SJ.LINK_VKR, SJ.DATE1, SJ.DATE2, SJ.LINK_DOC, SJ.LINK_EMPL, SJ.PERIOD_BEGIN
	FROM 
		dbo.S_J_C_Short SJ
		INNER JOIN #GROUP_PAYS T ON SJ.link_PAYS=T.PAY_LINK 
	WHERE 
		SJ.LINK_EMPL = @linkEmpl
	
ELSE
	INSERT INTO #SJC (LINK_PAYS, WAY_CALC, CODE_PAYS, NAME_PAYS, SUMMA, LINK_INC, LINK_VKR, DATE1, DATE2, LINK_DOC, LINK_EMPL, PERIOD_BEGIN)
	SELECT SJ.LINK_PAYS, SJ.WAY_CALC, SJ.CODE_PAYS, SJ.NAME_PAYS, SJ.SUMMA, SJ.LINK_INC, SJ.LINK_VKR, SJ.DATE1, SJ.DATE2, SJ.LINK_DOC, SJ.LINK_EMPL, SJ.PERIOD_BEGIN
	FROM 
		dbo.S_J_C_Short SJ
		INNER JOIN dbo.TAX_REF TR ON TR.LINK_PAYS =  SJ.LINK_PAYS
	WHERE 
		TR.LINK_TAX = @RefPay 
		AND LINK_EMPL = @linkEmpl

if @Month<1 or @Month>12
	return -1
SET @dDate1 = convert(datetime,'01.'+str(@Month)+'.'+str(@Year),104)
SET @dDate2 =DATEADD(M,1,@dDate1) -1

--------
CREATE TABLE #KU_EmplStafKBK (LINK_EMPL INT, LINK_KBK INT)
INSERT INTO #KU_EmplStafKBK (LINK_EMPL, LINK_KBK)
SELECT LINK_EMPL, LINK_KBK FROM dbo.KU_EmplStafKBK(default) WHERE LINK_EMPL = @linkEmpl

DECLARE @DOCUMENTS_RECALC_OPT1 INT --Суммы перерасчёта учитывать в месяце
SET @DOCUMENTS_RECALC_OPT1 = dbo.SA_GET_OPTION_BY_CODE('DOCUMENTS_RECALC_OPT1')
IF ISNULL(@DOCUMENTS_RECALC_OPT1,0) NOT IN (1,2) 
	SET @DOCUMENTS_RECALC_OPT1 = 1

CREATE TABLE #TMP (ID INT IDENTITY(1,1), CODE_PAY VARCHAR(10),NAME_PAY VARCHAR(60),WAY_CALC TINYINT, LINK_PAY INT, SUMMA NUMERIC(18,2), 
					KOEF NUMERIC(18,10), LINK_INC INT, LINK_VKR INT, DATE1 DATETIME, DATE2 DATETIME)

------
INSERT INTO #TMP (CODE_PAY,NAME_PAY,WAY_CALC,LINK_PAY,SUMMA,KOEF,LINK_INC,LINK_VKR,DATE1,DATE2)
SELECT 			
			[CODE_PAY] = CODE_PAYS,
			[NAME_PAY] = NAME_PAYS,
			[WAY_CALC],
			SJ.LINK_PAYS as [LINK_PAY],
			SUM(SJ.SUMMA) as [SUMMA],
			KOEF = 0,
			LINK_INC, LINK_VKR = COALESCE(LINK_VKR,DEF.LINK_KBK), DATE1, DATE2
FROM 
	#SJC SJ
	LEFT JOIN #KU_EmplStafKBK DEF ON DEF.LINK_EMPL = SJ.LINK_EMPL	
	--суммы по перерасчету будем учитывать в месяце, за который перерасчитывали, если они начислены в том же году
	LEFT JOIN dbo.SDOC_AREC R ON SJ.LINK_DOC = R.LINK_UP
WHERE 
	SJ.LINK_EMPL = @linkEmpl 
	AND
	(
		(
		COALESCE(R.LINK_UP,0) = 0 --НЕ ПЕРЕРАСЧЁТ
		OR
		(
			COALESCE(R.LINK_UP,0) <> 0 --ПЕРЕРАСЧЁТ
			AND
			@DOCUMENTS_RECALC_OPT1 = 2 -- И СУММЫ ЗА ПЕРЕРАСЧЁТ УЧИТЫВАТЬ В МЕСЯЦЕ, В КОТОРОМ ПЕРЕРАСЧИТЫВАЛИ
		)	
		OR
		SJ.WAY_CALC in (6,7) --НАЧИСЛЕНИЕ ПРЕМИИ
		)
		AND YEAR(SJ.PERIOD_BEGIN) = @Year AND MONTH(SJ.PERIOD_BEGIN) = @Month
	OR
		(
		COALESCE(R.LINK_UP,0) <> 0-- ЭТО ПЕРЕРАСЧЁТ
		AND 
		@DOCUMENTS_RECALC_OPT1 = 1 --И СУММЫ ЗА ПЕРЕРАСЧЁТ УЧИТЫВАТЬ В МЕСЯЦЕ, ЗА КОТОРЫЙ ПЕРЕРАСЧИТЫВАЛИ
		AND
		SJ.WAY_CALC NOT IN (6,7) -- НО НЕ ПЕРЕРАСЧЁТ ПРЕМИИ
		)
		AND YEAR(SJ.DATE1) = @Year AND MONTH(SJ.DATE1) = @Month
	)
GROUP BY  
	SJ.link_PAYS, LINK_INC, CODE_PAYS, NAME_PAYS, WAY_CALC, COALESCE(LINK_VKR,DEF.LINK_KBK), DATE1, DATE2


IF dbo.SA_GET_OPTION_BY_CODE('ARCHE_OPT3') = 1 AND @Status IN (1 /*Основной*/, 3 /*Внешний совместитель*/)
BEGIN
	
	/*
	Игнатьев А.Н. 2007-02-05
		В соответствии с ФЗ "255-ФЗ от 29.12.2006 ст.14, п.2
		Учитываем доходы, с которых уплачивались взносы в ФСС.
		Мат. помощь и пр. доходы, на которые предоставляется льгота 3000р. берем за минусом этой льготы
	*/
	
	CREATE TABLE #SPR_PREDEL (LINK_PAY INT, SUMMA NUMERIC(18,2) )
	INSERT INTO #SPR_PREDEL (LINK_PAY, SUMMA)
	SELECT REF_PAY, PREDEL FROM dbo.Salary_deduct_esn(@dDate1) 

	DECLARE @SPR TABLE (LINK_PAY int, LINK_DOH int, LINK_VYCH int, PREDEL numeric(18,2))

	/*Справочник пределов льгот*/
	insert into @SPR(LINK_PAY, LINK_DOH, LINK_VYCH, PREDEL)
	select DISTINCT LINK_PAY= P.link, LINK_DOH= DTI.LINK, LINK_VYCH= SDE.LINK_PAY,  SUMMA from dbo.pays P inner join dbo.DICTIONARY_TYP_INCOMS DTI on P.link_inc = DTI.link 
		inner join #SPR_PREDEL SDE on SDE.LINK_PAY = DTI.REF_DEDUCT

	/*Для каждого кода дохода рассчитывается остаток льготы*/

	DECLARE @PREDEL0 TABLE (LINK_DOH int, PREDEL numeric(18,2))
	INSERT INTO @PREDEL0 (LINK_DOH, PREDEL)
	SELECT DISTINCT LINK_DOH, PREDEL FROM @SPR

	CREATE TABLE #MAT_POM (DATE1 DATETIME, LINK_DOH INT, SUMMA NUMERIC(18,2))
	INSERT INTO #MAT_POM (DATE1, LINK_DOH, SUMMA)
	SELECT SJC.PERIOD_BEGIN, SJC.LINK_INC, SUM(SJC.SUMMA)
	FROM 
		#SJC SJC
	WHERE 
		YEAR(SJC.PERIOD_BEGIN) = @Year AND SJC.PERIOD_BEGIN <= @dDate2
		AND
		EXISTS (SELECT * FROM @SPR WHERE LINK_DOH = LINK_INC)
	GROUP BY 
		SJC.PERIOD_BEGIN, SJC.LINK_INC

	DECLARE @Cur CURSOR, @Cur0 CURSOR, @DATE1 DATETIME, @LINK_D1 INT, @PREDEL1 NUMERIC(18,2)
	SET @Cur = CURSOR FORWARD_ONLY
	FOR SELECT DISTINCT LINK_DOH FROM #MAT_POM ORDER BY LINK_DOH
	OPEN @Cur
	FETCH NEXT FROM @Cur INTO @LINK_D1
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN

			SET @PREDEL1 = ISNULL((SELECT TOP 1  PREDEL FROM @PREDEL0 WHERE LINK_DOH = @LINK_D1),0)

			SET @Cur0 = CURSOR FORWARD_ONLY
			FOR SELECT DATE1 FROM #MAT_POM WHERE LINK_DOH = @LINK_D1 ORDER BY LINK_DOH
			OPEN @Cur0
			FETCH NEXT FROM @Cur0 INTO @DATE1
			WHILE (@@fetch_status <> -1)
			BEGIN
				IF (@@fetch_status <> -2)
				BEGIN

					UPDATE #MAT_POM 
					SET SUMMA = CASE WHEN SUMMA >= @PREDEL1 THEN @PREDEL1 ELSE SUMMA END
					WHERE DATE1 =  @DATE1 AND LINK_DOH = @LINK_D1

					SET @PREDEL1 = @PREDEL1 - ISNULL((SELECT SUM(SUMMA) FROM #MAT_POM WHERE LINK_DOH = @LINK_D1 AND DATE1 = @DATE1),0)
				
				END
				FETCH NEXT FROM @Cur0 INTO @DATE1
			
			END	
			CLOSE @Cur0
			DEALLOCATE @Cur0
			
		
		END
		FETCH NEXT FROM @Cur INTO @LINK_D1
	
	END	
	CLOSE @Cur
	DEALLOCATE @Cur

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

	DECLARE @PREDEL TABLE (LINK_DOH int, PREDEL numeric(18,2))

	INSERT INTO @PREDEL (LINK_DOH, PREDEL)
	SELECT LINK_DOH, SUMMA FROM #MAT_POM WHERE YEAR(DATE1) = @Year AND MONTH(DATE1) = @Month

	/*Для каждого вида дохода с льготой*/
	DECLARE @Cur1 CURSOR, @LINK_DOH int, @PREDEL_SUM numeric(18,2), @Cur2 CURSOR, @LINK_PAY INT, @SUMMA1 numeric(18,2), @ID INT
	SET @Cur1 = CURSOR FORWARD_ONLY
	FOR Select * from @PREDEL where PREDEL > 0
		
	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @LINK_DOH, @PREDEL_SUM
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			SET @Cur2 = CURSOR FORWARD_ONLY
			FOR Select ID, SUMMA from #tmp where LINK_INC = @LINK_DOH and summa > 0
			OPEN @Cur2
			FETCH NEXT FROM @Cur2 INTO @ID, @SUMMA1
			WHILE (@@fetch_status <> -1)
			BEGIN
				IF (@@fetch_status <> -2)
				BEGIN	

					/*Уменьшаем сумму начисления на сумму льготы, т.к. с суммы льготы не отчислялии в ФСС*/
					UPDATE #tmp SET SUMMA = (CASE WHEN @PREDEL_SUM > 0  THEN
												CASE WHEN SUMMA > @PREDEL_SUM 
													THEN SUMMA - @PREDEL_SUM
													ELSE 0
												END		
												ELSE SUMMA 
											 END) 
					WHERE ID = @ID and summa > 0		
					
					/*Рассчитаем остаток льготы*/
					SET @PREDEL_SUM = @PREDEL_SUM - (Select @SUMMA1 - SUM(SUMMA) from #tmp where ID = @ID)
		
				END
				FETCH NEXT FROM @Cur2 INTO @ID, @SUMMA1
			END
			
			CLOSE @Cur2
			DEALLOCATE @Cur2
		END
		FETCH NEXT FROM @Cur1 INTO @LINK_DOH, @PREDEL_SUM
	END
	
	CLOSE @Cur1
	DEALLOCATE @Cur1
END

SELECT CODE_PAY,NAME_PAY,WAY_CALC,LINK_PAY,SUMMA,KOEF,LINK_INC,LINK_VKR,DATE1,DATE2 
FROM #TMP 
ORDER BY REPLACE(STR(CODE_PAY,10),' ', 0)


GO


GRANT EXECUTE ON dbo.[SALARY_BASE_SUM_PAY_MONTH_DIF_PERIODS] TO PUBLIC

GO


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


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

--------------------------------------------------------------------------------------------
-- ОБРАБОТЧИ СООБЩЕНИЙ С ШИНЫ ИЗ СМЕТЫ-СМАРТ
-- Требуется на базе зарплаты-кс
--------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[SMETA_SMART_MESSAGE_HANDLER]
	@msgLink INT OUTPUT
AS
BEGIN
	DECLARE
		 @Recipients		VARCHAR(1000)	-- получатель ответного сообщения
		,@msgContent		VARCHAR(max)	-- Содержимое сообщения в формате xml
		,@xmlData			XML				-- Данные в виде xml для передачи по шине
		,@objectCode		VARCHAR(30)		-- Код объекта для приёма

	-- Загрузка переменных из сообщения
	SET @objectCode = dbo.RMSGetProp(@msgLink, 'object')

	-- Документ для зарплаты
	IF (@objectCode = 'DOCUMENTS_SALARY')
	BEGIN
		SET @msgContent = dbo.RMSGetValue(@msgLink, 'XML')
		SET @xmlData = CONVERT(XML, @msgContent)
		EXEC dbo.[SMETA_SMART_DOCUMENTS_SALARY] @xmlData = @xmlData
	END
	-- Справочники Бюджетная классификация
	ELSE IF (@objectCode IN('BI_DICTION_KBK','BI_DICTION_DIV','BI_DICTION_ADMIN_BS','BI_DICTION_CSR','BI_DICTION_EXP','BI_DICTION_INCOME','BD_DOP_CLASSIF','DICTIONARY_REGIONAL','BB_DICTION_PROG','BI_DICTION_IVF','DICTIONARY_KOSGU','DEPARTMENTS_CORR'))
	BEGIN
		EXEC dbo.[SMETA_SMART_DICTION_RECEIVE] @msgLink = @msgLink
	END
	-- Кадровая информация
	ELSE IF (@objectCode = 'DICTIONARY_POST')
	BEGIN
		EXEC dbo.[SMETA_SMART_KADR_SEND] @msgLink = @msgLink OUTPUT, @objectCode = @objectCode
		RETURN 0
	END

	SET @msgLink = 0
END
GO

GRANT EXECUTE ON dbo.[SMETA_SMART_MESSAGE_HANDLER] TO PUBLIC
GO
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_REPORT_OSV_AO_DEPART1]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_REPORT_OSV_AO_DEPART1]

GO



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

CREATE PROCEDURE dbo.BK_REPORT_OSV_AO_DEPART1
	@varKSdDate1	DATETIME	,
	@varKSdDate2	DATETIME	,
	@varKScVal1 char(1), @varKSnOtborLink1 int	,
	@varKScVal2 char(1), @varKSnOtborLink2 int	,
	@cVal_KBK char(1), @nOtborLinkKBK int,	-- Отбор КБК --
	@varKSPrnKBK INT				,
	@varKSPrnSGU INT				,

	@varKScOtborAccount	VARCHAR (100)		,
	@varKScOtborAccountAN	VARCHAR (100)		,
	@intTYPE_ORG		INT,
	@intSVOD_ZB		int,		-- Сводный отчет (ЦБ) 
	@intREP_BY_OSNOV	INT = 0		-- Отчет в разрезе договоров
AS
BEGIN
	DECLARE	@varKSDEP_LINK	INT,
		@varKSORGNAME	VARCHAR(254)

	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)	/* -- Сводный отчет по ЦБ -- */
	SET @varKSDEP_LINK = dbo.BK_GetDepZB ()
				
	IF @intSVOD_ZB = 1 OR @varKSDEP_LINK IS NULL		/* -- Сводный отчет по ЦБ (собственные реквизиты организации) -- */
		SET @varKSDEP_LINK = dbo.GetOwnDepLink ()

	SELECT @varKSORGNAME = [NAME]
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @varKSDEP_LINK

	IF @intSVOD_ZB = 1
		SET @varKSORGNAME = RTRIM (@varKSORGNAME) + ' (ЦБ)'

	DECLARE @ACCT TABLE (LINK_ACCT INT)
	IF LEN (@varKScVal1) > 0
		INSERT INTO @ACCT
		SELECT RECORD
		FROM dbo.OBJECT_VAR_ACCT
		WHERE LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO @ACCT
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode ('302', DEFAULT, DEFAULT, DEFAULT) ACCT
		UNION 
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode ('206', DEFAULT, DEFAULT, DEFAULT) ACCT

	DECLARE @DEP TABLE (LINK_DEP INT, DEP_CODE  VARCHAR(20), DEP_NAME VARCHAR(254) )
	IF LEN(@varKScVal2)>0 BEGIN
		INSERT INTO @DEP
		SELECT OVR.RECORD, D.CODE, D.[NAME]
		FROM dbo.OBJECT_VAR_DEPARTMENT OVR, dbo.DICTIONARY_DEPARTMENT D
		WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@varKSnOtborLink2
	END
	ELSE
	BEGIN
		INSERT INTO @DEP
		SELECT D.LINK, D.CODE, D.[NAME]
		FROM dbo.DICTIONARY_DEPARTMENT D
		WHERE (@intTYPE_ORG = 0)
			OR (@intTYPE_ORG <> 0 AND TYPE = @intTYPE_ORG)
		INSERT INTO @DEP VALUES (0, '', 'Не указан')
	END

	--- ОТБОР ПО КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	DECLARE @TABLE1 TABLE (DEP INT, ACCOUNT INT, 
			KBK INT, KOSGU INT, AP1 INT,
			D_SUMMA NUMERIC (20,2), D_QTY NUMERIC (20,2),  
			K_SUMMA NUMERIC (20,2), K_QTY NUMERIC (20,2),  
			IN_SUMMA NUMERIC (20,2), IN_QTY NUMERIC (20,2),  	
			OUT_SUMMA NUMERIC (20,2), OUT_QTY NUMERIC (20,2))  	

	INSERT INTO @TABLE1
	SELECT T1.DEP,
		T1.ACCOUNT,
		CASE
			WHEN @varKSPrnKBK = 1 THEN T1.KBK
			ELSE 0
		END,
		CASE
			WHEN @varKSPrnSGU = 1 THEN T1.SGU
			ELSE 0
		END,
		CASE 
			WHEN @intREP_BY_OSNOV = 1 THEN T1.AP1
			ELSE 0
		END,
		SUM (T1.D_SUMMA), SUM (T1.D_QTY),
		SUM (T1.K_SUMMA), SUM (T1.K_QTY),
		SUM (T1.IN_SUMMA), SUM (T1.IN_QTY),
		SUM (T1.OUT_SUMMA), SUM (T1.OUT_QTY)
	FROM dbo.BK_GetTableOSVByDate (@varKSdDate1, @varKSdDate2, DEFAULT) T1
	INNER JOIN @TAB_KBK T2 ON (T2.LINK_KBK = T1.KBK)
	INNER JOIN @ACCT AC ON (AC.LINK_ACCT = T1.ACCOUNT)
	WHERE (@intSVOD_ZB = 1)
		OR (@intSVOD_ZB = 0 AND T1.DEP_LINK = @varKSDEP_LINK)
	GROUP BY  T1.DEP,
		T1.ACCOUNT,
		CASE
			WHEN @varKSPrnKBK = 1 THEN T1.KBK
			ELSE 0
		END,
		CASE
			WHEN @varKSPrnSGU = 1 THEN T1.SGU
			ELSE 0
		END,
		CASE 
			WHEN @intREP_BY_OSNOV = 1 THEN T1.AP1
			ELSE 0
		END

	DECLARE @RESULT TABLE (DEP INT, ACCOUNT INT, 
			DEP_CODE VARCHAR (20), DEP_NAME VARCHAR (254),
			ACCT_GR VARCHAR (30), ACCT_CODE VARCHAR (60),
			
			OSNOV_LINK INT, NUM_OSNOV	VARCHAR (30),
			DATE_OSNOV DATETIME, INF_OSNOV VARCHAR (254),

			D_SUM NUMERIC (20,2), D_QTY NUMERIC (20,2),	
			K_SUM NUMERIC (20,2), K_QTY NUMERIC (20,2),	
			DIN_SUM NUMERIC (20,2), DIN_QTY NUMERIC (20,2),		
			KIN_SUM NUMERIC (20,2), KIN_QTY NUMERIC (20,2),		
			DOUT_SUM NUMERIC (20,2), DOUT_QTY NUMERIC (20,2),	
			KOUT_SUM NUMERIC (20,2), KOUT_QTY NUMERIC (20,2),	
			ORGNAME VARCHAR (254),
			REP_HDR VARCHAR (254))

	INSERT INTO @RESULT
	SELECT OSV.DEP,
		OSV.ACCOUNT,
		DEP.DEP_CODE,
		DEP.DEP_NAME,
		SA.CODE,
		dbo.BK_GetAcctFullCode1 (OSV.ACCOUNT, OSV.KBK, OSV.KOSGU, @varKSPrnKBK, @varKSPrnSGU),

		OSN.LINK, OSN.NUMBER,
		OSN.[DATE], OSN.INFO,

		OSV.D_SUMMA, OSV.D_QTY,
		OSV.K_SUMMA, OSV.K_QTY,
		CASE
			WHEN SA.S_ACTIVE  = 1 AND SA.S_PASSIVE = 0 THEN OSV.IN_SUMMA
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 1 AND SA.S_PASSIVE = 0 THEN OSV.IN_QTY
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 0 AND SA.S_PASSIVE = 1 THEN OSV.IN_SUMMA
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 0 AND SA.S_PASSIVE = 1 THEN OSV.IN_QTY
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 1 AND SA.S_PASSIVE = 0 THEN OSV.OUT_SUMMA
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 1 AND SA.S_PASSIVE = 0 THEN OSV.OUT_QTY
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 0 AND SA.S_PASSIVE = 1 THEN OSV.OUT_SUMMA
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 0 AND SA.S_PASSIVE = 1 THEN OSV.OUT_QTY
			ELSE 0
		END,
		@varKSORGNAME AS ORGNAME,
		'ПО РАСЧЕТАМ С ОРГАНИЗАЦИЯМИ' AS REP_HDR
	FROM @TABLE1 OSV
	INNER JOIN @DEP DEP ON (DEP.LINK_DEP = OSV.DEP)
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = OSV.ACCOUNT)
	LEFT JOIN dbo.BD_OSNOV OSN ON (OSN.LINK = OSV.AP1)
	WHERE (OSV.D_SUMMA <> 0) OR (OSV.D_QTY<> 0)
		OR (OSV.K_SUMMA <> 0) OR (OSV.K_QTY <> 0)
		OR (OSV.IN_SUMMA <> 0) OR (OSV.IN_QTY <> 0)
		OR (OSV.OUT_SUMMA <> 0) OR (OSV.OUT_QTY <> 0)

	SELECT *,
		ISNULL (@intREP_BY_OSNOV, 0) AS BY_OSNOV
	FROM @RESULT
	ORDER BY DEP_CODE, DATE_OSNOV, NUM_OSNOV, OSNOV_LINK, ACCT_GR, ACCT_CODE
END


GO


GRANT EXECUTE ON dbo.[BK_REPORT_OSV_AO_DEPART1] TO PUBLIC

GO



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

GO
CREATE PROCEDURE [dbo].UNLOAD_XD_DOC_NASTR_TO(@NAME_OPER VARCHAR(254) = NULL)
AS
--EXECUTE dbo.[UNLOAD_XD_DOC_NASTR_TO] @NAME_OPER = 'Начисление отпускных (компенсации) за счет резерва  (Дт401.60-Кт302.11)'
BEGIN

SET NOCOUNT ON

IF OBJECT_ID('TEMPDB..#OUT') IS NOT NULL
	DROP TABLE #OUT

CREATE TABLE #OUT (ORD INT IDENTITY(1,1), TXT VARCHAR(8000), LINK INT)
INSERT INTO #OUT (TXT)
SELECT
'--Добавление в настройки документа "Типовая операция"
--Сгенерировано скриптом: EXECUTE dbo.[UNLOAD_XD_DOC_NASTR_TO] @NAME_OPER = ' 
+ CASE WHEN @NAME_OPER IS NULL THEN 'NULL' ELSE '''' + LTRIM(RTRIM(@NAME_OPER)) + '''' END

INSERT INTO #OUT (TXT)
SELECT
'
SET NOCOUNT ON

' + CHAR(13) + CHAR(10)

INSERT INTO #OUT (TXT)
SELECT
'IF OBJECT_ID(''TEMPDB..#tmp_XD_DOC_NASTR_TO'') IS NOT NULL
	DROP TABLE #tmp_XD_DOC_NASTR_TO
' + CHAR(13) + CHAR(10)

	
INSERT INTO #OUT (TXT)
SELECT
'
CREATE TABLE #tmp_XD_DOC_NASTR_TO (
	[SO_CODE] VARCHAR(30),
	[NAME_OPER] VARCHAR(2000),
	[OSN] tinyint)
'+ CHAR(13) + CHAR(10)

INSERT INTO #OUT (TXT)
SELECT 'INSERT INTO #tmp_XD_DOC_NASTR_TO ([SO_CODE], [NAME_OPER], [OSN]) 
VALUES(' 
+ '''' + LTRIM(RTRIM(SO.CODE)) + ''''
+ ', ''' + LTRIM(RTRIM(G1.[NAME_OPER])) + ''''
+ ', ' + CASE WHEN DTN.OSN IS NULL THEN 'NULL' ELSE CONVERT(VARCHAR(20),DTN.OSN) END
+ ')' + CHAR(13) + CHAR(10)
FROM
	dbo.G_PROV1 G1
	INNER JOIN dbo.DOC_NASTR_T1 DTN ON DTN.LINK_OPER = G1.LINK
	INNER JOIN dbo.DOC_NASTR DN ON DN.LINK = DTN.LINK_UP
	INNER JOIN dbo.S_OBJECTS SO ON SO.LINK = DN.[LINK]
WHERE
	(@NAME_OPER IS NULL OR @NAME_OPER = G1.NAME_OPER)

INSERT INTO #OUT (TXT)
SELECT '
IF OBJECT_ID(''TEMPDB..#G_PROV1_REC'') IS NOT NULL
	DROP TABLE #G_PROV1_REC
'

INSERT INTO #OUT (TXT)
SELECT '
CREATE TABLE #G_PROV1_REC (LINK1 INT, LINK2 INT)
'

INSERT INTO #OUT (TXT)
SELECT '
INSERT INTO dbo.DOC_NASTR (LINK, PRINT_SGU, PRINT_KBK, AN_PERIOD, AN_ORG, AN_BEGIN, AN_SHABLON) 
SELECT DISTINCT SO.LINK, PRINT_SGU=0, PRINT_KBK=0, AN_PERIOD=0, AN_ORG=0, AN_BEGIN=0, AN_SHABLON=''''
FROM
	#tmp_XD_DOC_NASTR_TO T
	INNER JOIN dbo.S_OBJECTS SO ON SO.CODE LIKE T.SO_CODE
WHERE
	NOT EXISTS (SELECT * FROM dbo.DOC_NASTR DN WHERE DN.[LINK] = SO.LINK)
'

INSERT INTO #OUT (TXT)
SELECT '
INSERT INTO 
	[dbo].[DOC_NASTR_T1] (LINK_UP, LINK_OPER, OSN)
SELECT 
	DN.LINK, G1.LINK, T.OSN
FROM
	#tmp_XD_DOC_NASTR_TO T
	INNER JOIN dbo.S_OBJECTS SO ON SO.CODE = T.SO_CODE
	INNER JOIN dbo.DOC_NASTR DN ON DN.[LINK] = SO.LINK
	INNER JOIN dbo.G_PROV1 G1 ON G1.NAME_OPER = T.[NAME_OPER]
	INNER JOIN dbo.G_PROV G ON G.LINK = G1.LINK_UP
	INNER JOIN dbo.S_OBJECTS SO2 ON SO2.LINK = G.[OBJECT] AND SO2.CODE = ''SHABLON_DOCUMENTS_PROV''
WHERE
	NOT EXISTS ( SELECT * FROM [dbo].[DOC_NASTR_T1] N WHERE N.LINK_UP = DN.LINK AND N.[LINK_OPER] = G1.LINK)
'					

 INSERT INTO #OUT (TXT)
SELECT
'
GO' + CHAR(13) + CHAR(10)


SELECT TXT as [--TXT] FROM #OUT ORDER BY ORD

SET NOCOUNT OFF
END

GO


GRANT EXECUTE ON dbo.[UNLOAD_XD_DOC_NASTR_TO] TO PUBLIC

GO




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

GO

CREATE    procedure [dbo].SALARY_REP_FUR1 @LINK int
AS 

select * into #CurDoc from  dbo.DOCUMENTS_ADD_FUR where link = @LINK
----

declare @ref_empl int
set @ref_empl = (select top 1 ref_empl from dbo.DOCUMENTS_ADD_FUR where link = @LINK)

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 = @LINK order by YEAR(SD.PERIOD),MONTH(SD.PERIOD)

--Для расчета по постановлению 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 = @LINK

select *, date1 = dbo.ConvertDMY2Date(1, YM % 100, YM / 100), date2 = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1, YM % 100, YM / 100))  
into #Temp from dbo.DOCUMENTS_ADD_FUR_TABLE T INNER JOIN #NUMERATOR N ON T.[MONTH] = N.M AND T.[YEAR] = N.Y 
where link = @LINK order by N.NUM

----
IF @instr = 2 --Поставить рабочие дние за периоды 
	update #Temp
	set [DAY] = dbo.WORKDAYS_DH(@link_empl, date1, date2, DEFAULT)
----
select 	d.num_arhe as doc_num, 
		[date1] = d.PER_ARHE, 
		[subdiv] = EP.SUBDIV_NAME,
		[sub_code] = EP.subdiv_code,
		INN = de.INN,
		KPP = de.KPP,
		[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] = OV.PERIOD_BEGIN,
		[DATE_PER2] = OV.PERIOD_END,
		[DATE_V1] = OV.[DATE_BEGIN],
		[DATE_V2] = OV.[DATE_END],
		[DAYS1] = (Case when ov.begin_vacation =  ov.date_begin and ov.HOLIDAY is not null
					then (DBO.W_DAYS(7, ov.[DATE_BEGIN], ov.[DATE_END]))
				    when ov.begin_vacation =  ov.date_begin and ov.HOLIDAY is null
					then (DBO.W_DAYS(7, ov.[DATE_BEGIN], ov.[DATE_END]) + dbo.SA_HOLIDAY_COUNT_FN(ov.[DATE_BEGIN], ov.[DATE_END]))
				else NULL end), -- если вид отпуска без учета праздников , то праздничные дни прибавляем к отпуску
		[DAYS2] = (Case when ov.begin_vacation <>  ov.date_begin
					then DBO.W_DAYS(7, ov.[DATE_BEGIN], ov.[DATE_END])
				else NULL end),

		[DAYS3] = (Case when ov.HOLIDAY is null
					then (DBO.W_DAYS(7, ov.[DATE_BEGIN], ov.[DATE_END]) + dbo.SA_HOLIDAY_COUNT_FN(ov.[DATE_BEGIN], ov.[DATE_END]))
				else (DBO.W_DAYS(7, ov.[DATE_BEGIN], ov.[DATE_END])) end),  -- если вид отпуска без учета праздников , то праздничные дни прибавляем к отпуску
 
		[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 T where NUM = 1),0),
		[sm1] 		= isnull((CASE WHEN @instr = 1 THEN (select SUM(coalesce(summa,0)+coalesce(summa_prem,0) + coalesce(mater,0)) from #Temp where NUM = 1) ELSE NULL END),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((CASE WHEN @instr = 1 THEN (select SUM(coalesce(summa,0)+coalesce(summa_prem,0) + coalesce(mater,0)) from #Temp where NUM = 2) ELSE NULL END),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((CASE WHEN @instr = 1 THEN (select SUM(coalesce(summa,0)+coalesce(summa_prem,0) + coalesce(mater,0)) from #Temp where NUM = 3) ELSE NULL END),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((CASE WHEN @instr = 1 THEN (select SUM(coalesce(summa,0)+coalesce(summa_prem,0) + coalesce(mater,0)) from #Temp where NUM = 4) ELSE NULL END),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((CASE WHEN @instr = 1 THEN (select SUM(coalesce(summa,0)+coalesce(summa_prem,0) + coalesce(mater,0)) from #Temp where NUM = 5) ELSE NULL END),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((CASE WHEN @instr = 1 THEN (select SUM(coalesce(summa,0)+coalesce(summa_prem,0) + coalesce(mater,0)) from #Temp where NUM = 6) ELSE NULL END),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((CASE WHEN @instr = 1 THEN (select SUM(coalesce(summa,0)+coalesce(summa_prem,0) + coalesce(mater,0)) from #Temp where NUM = 7) ELSE NULL END),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((CASE WHEN @instr = 1 THEN (select SUM(coalesce(summa,0)+coalesce(summa_prem,0) + coalesce(mater,0)) from #Temp where NUM = 8) ELSE NULL END),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((CASE WHEN @instr = 1 THEN (select SUM(coalesce(summa,0)+coalesce(summa_prem,0) + coalesce(mater,0)) from #Temp where NUM = 9) ELSE NULL END),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((CASE WHEN @instr = 1 THEN (select SUM(coalesce(summa,0)+coalesce(summa_prem,0) + coalesce(mater,0)) from #Temp where NUM = 10) ELSE NULL END),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((CASE WHEN @instr = 1 THEN (select SUM(coalesce(summa,0)+coalesce(summa_prem,0) + coalesce(mater,0)) from #Temp where NUM = 11) ELSE NULL END),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((CASE WHEN @instr = 1 THEN (select SUM(coalesce(summa,0)+coalesce(summa_prem,0) + coalesce(mater,0)) from #Temp where NUM = 12) ELSE NULL END),0),

		[sm_all]	= isnull((CASE WHEN @instr = 1 THEN (select SUM((coalesce(summa,0)+coalesce(summa_prem,0) + coalesce(mater,0))) from #Temp where NUM between 1 and 12) ELSE NULL END),0),
		[DAY_all]	= isnull(RP_DAYS,0),
		D.[NUMBER],
		D.[DATE]
into #V1
FROM 
	dbo.DOCUMENTS_ADD_FUR D
	inner join dbo.KU_EMPL_PLACING EP on D.REF_EMPL = EP.LINK
	inner join dbo.VACATION_ex ov on OV.LINK = D.REF_ARHE
	left join dbo.departments de on de.LINK = D.LINK_DEP 
where 
	D.LINK =@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 = @LINK --AND NUM BETWEEN 1 AND 12
GROUP BY	[MONTH], [YEAR], [DAY], [HOUR], DAY01, HOUR01, KOEF, NUM, Y, M
ORDER BY 	Y, M

----
select  
	ref, 
	[acc_code],
	[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 
	(
	SELECT 
		[REF]		= SD.LINK_PAY,
		[acc_code] = 
			(
				SELECT TOP 1
					(case when (ISNULL(CONVERT(VARCHAR(1),F.[SOURCE]),'') <> '') then (CONVERT(VARCHAR(1),F.[SOURCE]) + '.') else '' end + rtrim([cSinth]) + case when ([cAnalit] <> '') then ('.' + [cAnalit]) else '' end)
				FROM
					dbo.G_PROV1 G1
					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 AND GAP.DB_KR = 1
					INNER JOIN dbo.S_ACCOUNTS SA ON SA.LINK = GAP.ACCOUNT
				WHERE
					G1.LINK = P.LINK_OPER	
			),	
		[KSUMMA1]		= round(SD.SUMMA1 * coalesce(SD.KOEF1,0),4),
		[KSUMMA2]		= round(SD.SUMMA2 * coalesce(SD.KOEF2,0),4),
		[KSUMMA3]		= round(SD.SUMMA3 * coalesce(SD.KOEF3,0),4),
		[KSUMMA4]		= round(SD.SUMMA4 * coalesce(SD.KOEF4,0),4),
		[KSUMMA5]		= round(SD.SUMMA5 * coalesce(SD.KOEF5,0),4),
		[KSUMMA6]		= round(SD.SUMMA6 * coalesce(SD.KOEF6,0),4),
		[KSUMMA7]		= round(SD.SUMMA7 * coalesce(SD.KOEF7,0),4),
		[KSUMMA8]		= round(SD.SUMMA8 * coalesce(SD.KOEF8,0),4),
		[KSUMMA9]		= round(SD.SUMMA9 * coalesce(SD.KOEF9,0),4),
		[KSUMMA10]		= round(SD.SUMMA10 * coalesce(SD.KOEF10,0),4),
		[KSUMMA11]		= round(SD.SUMMA11 * coalesce(SD.KOEF11,0),4),
		[KSUMMA12]		= round(SD.SUMMA12 * coalesce(SD.KOEF12,0),4)
	FROM 	
		dbo.SDOC_AVAC_TABLE3 SD
		INNER JOIN dbo.PAYS P ON P.LINK = SD.LINK_PAY
		INNER JOIN dbo.SAL_SFIN F ON F.LINK = SD.LINK_KBK
	WHERE
		SD.LINK_UP = @LINK		
	) t1, #Tem T2

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 TOP 1 
					(case when (ISNULL(CONVERT(VARCHAR(1),F.[SOURCE]),'') <> '') then (CONVERT(VARCHAR(1),F.[SOURCE]) + '.') else '' end + rtrim([cSinth]) + case when ([cAnalit] <> '') then ('.' + [cAnalit]) else '' end)
				FROM
					dbo.PAYS PS
					INNER JOIN dbo.G_PROV1 G1 ON G1.LINK = PS.LINK_OPER
					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 AND GAP.DB_KR = 1
					INNER JOIN dbo.S_ACCOUNTS SA ON SA.LINK = GAP.ACCOUNT
				WHERE
					PS.LINK = P.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
		INNER JOIN dbo.SAL_SFIN F ON F.LINK = P.LINK_KBK
	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.%' 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= @LINK )
Set @CurYM = (select min(Year(DATE) * 100 + month(DATE)) from #CurDoc where link= @LINK )

---
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(10), 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 = @LINK and Year(DATE1) * 100 + month(DATE1) = @CurYM ) ,
[sm_m2] = (select sum(summa) from DOCUMENTS_ADD_FUR_TABLE0 where link = @LINK and Year(DATE1) * 100 + month(DATE1) <> @CurYM),
[sm_d1] = (select top 1 [DAY] from DOCUMENTS_ADD_FUR_TABLE0 where link = @LINK and Year(DATE1) * 100 + month(DATE1) = @CurYM ) ,
[sm_d2] = (select sum( distinct [DAY]) from DOCUMENTS_ADD_FUR_TABLE0 where link = @LINK 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 @acct1 VARCHAR(20), @acct2 VARCHAR(20), @acct3 VARCHAR(20)
SELECT 
	@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)



--В ТАБЛИЦЕ НАЧИСЛЕНИЯ ЗА ОТПУСК ПО ПЕРИОДАМ И ВИДАМ ФО
CREATE TABLE #AVAC_SUM (CURRENT_MONTH TINYINT, SRC TINYINT, SUMMA NUMERIC(18,2))
INSERT INTO #AVAC_SUM (CURRENT_MONTH, SRC, SUMMA)
SELECT 
	CURRENT_MONTH = CASE WHEN YEAR(D.[DATE]) = YEAR(T1.DATE1) AND MONTH(D.[DATE]) = MONTH(T1.DATE1) THEN 1 ELSE 0 END, 
	F.[SOURCE], 
	SUMMA = SUM(T1.SUMMA)
FROM 	
	dbo.SDOC D
	INNER JOIN dbo.SDOC_AVAC_TABLE1 T1 ON D.LINK = T1.LINK_UP
	INNER JOIN dbo.SAL_SFIN F ON F.LINK = T1.LINK_KBK
WHERE
	D.LINK = @LINK	
GROUP BY
	CASE WHEN YEAR(D.[DATE]) = YEAR(T1.DATE1) AND MONTH(D.[DATE]) = MONTH(T1.DATE1) THEN 1 ELSE 0 END,
	F.[SOURCE]	


----
declare @sm_all numeric(20,2), @sr_mes numeric(20,4), @sr_d numeric(20,4), @sm_m1 numeric(20,2), @sm_m2 numeric(20,2)
declare @sum_d1 numeric(18,2), @sum_d2 numeric(18,2)
--select top 1 @sr_mes = isnull(sr_mes, 0), @sr_d = isnull(sr_d, 0), @sm_m1 = isnull(sm_m1, 0), @sm_m2 = isnull(sm_m2, 0) from #v2 set @sr_mes = coalesce((select top 1 sr_mes from #v2),0)

--Вычисление среднемесячного заработка. Для 922 постановления Итого за расчетные мес / 12, по 562 не надо делить
set @sr_mes = coalesce((select SUM(coalesce(summa,0)+coalesce(summa_prem,0) + coalesce(mater,0)) from #Temp),0)
IF @INSTR = 1 
BEGIN
	IF (select COUNT(ORDERS) from #Temp) > 0
		set @sr_mes = COALESCE(@sr_mes,0) / (select COUNT(ORDERS) from #Temp)
END
---
set @sr_d = coalesce((select top 1 sr_d from #v2),0)
set @sm_m1 = ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE CURRENT_MONTH = 1),0)
set @sm_m2 = ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE CURRENT_MONTH = 0),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 @sm_all = sum(sm1+sm2+sm3) from #v2
Set @sm_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 @sm_all = 0 THEN 0.00 ELSE @sr_mes * sum(sm1)/@sm_all END,
	CASE WHEN @sm_all = 0 THEN 0.00 ELSE @sr_mes * sum(sm2)/@sm_all END,
	CASE WHEN @sm_all = 0 THEN 0.00 ELSE @sr_mes * sum(sm3)/@sm_all END,
	@acct1, @acct2, @acct3,
	@sr_mes, @sr_d, @sm_m1, @sm_m2,
	@sr_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 @sm_all = 0 THEN 0.00 ELSE @sr_d * sum(sm1)/@sm_all END,
	CASE WHEN @sm_all = 0 THEN 0.00 ELSE @sr_d * sum(sm2)/@sm_all END,
	CASE WHEN @sm_all = 0 THEN 0.00 ELSE @sr_d * sum(sm3)/@sm_all END,
	@acct1, @acct2, @acct3,
	@sr_d, @sr_d, @sm_m1, @sm_m2,
	@sr_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,
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE CURRENT_MONTH = 1 AND SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 1)),0),
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE CURRENT_MONTH = 1 AND SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 2)),0),
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE CURRENT_MONTH = 1 AND SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 3)),0),
	@acct1, @acct2, @acct3, @sr_d, @sr_d, 
	@sm_m1, 
	@sm_m2, 
	@sm_m1


--
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,
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE CURRENT_MONTH = 0 AND SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 1)),0),
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE CURRENT_MONTH = 0 AND SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 2)),0),
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE CURRENT_MONTH = 0 AND SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 3)),0),
	@acct1, @acct2, @acct3, @sr_d, @sr_d, 
	@sm_m1, 
	@sm_m2, 
	@sm_m2

--
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,
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 1)),0),
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 2)),0),
	ISNULL((SELECT SUM(SUMMA) FROM #AVAC_SUM WHERE SRC = ( select top 1 left(a.acc_code,1 ) from #T1 A inner JOIN #ACC_CODE B ON LEFT(a.acc_code,6) = b.acc_c where b.id = 3)),0),	
	@acct1, @acct2, @acct3,
	@sr_d, @sr_d,
	@sm_m1, 
	@sm_m2, 
	@sm_m1 + @sm_m2	 

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, @acct2, @acct3,
	0, 0, 0, 0,
	SUM(summa)
from 
	dbo.CALCULATE_JURNAL J 
	INNER JOIN dbo.PAYS P ON J.LINK_PAYS = P.LINK
	left join
	(select distinct G1.link, A.code
		from 
		dbo.g_prov1 g1
		inner join dbo.G_PROV2 G2 on G2.LINK_UP = G1.link 
		inner join dbo.g_prov_ap G on G.link_up = G2.link and G.db_kr = 1
		inner join dbo.s_accounts A on A.link = G.account
	) PA on P.link_oper = PA.link
	INNER JOIN #ACC_CODE c ON c.acc_c = LEFT(PA.CODE,6)	
where 
	J.LINK_EMPL = @ref_empl and MONTH(J.PERIOD_BEGIN) = @CurYM%100 and YEAR(J.PERIOD_BEGIN) = @CurYM/100 and P.[OBJECT] = 1
	and LINK_DOC <> @LINK


----
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, @acct2, @acct3,
	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], sf.CODE AS ACC_CODE
into #t9
from s_j_c , #D1 D1 , SAL_SFIN  sf 
where link_empl = @ref_empl and month_begin = d1.[month] and year_begin = [year] and typ_oper = 2 AND sf.LINK =  link_vkr AND WAY_CALC IN (4,5,6)
group by D1.code,link_pays,name_pays,code_pays, [month], [year], WAY_CALC,sf.CODE


--Список счетов по ндфл
create table #ACC_CODE_NDFL (id int identity(1,1), acc_c varchar(20))
insert into #ACC_CODE_NDFL (acc_c)
SELECT DISTINCT LEFT(acc_code,20) FROM #t9 ORDER BY LEFT(acc_code,20)


---- Удержания
--выделим отдельно удержания по НДФЛ
select 	D1.code AS CODE1,
		sm_N_1 = isnull((select SUM(sm1) from #T9 A INNER JOIN #ACC_CODE_NDFL B ON LEFT(a.ACC_CODE,20) = b.acc_c where b.id = 1 /*and acc_c =sf.CODE*/ AND  a.[month] = d1.[month] AND a.[year] = d1.[year] /*AND a.LINK_PAYS = s_j_c.link_pays*/),0),
		sm_N_2 = isnull((select SUM(sm1) from #T9 A INNER JOIN #ACC_CODE_NDFL B ON LEFT(a.ACC_CODE,20) = b.acc_c where b.id = 2 /*and acc_c =sf.CODE*/ AND  a.[month] = d1.[month] AND a.[year] = d1.[year] /*AND a.LINK_PAYS = s_j_c.link_pays*/),0),
		sm_N_3 = isnull((select SUM(sm1) from #T9 A INNER JOIN #ACC_CODE_NDFL B ON LEFT(a.ACC_CODE,20) = b.acc_c where b.id = 3 /*and acc_c =sf.CODE*/ AND a.[month] = d1.[month] AND a.[year] = d1.[year] /*AND a.LINK_PAYS = s_j_c.link_pays*/),0),
		[accU1] = ISNULL((SELECT TOP 1 acc_code FROM #T9 A INNER JOIN #ACC_CODE_NDFL B ON LEFT(a.acc_code,20) = b.acc_c where b.id = 1 /*AND a.[month] = d1.[month] AND a.[year] = d1.[year]*/ /*AND a.LINK_PAYS = s_j_c.link_pays*/),''),
		[accU2] = ISNULL((SELECT TOP 1 acc_code FROM #T9 A INNER JOIN #ACC_CODE_NDFL B ON LEFT(a.acc_code,20) = b.acc_c where b.id = 2 /*AND a.[month] = d1.[month] AND a.[year] = d1.[year]*/ /*AND a.LINK_PAYS = s_j_c.link_pays*/),''),
		[accU3] = ISNULL((SELECT TOP 1 acc_code FROM #T9 A INNER JOIN #ACC_CODE_NDFL B ON LEFT(a.acc_code,20) = b.acc_c where b.id = 3 /*AND a.[month] = d1.[month] AND a.[year] = d1.[year]*/ /*AND a.LINK_PAYS = s_j_c.link_pays*/),''),
		sum(summa) as sm1, 
	    link_pays, 
	    name_pays AS NP, 
	    code_pays AS CP, 
	    [month], 
	    [year], 
	    ndfl = CASE WHEN WAY_CALC IN (4,5,6) THEN 1 ELSE 0 END -- , 
	    --sf.CODE AS ACC_CODE
into #t10
from s_j_c S LEFT JOIN #D1 D1 ON 1=1  LEFT JOIN SAL_SFIN  sf  ON sf.LINK =  link_vkr
where link_empl = @ref_empl and month_begin = d1.[month] and year_begin = [year] and typ_oper = 2 --AND sf.LINK =  link_vkr
group by D1.code,link_pays,name_pays,code_pays, [month], [year], WAY_CALC--,sf.CODE

--- Удержания за текущий

insert into #t10
SELECT distinct convert(varchar(2),@M+7) AS CODE1 ,
		sm_N_1 = isnull((SELECT distinct SUM(summa) from s_j_c JJ left JOIN dbo.SAL_SFIN  sf1 ON  sf1.LINK =  jJ.link_vkr INNER JOIN #ACC_CODE_NDFL B ON LEFT(SF1.CODE,20) = b.acc_c  where b.id = 1 AND  JJ.month_begin = @CurYM%100 AND JJ.year_begin = @CurYM/100  AND JJ.link_empl = J.link_empl AND JJ.typ_oper = 2 AND JJ.WAY_CALC IN (4,5,6) /*AND a.LINK_PAYS = j.link_pays*/),0),
		sm_N_2 = isnull((SELECT distinct SUM(summa) from s_j_c JJ left JOIN dbo.SAL_SFIN  sf1 ON  sf1.LINK =  jJ.link_vkr INNER JOIN #ACC_CODE_NDFL B ON LEFT(SF1.CODE,20) = b.acc_c  where b.id = 2 AND  JJ.month_begin = @CurYM%100 AND JJ.year_begin = @CurYM/100  AND JJ.link_empl = J.link_empl AND JJ.typ_oper = 2 AND JJ.WAY_CALC IN (4,5,6) /*AND a.LINK_PAYS = j.link_pays*/),0),
		sm_N_3 = isnull((SELECT distinct SUM(summa) from s_j_c JJ left JOIN dbo.SAL_SFIN  sf1 ON  sf1.LINK =  jJ.link_vkr INNER JOIN #ACC_CODE_NDFL B ON LEFT(SF1.CODE,20) = b.acc_c  where b.id = 3 AND  JJ.month_begin = @CurYM%100 AND JJ.year_begin = @CurYM/100  AND JJ.link_empl = J.link_empl AND JJ.typ_oper = 2 AND JJ.WAY_CALC IN (4,5,6) /*AND a.LINK_PAYS = j.link_pays*/),0),
		[accU1] = ISNULL((SELECT TOP 1 LEFT(SF1.CODE,20) from s_j_c JJ left JOIN dbo.SAL_SFIN  sf1 ON  sf1.LINK =  jJ.link_vkr INNER JOIN #ACC_CODE_NDFL B ON LEFT(SF1.CODE,20) = b.acc_c  where b.id = 1 AND  JJ.month_begin = @CurYM%100 AND JJ.year_begin = @CurYM/100  AND JJ.link_empl = J.link_empl AND JJ.typ_oper = 2 AND JJ.WAY_CALC IN (4,5,6)   /*AND a.LINK_PAYS = j.link_pays*/),''),
		[accU2] = ISNULL((SELECT TOP 1 LEFT(SF1.CODE,20) from s_j_c JJ left JOIN dbo.SAL_SFIN  sf1 ON  sf1.LINK =  jJ.link_vkr INNER JOIN #ACC_CODE_NDFL B ON LEFT(SF1.CODE,20) = b.acc_c  where b.id = 2 AND  JJ.month_begin = @CurYM%100 AND JJ.year_begin = @CurYM/100  AND JJ.link_empl = J.link_empl AND JJ.typ_oper = 2 AND JJ.WAY_CALC IN (4,5,6)  /*AND a.LINK_PAYS = j.link_pays*/),''),
		[accU3] = ISNULL((SELECT TOP 1 LEFT(SF1.CODE,20) from s_j_c JJ left JOIN dbo.SAL_SFIN  sf1 ON  sf1.LINK =  jJ.link_vkr INNER JOIN #ACC_CODE_NDFL B ON LEFT(SF1.CODE,20) = b.acc_c  where b.id = 3 AND  JJ.month_begin = @CurYM%100 AND JJ.year_begin = @CurYM/100  AND JJ.link_empl = J.link_empl AND JJ.typ_oper = 2 AND JJ.WAY_CALC IN (4,5,6)  /*AND a.LINK_PAYS = j.link_pays*/),''),
		sum(summa) as sm1, link_pays, name_pays AS NP, code_pays AS CP, @CurYM%100 as [month], @CurYM/100 as [year], ndfl = CASE WHEN WAY_CALC IN (4,5,6) THEN 1 ELSE 0 END -- , sf.CODE AS ACC_CODE
  from dbo.s_j_c j 
	left JOIN dbo.SAL_SFIN  sf ON  sf.LINK =  j.link_vkr
where link_empl = @ref_empl  and month_begin = @CurYM%100 and year_begin = @CurYM/100 and typ_oper = 2
group by link_empl,link_pays ,name_pays,code_pays,WAY_CALC--,sf.CODE


------ Итого удержано
insert into #t10
Select convert(varchar(2),@M+8) as code1, 
	   sum(sm_N_1),
	   sum(sm_N_2) ,
	   sum(sm_N_3) ,
	   [accU1] ,
	   [accU2] ,
	   [accU3] ,
		sum(sm1), link_pays, np, cp, [month], [year], ndfl 
from #t10 where code1 = convert(varchar(2),@M+7) 
GROUP BY [accU1],[accU2],[accU3],link_pays,np, cp, [month], [year], ndfl 

----
-- Удержания по НДФЛ оставляем статичными 

select code1 as code2, sum(sm_n_1) AS sm_n1_all , sum(sm_n_2) AS sm_n2_all, sum(sm_n_3) AS sm_n3_all, sum(sm1) as sm_all ,[accU1] AS [accUN1],[accU2] AS [accUN2],[accU3] AS  [accUN3]   into #t11 from #t10 WHERE ndfl = 1 group by code1 ,[accU1],[accU2],[accU3]

DELETE FROM #t10 WHERE ndfl = 1   -- удаляем удержания по ндфл из таблицы удержаний, которые будут идти по порядку динамически, НДФЛ будет статичным

DECLARE @COUNT_U int, @COUNT_U_NDFL INT 

SET @COUNT_U = (SELECT COUNT(CODE1) FROM #t10 WHERE CODE1 <19)
SET @COUNT_U_NDFL = (SELECT COUNT(CODE2) FROM #T11 WHERE CODE2 <19)

----
DECLARE @Table_Name VARCHAR(100), @table1 VARCHAR(100)
EXEC X_GET_TABLE_NAME @Table_Name OUTPUT
EXEC X_GET_TABLE_NAME @table1 OUTPUT
EXEC M_CROSS_TABLE 
	'CODE1, MONTH, YEAR , sm_n_1, sm_n_2, sm_n_3,accU1,accU2,accU3',
	'CP, NP',
	'VARCHAR(10)#VARCHAR(254)',
	'SM1', 'NUMERIC(20,2)', 'SUM(SM1) AS SM1',
	#t10,
	@Table_Name

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

EXEC ('alter table ' + @table1 + '  add [sm_U_all] numeric(20,2) default 0.00 ')

EXEC('UPDATE  TT
		SET  CODE1 = (CASE WHEN '+ @COUNT_U +' <  '+ @COUNT_U_NDFL +'  then T1.code2  else T.code1 end ),
			MONTH = (CASE WHEN '+ @COUNT_U +' <  '+ @COUNT_U_NDFL +'  then (select top 1 month FROM #D1 where code = T1.code2 ) else T.MONTH end ),
			YEAR = (CASE WHEN '+ @COUNT_U +' <  '+ @COUNT_U_NDFL +'  then (select top 1 YEAR FROM #D1 where code = T1.code2 ) else T.YEAR end ),
		    accU1 = (CASE WHEN '+ @COUNT_U +' <  '+ @COUNT_U_NDFL +'  then T1.accUN1  else T.accU1 end ),
			accU2 = (CASE WHEN '+ @COUNT_U +' <  '+ @COUNT_U_NDFL +'  then T1.accUN2  else T.accU2 end ), 
			accU3 = (CASE WHEN '+ @COUNT_U +' <  '+ @COUNT_U_NDFL +'  then T1.accUN3  else T.accU3 end )
	  FROM  ' + @table1 + ' TT 
			left join #T11 T1 on  TT.CODE = T1.CODE2
			LEFT  JOIN ' + @Table_Name + ' T ON TT.CODE = T.CODE1 '	)

EXEC('UPDATE  TT
		SET  sm_U_all = ISNULL(T1.SM1,0)
	  FROM  ' + @table1 + ' TT 
			left join  (SELECT TA.CODE1 , sum(TA.SM1) AS sm1 FROM ' + @table1 + ' Tb 
			left join #T10 Ta on  Tb.CODE = Ta.CODE1   group by Ta.CODE1 ) T1 on  TT.CODE = T1.CODE1')




DECLARE @CODE_CNT INT, @DELTA INT, @I INT, @SQL_STR VARCHAR(8000)
SET @CODE_CNT = (SELECT COUNT(DISTINCT CP) FROM #t10 )
SET @DELTA = CASE WHEN @CODE_CNT = 0 THEN 1 ELSE 0 END

IF @DELTA > 0 BEGIN
	SET @I=1
	WHILE @I<=@DELTA BEGIN
		SET @SQL_STR= 'ALTER TABLE '  + @table1 + '  ADD CP_' + LTRIM(STR(@CODE_CNT+@I)) + '  VARCHAR(10) DEFAULT '''', NP_' + LTRIM(STR(@CODE_CNT+@I)) + '_' + LTRIM(STR(@CODE_CNT+@I)) + ' VARCHAR(254) DEFAULT '''', SM1_'
		+  LTRIM(STR(@CODE_CNT+@I)) + '_' + LTRIM(STR(@CODE_CNT+@I)) + '  NUMERIC(20,2) DEFAULT 0'
		EXEC (@SQL_STR)
		SET @I=@I+1
	END
END

DECLARE @FIELD_NAME VARCHAR(254)
SET @I = 1
SET @CODE_CNT = CASE WHEN @CODE_CNT < @DELTA THEN @DELTA ELSE @CODE_CNT END
WHILE @I <=@CODE_CNT BEGIN
	SET @FIELD_NAME= 'CP_' + RTRIM(LTRIM(STR(@I))) 
	SET @SQL_STR= ' UPDATE ' + @table1 + '  SET ' + @FIELD_NAME+ ' = ISNULL((SELECT TOP 1 '+@FIELD_NAME+' FROM ' +@Table_Name + ' WHERE '+
			@FIELD_NAME+ '  IS NOT NULL ), '''') ' 

	EXEC (@SQL_STR)

	SET @FIELD_NAME= 'NP_' + RTRIM(LTRIM(STR(@I))) + '_' + + RTRIM(LTRIM(STR(@I))) 
	SET @SQL_STR= ' UPDATE ' + @table1 + '  SET ' + @FIELD_NAME+ ' = ISNULL((SELECT TOP 1 '+@FIELD_NAME+' FROM ' +@Table_Name + ' WHERE '+
			@FIELD_NAME+ '  IS NOT NULL ), '''') ' 

	EXEC (@SQL_STR)

	SET @FIELD_NAME= 'SM1_' + RTRIM(LTRIM(STR(@I))) + '_' + + RTRIM(LTRIM(STR(@I))) 
	SET @SQL_STR= ' UPDATE ' + @table1 + '  SET ' + @FIELD_NAME+ ' = 0 WHERE ' + @FIELD_NAME + ' IS NULL ' 

	EXEC (@SQL_STR)
	SET @I=@I+1
END

Declare @Script varchar(254)
EXEC('UPDATE ' + @table1 + ' SET SM_ALL = 0 WHERE SM_ALL IS NULL')
set @Script = 'SELECT * FROM ' + @table1 + ' WHERE CODE <= ''' + convert(varchar(2),@M) + ''' ORDER BY CODE'
EXEC (@Script)
Set @Script = 'SELECT * FROM ' + @table1 + ' WHERE CODE > ''' + convert(varchar(2),@M) + ''' ORDER BY CODE'
EXEC (@Script)

Set @Script = 'SELECT CASE WHEN COALESCE(sm_all0,0) > (COALESCE(sm_all,0) + COALESCE(sm_U_all,0)) then  COALESCE(sm_all0,0) - (COALESCE(sm_all,0) + COALESCE(sm_U_all,0)) else 0 end as sm_all0 FROM ' + @table1 + ' WHERE CODE = ''' + convert(varchar(2),@M+8) + ''' ORDER BY CODE'
EXEC (@Script)
EXEC('DROP TABLE ' + @Table_Name)
EXEC('DROP TABLE ' + @table1)










GO


GRANT EXECUTE ON dbo.[SALARY_REP_FUR1] TO PUBLIC

GO



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

GO

CREATE PROCEDURE [dbo].SD_EMPL_SUM_VKR

	@varKSSumma numeric(15,2) output,
	@varKSnTypPay int =1,   
	@varKSnLinkEmpl int,
	@varKSdDate1 datetime	= 0,
	@varKSdDate2 datetime	= 0,
	@varKSLinkVKR int	= 0,
	@grop_ekr tinyint = 0,
	@LINK_EKR INT = 0
AS

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

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


-- Ведомости на выплату зарплаты учитываем по периоду выплаты
CREATE TABLE #VEDOM_ZP (LINK INT)
INSERT INTO #VEDOM_ZP (LINK)
	Select link_up from dbo.SDOC_VEDOM where TYP_PAYMENT = 1
	union all
	Select link_up from dbo.SDOC_VEDOM_DGH where TYP_PAYMENT = 1

---
SELECT 
	@varKSSumma = SUM(SUMMA) 
FROM 
	DBO.CALCULATE_JURNAL JC
	INNER JOIN DBO.PAYS P ON JC.LINK_PAYS = P.LINK
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = 'R211') R211
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = '211') T211	
	LEFT JOIN #VEDOM_ZP A ON A.LINK = JC.LINK_DOC
WHERE 
	LINK_EMPL = @varKSnLinkEmpl 
	AND P.OBJECT = @varKSnTypPay
	AND 
	(
		COALESCE(A.LINK,0) = 0 AND JC.PERIOD_BEGIN >= @varKSdDate1 AND JC.PERIOD_END <= @varKSdDate2  
		OR --ДЛЯ ВЕДОМОСТЕЙ ОПЕРАЦИИ БЕРЕМ ПО ПЕРИОДУ РАСЧЕТА
		COALESCE(A.LINK,0) > 0 AND (JC.DATE_BEGIN >= @varKSdDate1 AND JC.DATE_BEGIN <= @varKSdDate2 OR JC.PERIOD_BEGIN >= @varKSdDate1 AND JC.PERIOD_END <= @varKSdDate2)
	)
	AND COALESCE(JC.SUMMA,0) <> 0  
	AND (JC.LINK_VKR = @varKSLinkVKR OR @varKSLinkVKR = 0)
	AND ( 
			(CASE WHEN R211.LINK = ISNULL(JC.LINK_EKR,P.LINK_EKR) THEN T211.LINK ELSE ISNULL(JC.LINK_EKR,P.LINK_EKR) END) = @LINK_EKR 
			OR 
			@LINK_EKR = 0
		)
	
---
SELECT 
	[REF_PAY] = P.LINK, 
	[NAME_PAY] = P.NAME,
	[CODE_PAY] = P.CODE,
	[SUMMA] = SUM(COALESCE(JC.SUMMA,0)),
	[WAY]		 = P.OBJECT,
	LINK_EKR = (case when  @grop_ekr = 0 then 0 else DI.LINK end),
	EKR_CODE = (case when  @grop_ekr = 0 then '' else DI.CODE end),
	LINK_VKR,
	F.CODE as CODE_VKR
FROM 
	DBO.CALCULATE_JURNAL JC
	INNER JOIN DBO.PAYS P ON JC.LINK_PAYS = P.LINK
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = 'R211') R211
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = '211') T211	
	INNER JOIN dbo.KOSGU DI ON DI.LINK = (CASE WHEN R211.LINK = ISNULL(ISNULL(JC.LINK_EKR,P.LINK_EKR),@LinkEKR211) THEN T211.LINK ELSE ISNULL(ISNULL(JC.LINK_EKR,P.LINK_EKR),@LinkEKR211) END)
	LEFT JOIN dbo.SAL_SFIN F ON JC.LINK_VKR = F.LINK
	LEFT JOIN #VEDOM_ZP A ON A.LINK = JC.LINK_DOC
WHERE 
	LINK_EMPL = @varKSnLinkEmpl 
	AND P.OBJECT =@varKSnTypPay 
	AND COALESCE(JC.SUMMA,0) <> 0 
	AND 
	(
		COALESCE(A.LINK,0) = 0 AND JC.PERIOD_BEGIN >= @varKSdDate1 AND JC.PERIOD_END <= @varKSdDate2 
		OR --ДЛЯ ВЕДОМОСТЕЙ ОПЕРАЦИИ БЕРЕМ ПО ПЕРИОДУ РАСЧЕТА
		COALESCE(A.LINK,0) > 0 AND (JC.DATE_BEGIN >= @varKSdDate1 AND JC.DATE_BEGIN <= @varKSdDate2 OR JC.PERIOD_BEGIN >= @varKSdDate1 AND JC.PERIOD_END <= @varKSdDate2)
	)   
	AND (JC.LINK_VKR = @varKSLinkVKR OR @varKSLinkVKR = 0)
	AND ( DI.LINK = @LINK_EKR OR @LINK_EKR = 0)
GROUP BY 
	P.LINK, P.NAME, P.CODE, P.OBJECT, JC.LINK_DOC,
	(case when  @grop_ekr = 0 then 0 else DI.LINK end),
	(case when  @grop_ekr = 0 then '' else DI.CODE end), LINK_VKR, F.CODE



GO


GRANT EXECUTE ON dbo.[SD_EMPL_SUM_VKR] TO PUBLIC

GO

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

CREATE PROCEDURE dbo.RMS_RECEIVEMESSAGE
  @msgLink int = null output
AS
BEGIN
	SET NOCOUNT ON

	if object_id('[dbo].[sys_events_rms]') is not null
		INSERT[dbo].[SYS_EVENTS_RMS](LINK_MSG, GUID, DIRECTION, TYPE, NAME, SUBJECT, DATETIME, SENDER, RECIPIENTS, PRIORITY, STATUS, STATUS_DATE, STATUS_INFO)
		SELECT LINK, GUID, DIRECTION, TYPE, NAME, SUBJECT, DATE_TIME, SENDER, RECIPIENTS, PRIORITY, STATUS, STATUS_DATE, convert(nvarchar(4000), left(STATUS_INFO,4000))
		FROM dbo.rms_messages where link = @msgLink

	DECLARE @subject varchar(254) 
	SELECT @subject = subject from dbo.rms_messages where link = @msgLink

	IF upper(@subject) like upper('SMETA_SMART')
	begin
		execute [dbo].[SMETA_SMART_MESSAGE_HANDLER] @msgLink = @msgLink OUTPUT
		if object_id('dbo.events_rms_set_processed') is not null exec [dbo].[events_rms_set_processed] @nLink = @msgLink
	end
END
GO

GRANT EXECUTE ON dbo.[RMS_RECEIVEMESSAGE] TO PUBLIC
GO
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[BK_REPORT_OSV_DEP_DEBET]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BK_REPORT_OSV_DEP_DEBET]

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

CREATE PROCEDURE dbo.BK_REPORT_OSV_DEP_DEBET
	@varKSdDate1	DATETIME	,
	@varKSdDate2	DATETIME	,
	@varKScVal1 char(1), @varKSnOtborLink1 int	,
	@varKScVal2 char(1), @varKSnOtborLink2 int	,
	@cVal_KBK char(1), @nOtborLinkKBK int,	-- Отбор КБК --
	@varKSPrnKBK INT				,
	@varKSPrnSGU INT				,

	@varKScOtborAccount	VARCHAR (100)		,
	@varKScOtborAccountAN	VARCHAR (100)		,
	@intTYPE_ORG		INT,
	@intSVOD_ZB		int,	 -- Сводный отчет (ЦБ) --
	@intREP_BY_OSNOV	INT = 0		-- Отчет в разрезе договоров --
AS
BEGIN
	DECLARE	@varKSDEP_LINK	INT,
		@varKSORGNAME	VARCHAR(254)

	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)	/* -- Сводный отчет по ЦБ -- */
	SET @varKSDEP_LINK = dbo.BK_GetDepZB ()
				
	IF @intSVOD_ZB = 1 OR @varKSDEP_LINK IS NULL		/* -- Сводный отчет по ЦБ (собственные реквизиты организации) -- */
		SET @varKSDEP_LINK = dbo.GetOwnDepLink ()

	SELECT @varKSORGNAME = [NAME]
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @varKSDEP_LINK

	IF @intSVOD_ZB = 1
		SET @varKSORGNAME = RTRIM (@varKSORGNAME) + ' (ЦБ)'

	DECLARE @ACCT TABLE (LINK_ACCT INT)
	IF LEN (@varKScVal1) > 0
		INSERT INTO @ACCT
		SELECT RECORD
		FROM dbo.OBJECT_VAR_ACCT
		WHERE LINK_UP = @varKSnOtborLink1
	ELSE
		INSERT INTO @ACCT
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode ('205', DEFAULT, DEFAULT, DEFAULT) ACCT

/*
SELECT SA.CODE, * FROM @ACCT, S_ACCOUNTS SA WHERE LINK_ACCT = SA.LINK
RETURN
*/
	DECLARE @DEP TABLE (LINK_DEP INT, DEP_CODE  VARCHAR(20), DEP_NAME VARCHAR(254) )
	IF LEN(@varKScVal2)>0 BEGIN
		INSERT INTO @DEP
		SELECT OVR.RECORD, D.CODE, D.[NAME]
		FROM dbo.OBJECT_VAR_DEPARTMENT OVR, dbo.DICTIONARY_DEPARTMENT D
		WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@varKSnOtborLink2
	END
	ELSE
	BEGIN
		INSERT INTO @DEP
		SELECT D.LINK, D.CODE, D.[NAME]
		FROM dbo.DICTIONARY_DEPARTMENT D
		WHERE (@intTYPE_ORG = 0)
			OR (@intTYPE_ORG <> 0 AND TYPE = @intTYPE_ORG)
		INSERT INTO @DEP VALUES (0, '', 'Не указан')
	END

	--- ОТБОР ПО КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	DECLARE @TABLE1 TABLE (DEP INT, ACCOUNT INT, 
			KBK INT, KOSGU INT,
			D_SUMMA NUMERIC (20,2), D_QTY NUMERIC (20,2),  
			K_SUMMA NUMERIC (20,2), K_QTY NUMERIC (20,2),  
			IN_SUMMA NUMERIC (20,2), IN_QTY NUMERIC (20,2),  	
			OUT_SUMMA NUMERIC (20,2), OUT_QTY NUMERIC (20,2))  	

	INSERT INTO @TABLE1
	SELECT T1.DEP,
		T1.ACCOUNT,
		CASE
			WHEN @varKSPrnKBK = 1 THEN T1.KBK
			ELSE 0
		END,
		CASE
			WHEN @varKSPrnSGU = 1 THEN T1.SGU
			ELSE 0
		END,
		SUM (T1.D_SUMMA), SUM (T1.D_QTY),
		SUM (T1.K_SUMMA), SUM (T1.K_QTY),
		SUM (T1.IN_SUMMA), SUM (T1.IN_QTY),
		SUM (T1.OUT_SUMMA), SUM (T1.OUT_QTY)
	FROM dbo.BK_GetTableOSVByDate (@varKSdDate1, @varKSdDate2, DEFAULT) T1
	INNER JOIN @TAB_KBK T2 ON (T2.LINK_KBK = T1.KBK)
	INNER JOIN @ACCT AC ON (AC.LINK_ACCT = T1.ACCOUNT)
	WHERE (@intSVOD_ZB = 1)
		OR (@intSVOD_ZB = 0 AND T1.DEP_LINK = @varKSDEP_LINK)
	GROUP BY  T1.DEP,
		T1.ACCOUNT,
		CASE
			WHEN @varKSPrnKBK = 1 THEN T1.KBK
			ELSE 0
		END,
		CASE
			WHEN @varKSPrnSGU = 1 THEN T1.SGU
			ELSE 0
		END

	DECLARE @RESULT TABLE (DEP INT, ACCOUNT INT, 
			DEP_CODE VARCHAR (20), DEP_NAME VARCHAR (254),
			ACCT_GR VARCHAR (30), ACCT_CODE VARCHAR (60),

			OSNOV_LINK INT, NUM_OSNOV	VARCHAR (30),
			DATE_OSNOV DATETIME, INF_OSNOV VARCHAR (254),

			D_SUM NUMERIC (20,2), D_QTY NUMERIC (20,2),	
			K_SUM NUMERIC (20,2), K_QTY NUMERIC (20,2),	
			DIN_SUM NUMERIC (20,2), DIN_QTY NUMERIC (20,2),		
			KIN_SUM NUMERIC (20,2), KIN_QTY NUMERIC (20,2),		
			DOUT_SUM NUMERIC (20,2), DOUT_QTY NUMERIC (20,2),	
			KOUT_SUM NUMERIC (20,2), KOUT_QTY NUMERIC (20,2),	
			ORGNAME VARCHAR (254),
			REP_HDR VARCHAR (254))

	INSERT INTO @RESULT
	SELECT OSV.DEP,
		OSV.ACCOUNT,
		DEP.DEP_CODE,
		DEP.DEP_NAME,
		SA.CODE,
		dbo.BK_GetAcctFullCode1 (OSV.ACCOUNT, OSV.KBK, OSV.KOSGU, @varKSPrnKBK, @varKSPrnSGU),

		0, '',
		NULL, '',

		OSV.D_SUMMA, OSV.D_QTY,
		OSV.K_SUMMA, OSV.K_QTY,
		CASE
			WHEN SA.S_ACTIVE  = 1 AND SA.S_PASSIVE = 0 THEN OSV.IN_SUMMA
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 1 AND SA.S_PASSIVE = 0 THEN OSV.IN_QTY
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 0 AND SA.S_PASSIVE = 1 THEN OSV.IN_SUMMA
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 0 AND SA.S_PASSIVE = 1 THEN OSV.IN_QTY
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 1 AND SA.S_PASSIVE = 0 THEN OSV.OUT_SUMMA
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 1 AND SA.S_PASSIVE = 0 THEN OSV.OUT_QTY
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 0 AND SA.S_PASSIVE = 1 THEN OSV.OUT_SUMMA
			ELSE 0
		END,
		CASE
			WHEN SA.S_ACTIVE  = 0 AND SA.S_PASSIVE = 1 THEN OSV.OUT_QTY
			ELSE 0
		END,
		@varKSORGNAME AS ORGNAME,
		'ПО РАСЧЕТАМ С ДЕБИТОРАМИ ПО ДОХОДАМ'
	FROM @TABLE1 OSV
	INNER JOIN @DEP DEP ON (DEP.LINK_DEP = OSV.DEP)
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = OSV.ACCOUNT)
	WHERE (OSV.D_SUMMA <> 0) OR (OSV.D_QTY<> 0)
		OR (OSV.K_SUMMA <> 0) OR (OSV.K_QTY <> 0)
		OR (OSV.IN_SUMMA <> 0) OR (OSV.IN_QTY <> 0)
		OR (OSV.OUT_SUMMA <> 0) OR (OSV.OUT_QTY <> 0)

	SELECT *,
		ISNULL (@intREP_BY_OSNOV, 0) AS BY_OSNOV
	FROM @RESULT
	ORDER BY DEP_CODE, DATE_OSNOV, NUM_OSNOV, OSNOV_LINK, ACCT_GR, ACCT_CODE
END


GO


GRANT EXECUTE ON dbo.[BK_REPORT_OSV_DEP_DEBET] TO PUBLIC

GO



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

GO
CREATE PROCEDURE [dbo].UNLOAD_SHABLON_DOCUMENTS_PROV (@NAME_OPER VARCHAR(254) = NULL, @MODE VARCHAR(3) = 'ADD', @NASTR_DOC INT = 0)
AS
/*
@NAME_OPER точное наименование типовой операции 
@MODE ADD - только на добавление новой Т/О, UPD - на добавление и изменение
@NASTR =1 выгружать привязку к документу и настройки на формирование проводок

UNLOAD_SHABLON_DOCUMENTS_PROV 'Начисление отпускных (компенсации) за счет резерва  (Дт401.60-Кт302.11)', @NASTR_DOC = 1

*/
BEGIN

SET NOCOUNT ON

IF OBJECT_ID('TEMPDB..#OUT') IS NOT NULL
	DROP TABLE #OUT

CREATE TABLE #OUT (ORD INT IDENTITY(1,1), TXT VARCHAR(8000), LINK INT)
INSERT INTO #OUT (TXT)
SELECT
'--Добавление системной типовой операции
--Сгенерировано скриптом: EXECUTE dbo.[UNLOAD_SHABLON_DOCUMENTS_PROV] @NAME_OPER = ' 
+ CASE WHEN @NAME_OPER IS NULL THEN 'NULL' ELSE '''' + LTRIM(RTRIM(@NAME_OPER)) + '''' END
+ ', @MODE = ' + CASE WHEN @MODE IS NULL THEN 'NULL' ELSE '''' + LTRIM(RTRIM(@MODE)) + '''' END
+ ', @NASTR_DOC = ' + CONVERT (VARCHAR (2), (@NASTR_DOC)) 


INSERT INTO #OUT (TXT)
SELECT
'
SET NOCOUNT ON

' + CHAR(13) + CHAR(10)

INSERT INTO #OUT (TXT)
SELECT
'IF OBJECT_ID(''TEMPDB..#tmp_G_PROV1'') IS NOT NULL
	DROP TABLE #tmp_G_PROV1
' + CHAR(13) + CHAR(10)
	
INSERT INTO #OUT (TXT)
SELECT
'
CREATE TABLE #tmp_G_PROV1 (
	[LINK] int ,
	[LINK_UP] int,
	[NAME_OPER] varchar(254),
	[ORDERS] int)
' + CHAR(13) + CHAR(10)

IF OBJECT_ID('TEMPDB..#G_PROV1_REC') IS NOT NULL
	DROP TABLE #G_PROV1_REC

CREATE TABLE #G_PROV1_REC (LINK INT)

INSERT INTO #OUT (TXT,LINK) OUTPUT INSERTED.LINK INTO #G_PROV1_REC (LINK)
SELECT 'INSERT INTO #tmp_G_PROV1 (LINK,LINK_UP,NAME_OPER,ORDERS) 
VALUES(' + CONVERT(VARCHAR(20),G1.LINK) 
+ ',' + CONVERT(VARCHAR(20),G1.LINK_UP)
+ ',''' + LTRIM(RTRIM(G1.NAME_OPER)) + ''''
+ ',' + CONVERT(VARCHAR(20),G1.ORDERS)
+ ')'+ CHAR(13) + CHAR(10) 
,G1.LINK

FROM 
	dbo.G_PROV G
	INNER JOIN dbo.S_OBJECTS SO ON SO.LINK = G.[OBJECT]
	INNER JOIN dbo.G_PROV1 G1 ON G1.LINK_UP = G.LINK
WHERE
	SO.[CODE] = 'SHABLON_DOCUMENTS_PROV'
	AND
	(@NAME_OPER IS NULL OR G1.NAME_OPER = @NAME_OPER)

---------------------------------------------------------------------------------------------------
INSERT INTO #OUT (TXT)
SELECT
'
IF OBJECT_ID(''TEMPDB..#tmp_G_PROV2'') IS NOT NULL
	DROP TABLE #tmp_G_PROV2
' + CHAR(13) + CHAR(10)

IF OBJECT_ID('TEMPDB..#G_PROV2_REC') IS NOT NULL
	DROP TABLE #G_PROV2_REC

CREATE TABLE #G_PROV2_REC (LINK INT)
	
INSERT INTO #OUT (TXT)
SELECT
'
CREATE TABLE #tmp_G_PROV2 (
	[LINK] int,
	[LINK_UP] int,
	[NAME] varchar(254),
	[ORDERS] smallint,
	XOG_CODE VARCHAR(2),
	XO_CODE VARCHAR(2),
	STORNO TINYINT)
' + CHAR(13) + CHAR(10) 

INSERT INTO #OUT (TXT,LINK) OUTPUT INSERTED.LINK INTO #G_PROV2_REC (LINK)
SELECT 'INSERT INTO #tmp_G_PROV2 (LINK,LINK_UP,NAME,ORDERS,XOG_CODE,XO_CODE,STORNO) 
VALUES(' + CONVERT(VARCHAR(20),G2.LINK) 
+ ',' + CONVERT(VARCHAR(20),G2.LINK_UP)
+ ',''' + LTRIM(RTRIM(G2.NAME)) + ''''
+ ',' + CONVERT(VARCHAR(20),ORDERS)
+ ', ' + CASE WHEN XOG_CODE IS NULL THEN 'NULL' ELSE '''' + LTRIM(RTRIM(XOG_CODE)) + '''' END
+ ', ' + CASE WHEN XO_CODE IS NULL THEN 'NULL' ELSE '''' + LTRIM(RTRIM(XO_CODE)) + '''' END
+ ', ' + CONVERT(VARCHAR(1),g2.STORNO)
+ ')'+ CHAR(13) + CHAR(10)
,G2.LINK
FROM
	#G_PROV1_REC T
	INNER JOIN dbo.G_PROV2 G2 ON G2.LINK_UP = T.LINK
	LEFT JOIN 
	(SELECT XO.LINK, XOG.CODE AS XOG_CODE, XO.CODE AS XO_CODE FROM [dbo].[XOZ_OPER] XO
		INNER JOIN [dbo].[XOZ_OPER_GROUP] XOG ON XO.GROUP_LINK = XOG.LINK) X ON G2.ECON_OPER = X.LINK

---------------------------------------------------------------------------------------------------------
INSERT INTO #OUT (TXT)
SELECT
'
IF OBJECT_ID(''TEMPDB..#tmp_G_PROV_AP'') IS NOT NULL
	DROP TABLE #tmp_G_PROV_AP
' + CHAR(13) + CHAR(10)

INSERT INTO #OUT (TXT)
SELECT
'
CREATE TABLE #tmp_G_PROV_AP (
	[LINK_UP] int,
	[DB_KR] tinyint,
	[ACCOUNT] VARCHAR(20),
	[EKR] VARCHAR(3),
	[SGU] VARCHAR(3))
' + CHAR(13) + CHAR(10)

INSERT INTO #OUT (TXT)
SELECT 'INSERT INTO #tmp_G_PROV_AP (LINK_UP, DB_KR, ACCOUNT, EKR, SGU)
VALUES(' + CONVERT(VARCHAR(20),GAP.LINK_UP) 
+ ',' + CONVERT(VARCHAR(20),GAP.DB_KR)
+ ',''' + LTRIM(RTRIM(A.CODE)) + ''''
+ ', ' + CASE WHEN T_EKR.CODE IS NULL THEN 'NULL' ELSE '''' + LTRIM(RTRIM(T_EKR.CODE)) + '''' END
+ ', ' + CASE WHEN T_SGU.CODE IS NULL THEN 'NULL' ELSE '''' + LTRIM(RTRIM(T_SGU.CODE)) + '''' END
+ ')'+ CHAR(13) + CHAR(10)
FROM
	#G_PROV2_REC T
	INNER JOIN dbo.G_PROV_AP GAP ON GAP.LINK_UP = T.LINK
	INNER JOIN [dbo].[S_ACCOUNTS] A ON GAP.ACCOUNT = A.LINK
	LEFT JOIN [dbo].[KOSGU] T_EKR ON GAP.EKR = T_EKR.LINK
	LEFT JOIN [dbo].[KOSGU] T_SGU ON GAP.SGU = T_SGU.LINK



INSERT INTO #OUT (TXT)
SELECT
'
IF COLUMNPROPERTY(object_id(''[dbo].[G_PROV1]''), ''LINK2'', ''AllowsNull'') is NOT NULL
   ALTER TABLE [dbo].[G_PROV1] DROP COLUMN [LINK2]
'

INSERT INTO #OUT (TXT)
SELECT
'
IF COLUMNPROPERTY(object_id(''[dbo].[G_PROV1]''), ''LINK2'', ''AllowsNull'') is NULL
   ALTER TABLE [dbo].[G_PROV1] ADD [LINK2] int
'

INSERT INTO #OUT (TXT)
SELECT
'GO'+ CHAR(13) + CHAR(10)

INSERT INTO #OUT (TXT)
SELECT
'
IF OBJECT_ID(''TEMPDB..#G_PROV1_REC'') IS NOT NULL
	DROP TABLE #G_PROV1_REC
'

INSERT INTO #OUT (TXT)
SELECT
'
CREATE TABLE #G_PROV1_REC (LINK1 INT, LINK2 INT)
'

INSERT INTO #OUT (TXT)
SELECT
'
INSERT INTO dbo.G_PROV1 (LINK_UP, NAME_OPER, ORDERS, LINK2)
OUTPUT INSERTED.LINK, INSERTED.LINK2 INTO #G_PROV1_REC (LINK1,LINK2)	
SELECT DISTINCT LINK_UP = T.LINK, TG1.NAME_OPER, TG1.ORDERS, LINK2 = TG1.LINK  
FROM
	#tmp_G_PROV1 TG1
	INNER JOIN (SELECT TOP 1 G.LINK FROM dbo.G_PROV G INNER JOIN dbo.S_OBJECTS SO ON SO.LINK = G.[OBJECT] 
					WHERE SO.[CODE] = ''SHABLON_DOCUMENTS_PROV'') T ON 1=1
WHERE
	NOT EXISTS (SELECT *
				FROM
					dbo.G_PROV1 G1
				WHERE
					RTRIM(LTRIM(G1.NAME_OPER)) = RTRIM(LTRIM(TG1.NAME_OPER)))
'

INSERT INTO #OUT (TXT)
SELECT
'
IF COLUMNPROPERTY(object_id(''[dbo].[G_PROV2]''), ''LINK2'', ''AllowsNull'') is NOT NULL
   ALTER TABLE [dbo].[G_PROV2] DROP COLUMN [LINK2]
'

INSERT INTO #OUT (TXT)
SELECT
'
IF COLUMNPROPERTY(object_id(''[dbo].[G_PROV2]''), ''LINK2'', ''AllowsNull'') is NULL
   ALTER TABLE [dbo].[G_PROV2] ADD [LINK2] int
'

INSERT INTO #OUT (TXT)
SELECT
'GO'+ CHAR(13) + CHAR(10)

INSERT INTO #OUT (TXT)
SELECT
'
IF OBJECT_ID(''TEMPDB..#G_PROV2_REC'') IS NOT NULL
	DROP TABLE #G_PROV2_REC
'

INSERT INTO #OUT (TXT)
SELECT
'
CREATE TABLE #G_PROV2_REC (LINK1 INT, LINK2 INT)
'

IF @MODE = 'UPD'
BEGIN
INSERT INTO #OUT (TXT)
SELECT
'
DELETE FROM dbo.G_PROV2 WHERE EXISTS (SELECT * FROM #G_PROV1_REC T WHERE T.LINK1 = dbo.G_PROV2.LINK_UP)
'
END

INSERT INTO #OUT (TXT)
SELECT
'
INSERT INTO dbo.G_PROV2 (LINK_UP, SUMMA, QUANTITY, STORNO, NAME, ORDERS, ECON_OPER, LINK2)
OUTPUT INSERTED.LINK, INSERTED.LINK2 INTO #G_PROV2_REC (LINK1,LINK2)	
SELECT DISTINCT LINK_UP = R.LINK1, SUMMA = 0, QUANTITY = 0, STORNO = TG2.STORNO, TG2.NAME, TG2.ORDERS, ECON_OPER = X.LINK, LINK2 = TG2.LINK  
FROM
	#G_PROV1_REC R
	INNER JOIN dbo.G_PROV1 G1 ON G1.LINK = R.LINK1
	INNER JOIN #tmp_G_PROV2 TG2 ON R.LINK2 = TG2.LINK_UP  
	LEFT JOIN 
	(SELECT XO.LINK, XOG.CODE AS XOG_CODE, XO.CODE AS XO_CODE FROM [dbo].[XOZ_OPER] XO
		INNER JOIN [dbo].[XOZ_OPER_GROUP] XOG ON XO.GROUP_LINK = XOG.LINK) X 
		ON LTRIM(RTRIM(TG2.XOG_CODE)) = LTRIM(RTRIM(X.XOG_CODE)) AND LTRIM(RTRIM(TG2.XO_CODE)) = LTRIM(RTRIM(X.XO_CODE))
'

INSERT INTO #OUT (TXT)
SELECT
'
INSERT INTO dbo.G_PROV_AP (LINK_UP,DB_KR,ACCOUNT,EKR,SGU)
SELECT DISTINCT
	LINK_UP = R.LINK1, TGAP.DB_KR, ACCOUNT = SA.LINK, EKR = T_EKR.LINK, SGU = T_SGU.LINK
FROM
	#G_PROV2_REC R
	INNER JOIN dbo.G_PROV2 G2 ON G2.LINK = R.LINK1
	INNER JOIN dbo.G_PROV1 G1 ON G2.LINK_UP = G1.LINK
	INNER JOIN #tmp_G_PROV_AP TGAP ON G2.LINK2 = TGAP.LINK_UP
	INNER JOIN dbo.S_ACCOUNTS SA ON SA.CODE like LTRIM(RTRIM(TGAP.ACCOUNT))
	LEFT JOIN [dbo].[KOSGU] T_EKR ON T_EKR.CODE = TGAP.EKR
	LEFT JOIN [dbo].[KOSGU] T_SGU ON T_SGU.CODE = TGAP.SGU
'

INSERT INTO #OUT (TXT)
SELECT
'
--ЗАВЕРШАЮЩИЕ ОПЕРАЦИИ:
--1. Удаление временных колонок
IF COLUMNPROPERTY(object_id(''[dbo].[G_PROV1]''), ''LINK2'', ''AllowsNull'') is NOT NULL
   ALTER TABLE [dbo].[G_PROV1] DROP COLUMN [LINK2]
'

INSERT INTO #OUT (TXT)
SELECT
'
IF COLUMNPROPERTY(object_id(''[dbo].[G_PROV2]''), ''LINK2'', ''AllowsNull'') is NOT NULL
   ALTER TABLE [dbo].[G_PROV2] DROP COLUMN [LINK2]
'

INSERT INTO #OUT (TXT)
SELECT
'GO'+ CHAR(13) + CHAR(10)

INSERT INTO #OUT (TXT)
SELECT
'
--2. Удаление типовых операций без проводок
DELETE FROM dbo.G_PROV1
WHERE
	EXISTS (SELECT * FROM #G_PROV1_REC R WHERE R.LINK1 = dbo.G_PROV1.LINK)
	AND NOT EXISTS (
		SELECT *
		FROM dbo.G_PROV2 G2 INNER JOIN dbo.G_PROV_AP GAP ON GAP.LINK_UP = G2.LINK
		WHERE G2.LINK_UP = dbo.G_PROV1.LINK)
'
INSERT INTO #OUT (TXT)
SELECT
'GO'+ CHAR(13) + CHAR(10)

SELECT TXT as [--TXT] FROM #OUT ORDER BY ORD

IF @NASTR_DOC = 1 
BEGIN
	EXECUTE dbo.[UNLOAD_XD_DOC_NASTR_TO] @NAME_OPER = @NAME_OPER
END

SET NOCOUNT OFF
END



GO


GRANT EXECUTE ON dbo.[UNLOAD_SHABLON_DOCUMENTS_PROV] TO PUBLIC

GO


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

--------------------------------------------------------------------------------------------
-- СИНХРОНИЗАЦИЯ СО СМЕТОЙ-СМАРТ ЧЕРЕЗ ШИНУ
--------------------------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[SMETA_SMART_SYNC]
	 @exportDTName		VARCHAR(100) = NULL		-- Таблица с информацией для передачи в смету-смарт
	,@contactLink		INT						-- Линк котнтакта получателя сообщения базы сметы-смарт
	,@objectCode		VARCHAR(30)				-- Код объекта для передачи
	,@isDelete			BIT = 0					-- Режим удаления документов
	,@vcProtocol		VARCHAR(8000) OUTPUT	-- Протокол для передачи текста ошибки
AS
BEGIN
	DECLARE
		 @Recipients	VARCHAR(1000)	-- Получатель сообщения (адрес на шине)
		,@xmlData		XML				-- Данные в виде xml для передачи по шине
		,@msgContent	VARCHAR(MAX)	-- Содержимое сообщения в формате xml
		,@msgLink		INT				-- Линк сообщения на шине
		,@msgRespLink	INT				-- Линк сообщения ответа
		,@msgStatus		VARCHAR(100)	-- Статус сообщения
		,@isDeleteStr	VARCHAR(10)		-- Режим удаления документов
		,@nvcExec		NVARCHAR(MAX)

	SET @vcProtocol = ''
	SET @isDeleteStr = CAST(@isDelete AS VARCHAR(10))

	-- Загрузка адреса получателя
	SELECT @Recipients = [ADDRESS] FROM dbo.[rms_CONTACTS] WHERE [LINK] = @contactLink
	IF (@Recipients IS NULL OR @Recipients = '')
	BEGIN
		SET @vcProtocol = 'Не найден получатель сообщения.'
		RETURN -1
	END

	-- Документы для зарплаты
	IF (@objectCode = 'DOCUMENTS_SALARY')
	BEGIN
		IF (@isDelete = 0)
		BEGIN
			SET @nvcExec = 'DECLARE @s VARCHAR(MAX)
SET @s = ''''
SELECT @s = @s + CONVERT(VARCHAR(MAX),[XML_DATA]) FROM ' + @exportDTName + '
WHERE [ID] > 1
ORDER BY [ID]
IF (LEN(@s) > 0) SET @xmlData = CONVERT(XML, @s)
ELSE SET @xmlData = NULL'
			EXEC SP_EXECUTESQL @nvcExec, N'@xmlData XML OUTPUT', @xmlData = @xmlData OUTPUT
		END
		ELSE
		BEGIN
			SET @nvcExec = 'IF EXISTS(SELECT 1 FROM ' + @exportDTName + ')
	SET @xmlData = (SELECT [XML_DATA] [GUID] FROM ' + @exportDTName + ' FOR XML RAW, ROOT(''ROOT''), TYPE)
ELSE SET @xmlData = NULL'
			EXEC SP_EXECUTESQL @nvcExec, N'@xmlData XML OUTPUT', @xmlData = @xmlData OUTPUT
		END
	END
	-- Запрос на синхронизацию справочников
	ELSE IF (@objectCode IN('BI_DICTION_KBK','BI_DICTION_DIV','BI_DICTION_ADMIN_BS','BI_DICTION_CSR','BI_DICTION_EXP','BI_DICTION_INCOME','BD_DOP_CLASSIF','DICTIONARY_REGIONAL','BB_DICTION_PROG','BI_DICTION_IVF','DICTIONARY_KOSGU','DEPARTMENTS_CORR'))
	BEGIN
		DECLARE
			 @depLink INT
			,@INN VARCHAR(12)
			,@KPP VARCHAR(9)

		SELECT @depLink = [DEP_LINK] FROM dbo.USER_INFO
		SELECT @INN = [INN], @KPP = [KPP] FROM dbo.DEPARTMENTS WHERE LINK = @depLink

		-- Отправка сообщения по шине
		EXEC [dbo].[RMSCreateMessage]
			 @msgLink	= @msgLink OUTPUT
			,@Type		= 'DOCUMENT'	-- тип сообщения по умолчанию
			,@Subject	= 'ZARPLATA_KS'	-- со стороны сметы-смарт настроен обработчик по коду ZARPLATA_KS для приёма сообщений из зарплаты-кс
			,@Status	= 'NEW'			-- статус сообщения по умолчанию NEW
			,@Recipients= @Recipients	-- получатели
			,@PName		= 'object'		-- параметр код передаваемого объекта
			,@PValue	= @objectCode	-- код передаваемого объекта
			,@P2Name	= 'INN'
			,@P2Value	= @INN
			,@P3Name	= 'KPP'
			,@P3Value	= @KPP
	END
	ELSE
	BEGIN
		SET @vcProtocol = 'Неизвестный код объекта для передачи: ' + @objectCode
		RETURN -1
	END

	IF (@xmlData IS NOT NULL)
	BEGIN
		SET @msgContent = CONVERT(VARCHAR(MAX), @xmlData)

		-- Отправка сообщения по шине
		EXEC [dbo].[RMSCreateMessage]
			 @msgLink	= @msgLink OUTPUT
			,@Type		= 'DOCUMENT'	-- тип сообщения по умолчанию
			,@Subject	= 'ZARPLATA_KS'	-- со стороны сметы-смарт настроен обработчик по коду ZARPLATA_KS для приёма сообщений из зарплаты-кс
			,@Status	= 'NEW'			-- статус сообщения по умолчанию NEW
			,@Recipients= @Recipients	-- получатели
			,@PName		= 'object'		-- параметр код передаваемого объекта
			,@PValue	= @objectCode	-- код передаваемого объекта
			,@P2Name	= 'isDelete'	-- параметр операции удаления документов
			,@P2Value	= @isDeleteStr	-- режим удаления документов
			,@CName		= 'XML'			-- имя содержимого сообщения
			,@CValue	= @msgContent	-- значение содержимого сообщения
	END
	ELSE
	BEGIN
		SET @vcProtocol = 'Нет данных для передачи'
		RETURN -1
	END

	RETURN 0
END
GO

GRANT EXECUTE ON dbo.[SMETA_SMART_SYNC] TO PUBLIC
GO
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[KD_HOLIDAYS_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[KD_HOLIDAYS_SAVE]

GO

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

CREATE  PROCEDURE dbo.KD_HOLIDAYS_SAVE
	@parLINK	   	int	OUTPUT,
	@parNAME       	VARCHAR(60),
	@parDAY        	INT = 1,
	@parMonth      	INT = 1,
	@parDATE      	DATETIME = null,
	@parTD_LINK  	INT,
	@parTYPE_HOL  	TINYINT = 1,
	@DAY1        	INT,
	@Month1      	INT,
	@parDATE1      DATETIME = null
	
AS

DECLARE @SQLError	int, 
		@EventText	varchar(7000),
		@trancount	int,  
		@ObjLink int, 
		@RowCount INT

--
SET @trancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN


IF LEN(@parNAME) = 0 
BEGIN
	ROLLBACK
	RETURN 5
END

SELECT @ObjLink = LINK FROM dbo.S_OBJECTS WHERE CODE = 'KD_HOLIDAYS'

IF @parLINK is null OR @parLINK = 0
BEGIN
	INSERT INTO dbo.HOLIDAYS WITH (ROWLOCK) (NAME,[DAY],[MONTH],TD_LINK,TYPE_HOL,[DAY1],[MONTH1],[YEAR]) 
	SELECT @parNAME,DAY(@parDATE),MONTH(@parDATE),@parTD_LINK,@parTYPE_HOL, DAY(@parDATE1), MONTH(@parDATE1), YEAR(@parDATE)
	
	SELECT @SQLError = @@ERROR, @parLINK = @@IDENTITY
	IF @SQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
END
ELSE
BEGIN
	UPDATE dbo.HOLIDAYS WITH (ROWLOCK) 
	SET NAME = @parNAME,[DAY] = DAY(@parDATE),[MONTH] = MONTH(@parDATE), TD_LINK = @parTD_LINK, TYPE_HOL = @parTYPE_HOL,
		[DAY1] = DAY(@parDATE1), [MONTH1] = MONTH(@parDATE1), [YEAR] =  YEAR(@parDATE)
	WHERE LINK =@parLINK
	
	SELECT @SQLError = @@ERROR, @RowCount = @@ROWCOUNT
	IF @SQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
	IF @RowCount = 0
	BEGIN
		ROLLBACK
		RETURN 2
	END
END	


SET @EventText = 'Справочник праздничных дней' + ' ' +  RTRIM(CONVERT(VARCHAR(7000), @parNAME))
EXECUTE dbo.WF_GENERATEEVENT 'Сохранение строки справочника', @EventText, @ObjLink, 'HOLIDAYS', @parLINK

IF @@TRANCOUNT > @trancount
	COMMIT TRAN
RETURN 0



GO


GRANT EXECUTE ON dbo.[KD_HOLIDAYS_SAVE] TO PUBLIC

GO


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


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

GO

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

CREATE PROCEDURE dbo.BK_REPORT_AKT_RESIVE_DEP1
	@varKSdDate1	DATETIME,
	@varKSdDate2	DATETIME,
	@varKScVal1 char(1), @varKSnOtborLink1 int,
	@varKScVal2 char(1), @varKSnOtborLink2 int,
	@cVal_KBK char(1), @nOtborLinkKBK int,	-- Отбор КБК --
	@cVal_EKR char(1), @nOtborLinkEKR int,	-- Отбор ЭКР --
	@intParamDep	INT,
	@intRepByEKR	INT,
	@intRepByKBK	INT,
	@intSVOD_ZB	int,	-- Сводный отчет (ЦБ) --
	@strACCT_SINTH	VARCHAR (100) = '206, 302',
	@intNO_ZACHET	TINYINT = 0,
	@intRepByAP1	TINYINT = 0,
	@cVal_OSNOV char(1) = '', @intOtbor_OSNOV Int = NULL	-- Отбор документов оснований --
AS
BEGIN
	DECLARE	@varKSDEP_LINK	INT,
		@varKSORG_Code	VARCHAR(20),
		@varKSORGNAME	VARCHAR(254),
		@strDATE_BEGIN	VARCHAR (10),
		@strDATE_END	VARCHAR (10),
		@strDATE_OUT	VARCHAR (10),
		@strGLBUH_NAME	VARCHAR (30),
		@intXO_ZACHET	INT,
		@dDATE_OUT_REST	DATETIME,
		
		@F_CHECK_OSNOV	TINYINT

	IF ISNULL (@intNO_ZACHET, 0) = 1
		SELECT @intXO_ZACHET = LINK
		FROM dbo.XD_XOZ_OPER
		WHERE FULLCODE = '14.03'
	ELSE
		SET @intXO_ZACHET = -1

	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)	-- Сводный отчет по ЦБ -- 
	SET @varKSDEP_LINK = dbo.BK_GetDepZB ()
--	SET @varKSDEP_LINK = COALESCE (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())

	IF @intSVOD_ZB = 1 OR @varKSDEP_LINK IS NULL 	
		SET @varKSDEP_LINK = dbo.GetOwnDepLink ()

	SELECT  @varKSDEP_LINK = D.LINK,
		@varKSORG_Code = D.[CODE],
		@varKSORGNAME = dbo.BK_GET_PRINT_DEP_NAME (D.LINK),
		@strGLBUH_NAME = ISNULL (OTV_B.[FACE_NAME], '')
	FROM dbo.DICTIONARY_DEPARTMENT D
	LEFT OUTER JOIN dbo.DICTIONARY_OTV_FACE OTV_B ON (OTV_B.DEP_LINK = D.LINK
		AND OTV_B.[NAME] = 'Главный бухгалтер')
	WHERE D.LINK = @varKSDEP_LINK

	IF @intSVOD_ZB = 1
		SET @varKSORGNAME = RTRIM (@varKSORGNAME) + ' (ЦБ)'
	
	CREATE TABLE #TABLE_ACCT ([UPD] INT, [DEL] INT, [CHECKED] INT,
			[LINK] INT, [CODE] VARCHAR (30), [NAME] VARCHAR (254))
	
	IF LEN (@varKScVal1) > 0
		INSERT INTO #TABLE_ACCT (UPD, DEL, CHECKED, LINK, CODE, [NAME])
		SELECT 0, 0, 0, OVA.RECORD, SA.CODE, SA.[NAME]
		FROM dbo.OBJECT_VAR_ACCT OVA, dbo.S_ACCOUNTS SA
		WHERE OVA.LINK_UP = @varKSnOtborLink1
			AND SA.LINK = OVA.RECORD
	ELSE
		INSERT INTO #TABLE_ACCT
		EXEC dbo.BK_GET_OTBOR_ACCOUNTS1 @strACCT_SINTH, DEFAULT, DEFAULT

-- SELECT * FROM #TABLE_ACCT

	DECLARE @DEP_TABLE TABLE (LINK_DEP INT, DEP_CODE  VARCHAR(20), DEP_NAME VARCHAR(254))

	IF ISNULL (@intParamDep, 0) = 0 -- организация в параметрах не указана
	BEGIN
		IF LEN(@varKScVal2)>0
		BEGIN
			INSERT INTO @DEP_TABLE
				SELECT OVR.RECORD, D.CODE, D.[NAME]
				FROM OBJECT_VAR_DEPARTMENT OVR, DICTIONARY_DEPARTMENT D
				WHERE D.LINK=OVR.RECORD AND OVR.LINK_UP=@varKSnOtborLink2
		END
		ELSE
		BEGIN
			INSERT INTO @DEP_TABLE
				SELECT D.LINK, D.CODE, D.[NAME] FROM DICTIONARY_DEPARTMENT D
			INSERT INTO @DEP_TABLE VALUES (0, '', '')
		END
	END
	ELSE
		INSERT INTO @DEP_TABLE
			SELECT D.LINK, D.CODE, D.[NAME]
			FROM dbo.DICTIONARY_DEPARTMENT D
			WHERE LINK = @intParamDep

	--- ОТБОР КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30), KBK_NAME [VARCHAR] (254))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE,
			AP.NAME
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE, AP_NAME
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	--- Отбор ЭКР --- 
	DECLARE @TAB_EKR TABLE (LINK_EKR [INT], EKR_CODE  [VARCHAR] (20), EKR_NAME [VARCHAR] (254))
	IF LEN(@cVal_EKR)>0 BEGIN
		INSERT INTO @TAB_EKR
			SELECT OVR.RECORD, D.CODE, D.[NAME]
			FROM dbo.OBJECT_VAR_KOSGU OVR, dbo.KOSGU D
			WHERE D.LINK = OVR.RECORD AND OVR.LINK_UP = @nOtborLinkEKR
	END
	ELSE
	BEGIN
		INSERT INTO @TAB_EKR
		SELECT LINK_AP, AP_CODE, AP_NAME
		FROM dbo.BK_GetTableDictionByAP ('EKR')
	END

	--- Отбор документов оснований --- 
	DECLARE @TAB_OSNOV TABLE
		(LINK INT,
		NUM  VARCHAR (50),
		NAME VARCHAR (254),
		INFO VARCHAR (254))

	IF LEN (@cVal_OSNOV)>0
	BEGIN
		INSERT INTO @TAB_OSNOV
		SELECT
			OVR.RECORD,
			D.NUMBER,
			D.[TYPE],
			D.INFO
		FROM dbo.OBJECT_VAR_OSNOV OVR
		INNER JOIN dbo.BD_OSNOV D ON (D.LINK = OVR.RECORD)
		WHERE OVR.LINK_UP = @intOtbor_OSNOV
		
		SET @F_CHECK_OSNOV = 1
	END	
	ELSE
	BEGIN
		INSERT INTO @TAB_OSNOV
		SELECT
			0,
			'',
			'',
			''
	
		SET @F_CHECK_OSNOV = 0
	END	

--elect * from @TAB_OSNOV
	
	--- ДЕБЕТОВЫЕ ОБОРОТЫ --- 
	DECLARE @TAB_DB TABLE
		(LINK_DOC INT,
		DEP	INT,
		KBK INT,
		EKR INT,
		OSNOV INT,
		SUMMA NUMERIC (28,4))

	INSERT INTO @TAB_DB
	SELECT
		T1.LINK_DOC,
		T1.DEP,
		CASE
			WHEN @intRepByKBK = 1 THEN T1.KBK
			ELSE 0
		END,
		CASE
			WHEN @intRepByEKR = 1 THEN T1.EKR
			ELSE 0
		END,
		CASE
			WHEN @intRepByAP1 = 1 THEN T1.AP1
			ELSE 0
		END,
		SUM (T1.SUMMA)
	FROM dbo.BK_GetTableOborotByDate1 (@varKSdDate1, @varKSdDate2, 0, DEFAULT, DEFAULT) T1
	INNER JOIN #TABLE_ACCT T2 ON (T2.LINK = T1.ACCOUNT)
	INNER JOIN @TAB_KBK K1 ON (K1.LINK_KBK = T1.KBK)
	INNER JOIN @TAB_OSNOV OSN ON (@F_CHECK_OSNOV = 0
		OR @F_CHECK_OSNOV = 1 AND OSN.LINK = T1.AP1)
	WHERE (@intSVOD_ZB = 1
			OR @intSVOD_ZB = 0 AND T1.DEP_LINK = @varKSDEP_LINK)
		AND ISNULL (T1.XOZ_OPER, 0) <> @intXO_ZACHET
	GROUP BY
		T1.LINK_DOC,
		T1.DEP,
		CASE
			WHEN @intRepByKBK = 1 THEN T1.KBK
			ELSE 0
		END,
		CASE
			WHEN @intRepByEKR = 1 THEN T1.EKR
			ELSE 0
		END,
		CASE
			WHEN @intRepByAP1 = 1 THEN T1.AP1
			ELSE 0
		END

-- select * from @TAB_DB

	--- КРЕДИТОВЫЕ ОБОРОТЫ --- 
	DECLARE @TAB_KT TABLE
		(LINK_DOC INT,
		DEP	INT,
		KBK INT,
		EKR INT,
		OSNOV INT,
		SUMMA NUMERIC (28,4))

	INSERT INTO @TAB_KT
	SELECT T1.LINK_DOC,
		T1.DEP,
		CASE
			WHEN @intRepByKBK = 1 THEN T1.KBK
			ELSE 0
		END,
		CASE
			WHEN @intRepByEKR = 1 THEN T1.EKR
			ELSE 0
		END,
		CASE
			WHEN @intRepByAP1 = 1 THEN T1.AP1
			ELSE 0
		END,
		SUM (T1.SUMMA)
	FROM dbo.BK_GetTableOborotByDate1 (@varKSdDate1, @varKSdDate2, 1, DEFAULT, DEFAULT) T1
	INNER JOIN #TABLE_ACCT T2 ON (T2.LINK = T1.ACCOUNT)
	INNER JOIN @TAB_KBK K1 ON (K1.LINK_KBK = T1.KBK)
	INNER JOIN @TAB_OSNOV OSN ON (@F_CHECK_OSNOV = 0
		OR @F_CHECK_OSNOV = 1 AND OSN.LINK = T1.AP1)
	WHERE (@intSVOD_ZB = 1
			OR @intSVOD_ZB = 0 AND T1.DEP_LINK = @varKSDEP_LINK)
		AND ISNULL (T1.XOZ_OPER, 0) <> @intXO_ZACHET
	GROUP BY T1.LINK_DOC,
		T1.DEP,
		CASE
			WHEN @intRepByKBK = 1 THEN T1.KBK
			ELSE 0
		END,
		CASE
			WHEN @intRepByEKR = 1 THEN T1.EKR
			ELSE 0
		END,
		CASE
			WHEN @intRepByAP1 = 1 THEN T1.AP1
			ELSE 0
		END

-- select * from @TAB_KT

	--- ВХОДЯЩИЕ ОСТАТКИ --- 
	DECLARE @TAB_IN_REST TABLE
		(DEP INT,
		KBK INT,
		EKR INT,
		OSNOV INT,
		D_SUM_EKR NUMERIC (28,4),
		K_SUM_EKR NUMERIC (28,4))
		
	INSERT INTO @TAB_IN_REST 
	SELECT
		ISNULL (T_REST.DEP, 0) AS DEP,
		CASE
			WHEN @intRepByKBK = 1 THEN ISNULL (T_REST.KBK, 0)
			ELSE 0
		END,
		CASE
			WHEN @intRepByEKR = 1 THEN ISNULL (T_REST.EKR, 0)
			ELSE 0
		END,
		CASE
			WHEN @intRepByAP1 = 1 THEN ISNULL (T_REST.AP1, 0)
			ELSE 0
		END,
		SUM (T_REST.D_SUMMA),
		SUM (T_REST.K_SUMMA)
	FROM dbo.ARestTableByDate (@varKSdDate1, DEFAULT) T_REST
	INNER JOIN #TABLE_ACCT T_ACCT ON (T_ACCT.LINK = T_REST.ACCOUNT)
	INNER JOIN @TAB_KBK K1 ON (K1.LINK_KBK = ISNULL (T_REST.KBK, 0))
	INNER JOIN @TAB_OSNOV OSN ON (@F_CHECK_OSNOV = 0
		OR @F_CHECK_OSNOV = 1 AND OSN.LINK = T_REST.AP1)
	WHERE (@intSVOD_ZB = 1
			AND T_REST.DEP_LINK IN (SELECT LINK FROM dbo.DEPARTMENTS WHERE ZB = 1 OR TYPE = 4))
		OR (@intSVOD_ZB = 0 AND T_REST.DEP_LINK = @varKSDEP_LINK)
	GROUP BY ISNULL (T_REST.DEP, 0),
		CASE
			WHEN @intRepByKBK = 1 THEN ISNULL (T_REST.KBK, 0)
			ELSE 0
		END,
		CASE
			WHEN @intRepByEKR = 1 THEN ISNULL (T_REST.EKR, 0)
			ELSE 0
		END,
		CASE
			WHEN @intRepByAP1 = 1 THEN ISNULL (T_REST.AP1, 0)
			ELSE 0
		END

-- select * from @TAB_IN_REST

	--- ИСХОДЯЩИЕ ОСТАТКИ --- 
	SET @dDATE_OUT_REST = DATEADD (DAY, 1, @varKSdDate2)

	DECLARE @TAB_OUT_REST TABLE
		(DEP INT,
		KBK INT,
		EKR INT,
		OSNOV INT,
		D_SUM_EKR NUMERIC (28,4),
		K_SUM_EKR NUMERIC (28,4))

	INSERT INTO @TAB_OUT_REST 
	SELECT
		ISNULL (T_REST.DEP, 0) AS DEP,
		CASE
			WHEN @intRepByKBK = 1 THEN ISNULL (T_REST.KBK, 0)
			ELSE 0
		END,
		CASE
			WHEN @intRepByEKR = 1 THEN ISNULL (T_REST.EKR, 0)
			ELSE 0
		END,
		CASE
			WHEN @intRepByAP1 = 1 THEN ISNULL (T_REST.AP1, 0)
			ELSE 0
		END,
		SUM (T_REST.D_SUMMA),
		SUM (T_REST.K_SUMMA)
	FROM dbo.ARestTableByDate (@dDATE_OUT_REST, DEFAULT) T_REST
	INNER JOIN #TABLE_ACCT T_ACCT ON (T_ACCT.LINK = T_REST.ACCOUNT)
	INNER JOIN @TAB_KBK K1 ON (K1.LINK_KBK = ISNULL (T_REST.KBK, 0))
	INNER JOIN @TAB_OSNOV OSN ON (@F_CHECK_OSNOV = 0
		OR @F_CHECK_OSNOV = 1 AND OSN.LINK = T_REST.AP1)
	WHERE (@intSVOD_ZB = 1
			AND T_REST.DEP_LINK IN (SELECT LINK FROM dbo.DEPARTMENTS WHERE ZB = 1 OR TYPE = 4))
		OR (@intSVOD_ZB = 0 AND T_REST.DEP_LINK = @varKSDEP_LINK)
	GROUP BY ISNULL (T_REST.DEP, 0),
		CASE
			WHEN @intRepByKBK = 1 THEN ISNULL (T_REST.KBK, 0)
			ELSE 0
		END,
		CASE
			WHEN @intRepByEKR = 1 THEN ISNULL (T_REST.EKR, 0)
			ELSE 0
		END,
		CASE
			WHEN @intRepByAP1 = 1 THEN ISNULL (T_REST.AP1, 0)
			ELSE 0
		END

-- select * from @TAB_OUT_REST

	--- ИТОГОВЫЕ ОСТАТКИ ПО КБК ---
	DECLARE @TAB_REST_KBK_IN TABLE
		(DEP INT,
		KBK INT,
		OSNOV INT,
		D_SUMMA NUMERIC (28,4),
		K_SUMMA NUMERIC (28,4))
	INSERT INTO @TAB_REST_KBK_IN
	SELECT
		DEP,
		KBK,
		OSNOV,
		SUM (D_SUM_EKR),
		SUM (K_SUM_EKR)
	FROM @TAB_IN_REST
	GROUP BY
		DEP,
		KBK,
		OSNOV

	DECLARE @TAB_REST_KBK_OUT TABLE
		(DEP INT,
		KBK INT,
		OSNOV INT,
		D_SUMMA NUMERIC (28,4),
		K_SUMMA NUMERIC (28,4))
	INSERT INTO @TAB_REST_KBK_OUT
	SELECT
		DEP,
		KBK,
		OSNOV,
		SUM (D_SUM_EKR),
		SUM (K_SUM_EKR)
	FROM @TAB_OUT_REST
	GROUP BY
		DEP,
		KBK,
		OSNOV
	
	--- ИТОГОВЫЕ ОСТАТКИ ПО ОРГАНИЗАЦИЯМ ---
	DECLARE @TAB_REST_DEP_IN TABLE (DEP INT, D_SUMMA NUMERIC (28,4), K_SUMMA NUMERIC (28,4))
	INSERT INTO @TAB_REST_DEP_IN
	SELECT DEP,
		SUM (D_SUM_EKR),
		SUM (K_SUM_EKR)
	FROM @TAB_IN_REST
	GROUP BY DEP		

	DECLARE @TAB_REST_DEP_OUT TABLE (DEP INT, D_SUMMA NUMERIC (28,4), K_SUMMA NUMERIC (28,4))
	INSERT INTO @TAB_REST_DEP_OUT
	SELECT DEP,
		SUM (D_SUM_EKR),
		SUM (K_SUM_EKR)
	FROM @TAB_OUT_REST
	GROUP BY DEP

	--- ИТОГОВЫЕ ОСТАТКИ ПО AP1 ---
	DECLARE @TAB_REST_AP1_IN TABLE
		(DEP INT,
		OSNOV INT,
		D_SUMMA NUMERIC (28,4),
		K_SUMMA NUMERIC (28,4))
		
	INSERT INTO @TAB_REST_AP1_IN
	SELECT
		DEP,
		OSNOV,
		SUM (D_SUM_EKR),
		SUM (K_SUM_EKR)
	FROM @TAB_IN_REST
	GROUP BY
		DEP,
		OSNOV		

	DECLARE @TAB_REST_AP1_OUT TABLE
		(DEP INT,
		OSNOV INT,
		D_SUMMA NUMERIC (28,4),
		K_SUMMA NUMERIC (28,4))
	INSERT INTO @TAB_REST_AP1_OUT
	SELECT
		DEP,
		OSNOV,
		SUM (D_SUM_EKR),
		SUM (K_SUM_EKR)
	FROM @TAB_OUT_REST
	GROUP BY
		DEP,
		OSNOV		

	--- ИТОГОВЫЕ ОБОРОТЫ --- 
	DECLARE @TAB_OBOROT TABLE
		(LINK_DOC INT,
		DEP INT,
		KBK INT,
		EKR INT,
		OSNOV INT,
		DT_SUM NUMERIC (28,4),
		KT_SUM NUMERIC (28,4))

	INSERT INTO @TAB_OBOROT 
		(LINK_DOC,
		DEP,
		KBK,
		EKR,
		OSNOV)
	SELECT 
		LINK_DOC,
		DEP,
		KBK,
		EKR,
		OSNOV
	FROM @TAB_DB
	UNION 
	SELECT 
		LINK_DOC,
		DEP,
		KBK,
		EKR,
		OSNOV
	FROM @TAB_KT

	UPDATE @TAB_OBOROT
	SET DT_SUM = COALESCE (DB.SUMMA, 0),
		KT_SUM = COALESCE (KT.SUMMA, 0)
	FROM @TAB_OBOROT T1
	LEFT OUTER JOIN @TAB_DB DB ON (DB.LINK_DOC = T1.LINK_DOC
		AND DB.DEP = T1.DEP
		AND DB.KBK = T1.KBK
		AND DB.EKR = T1.EKR
		AND DB.OSNOV = T1.OSNOV)
	LEFT OUTER JOIN @TAB_KT KT ON (KT.LINK_DOC = T1.LINK_DOC
		AND KT.DEP = T1.DEP
		AND KT.KBK = T1.KBK
		AND KT.EKR = T1.EKR
		AND KT.OSNOV = T1.OSNOV)

-- select * from @TAB_OBOROT
	--- СПИСОК ОРГАНИЗАЦИЙ, ПО КОТОРЫМ СОБИРАЕМ --- 
	DECLARE @TAB_ALL_REC TABLE
		(DEP INT,
		KBK INT,
		EKR INT,
		OSNOV INT)
	
	INSERT INTO @TAB_ALL_REC
		(DEP,
		KBK,
		EKR,
		OSNOV)
	SELECT
		DEP,
		KBK,
		EKR,
		OSNOV
	FROM @TAB_OBOROT
	UNION 
	SELECT
		DEP,
		KBK,
		EKR,
		OSNOV
	FROM @TAB_IN_REST
	WHERE D_SUM_EKR <> 0 OR K_SUM_EKR <> 0 
	UNION 
	SELECT
		DEP,
		KBK,
		EKR,
		OSNOV
	FROM @TAB_OUT_REST
	WHERE D_SUM_EKR <> 0 OR K_SUM_EKR <> 0 

-- select * from @TAB_ALL_REC

	--- РЕЗУЛЬТАТЫ --- 
	DECLARE @TAB_RES TABLE (LINK_DOC INT, DEP INT, KBK INT, EKR INT,
		DOC_DATE VARCHAR (10), dDOC_DATE DATETIME, DOC_NUM VARCHAR (50),
		DOC_NAME VARCHAR (254),
		DATE_BEGIN VARCHAR (10), DATE_END VARCHAR (10),
		DATE_NEXT VARCHAR (10),
		DEP_CODE1 VARCHAR (10), DEP_NAME1 VARCHAR (254),
		DEP_CODE2 VARCHAR (10), DEP_NAME2 VARCHAR (254),
		EKR_CODE VARCHAR (10), EKR_NAME VARCHAR (254),
		KBK_CODE VARCHAR (30), KBK_NAME VARCHAR (254),
		GLBUH1 VARCHAR (30), GLBUH2 VARCHAR (30),
		DT_SUM NUMERIC (28,4), KT_SUM NUMERIC (28,4),
		DIN_SUM NUMERIC (28,4), KIN_SUM NUMERIC (28,4),
		DIN_SUM_A NUMERIC (28,4), KIN_SUM_A NUMERIC (28,4),
		DIN_SUM_K NUMERIC (28,4), KIN_SUM_K NUMERIC (28,4),
		DIN_SUM_E NUMERIC (28,4), KIN_SUM_E NUMERIC (28,4),
		DOUT_SUM NUMERIC (28,4), KOUT_SUM NUMERIC (28,4),
		DOUT_SUM_A NUMERIC (28,4), KOUT_SUM_A NUMERIC (28,4),
		DOUT_SUM_K NUMERIC (28,4), KOUT_SUM_K NUMERIC (28,4),
		DOUT_SUM_E NUMERIC (28,4), KOUT_SUM_E NUMERIC (28,4),
		OSNOV_NUM	VARCHAR (30), OSNOV_INFO VARCHAR (254),
		OSNOV	INT)

	SET @strDATE_BEGIN = CONVERT (VARCHAR (10), @varKSdDate1, 104)
	SET @strDATE_END = CONVERT (VARCHAR (10), @varKSdDate2, 104)
	SET @strDATE_OUT = CONVERT (VARCHAR (10), @dDATE_OUT_REST, 104)

	INSERT INTO @TAB_RES
	SELECT
		T1.LINK_DOC,
		ALL_REC.DEP,
		ALL_REC.KBK,
		ALL_REC.EKR,
		CONVERT (VARCHAR (10), G.DATE_PROV, 104),
		G.DATE_PROV,
		ISNULL (G.NUMBER, ''),
		ISNULL (dbo.JurnalProvGetDocKind (G.LINK, G.OBJECT), ''),
		@strDATE_BEGIN,
		@strDATE_END,
		@strDATE_OUT,
		@varKSORG_Code, 
		@varKSORGNAME,
		D.DEP_CODE,
		D.DEP_NAME,
		E.EKR_CODE,
		E.EKR_NAME,
		K.KBK_CODE,
		K.KBK_NAME,
		@strGLBUH_NAME,
		ISNULL (OTV_B2.FACE_NAME, ''),
		ISNULL (T1.DT_SUM, 0),
		ISNULL (T1.KT_SUM, 0),
		ISNULL (TR_DEP_IN.D_SUMMA, 0),
		ISNULL (TR_DEP_IN.K_SUMMA, 0),
		ISNULL (TR_AP1_IN.D_SUMMA, 0),
		ISNULL (TR_AP1_IN.K_SUMMA, 0),
		ISNULL (TR_KBK_IN.D_SUMMA, 0),
		ISNULL (TR_KBK_IN.K_SUMMA, 0),
		ISNULL (TR_IN.D_SUM_EKR, 0),
		ISNULL (TR_IN.K_SUM_EKR, 0),
		ISNULL (TR_DEP_OUT.D_SUMMA, 0),
		ISNULL (TR_DEP_OUT.K_SUMMA, 0),
		ISNULL (TR_AP1_OUT.D_SUMMA, 0),
		ISNULL (TR_AP1_OUT.K_SUMMA, 0),
		ISNULL (TR_KBK_OUT.D_SUMMA, 0),
		ISNULL (TR_KBK_OUT.K_SUMMA, 0),
		ISNULL (TR_OUT.D_SUM_EKR, 0),
		ISNULL (TR_OUT.K_SUM_EKR, 0),
		ISNULL (OSN.NUMBER, ''),
		ISNULL (OSN.INFO, ''),
		ISNULL (OSN.LINK, 0)
-- select *  
	FROM @TAB_ALL_REC ALL_REC
	INNER JOIN @DEP_TABLE D ON (D.LINK_DEP = ALL_REC.DEP) 
	LEFT JOIN @TAB_EKR E ON (E.LINK_EKR = ALL_REC.EKR)
	LEFT JOIN @TAB_KBK K ON (K.LINK_KBK = ALL_REC.KBK)
	LEFT JOIN dbo.BD_OSNOV OSN ON (OSN.LINK = ALL_REC.OSNOV)
	LEFT OUTER JOIN @TAB_OBOROT T1 ON (T1.DEP = ALL_REC.DEP
		AND T1.EKR = ALL_REC.EKR
		AND T1.KBK = ALL_REC.KBK
		AND T1.OSNOV = ALL_REC.OSNOV)
	LEFT OUTER JOIN dbo.G_PROV G ON (G.LINK = T1.LINK_DOC)
	LEFT OUTER JOIN dbo.DICTIONARY_OTV_FACE OTV_B2 ON
		(OTV_B2.DEP_LINK = ALL_REC.DEP
		AND OTV_B2.[NAME] = 'Главный бухгалтер')
	LEFT OUTER JOIN @TAB_REST_DEP_IN TR_DEP_IN ON (TR_DEP_IN.DEP = ALL_REC.DEP)
	LEFT OUTER JOIN @TAB_REST_KBK_IN TR_KBK_IN ON
		(TR_KBK_IN.DEP = ALL_REC.DEP
		AND TR_KBK_IN.OSNOV = ALL_REC.OSNOV
		AND TR_KBK_IN.KBK = ALL_REC.KBK)
	LEFT OUTER JOIN @TAB_REST_AP1_IN TR_AP1_IN ON
		(TR_AP1_IN.DEP = ALL_REC.DEP
		AND TR_AP1_IN.OSNOV = ALL_REC.OSNOV)
	LEFT OUTER JOIN @TAB_IN_REST TR_IN ON
		(TR_IN.DEP = ALL_REC.DEP
		AND TR_IN.KBK = ALL_REC.KBK
		AND TR_IN.EKR = ALL_REC.EKR
		AND TR_IN.OSNOV = ALL_REC.OSNOV)
	LEFT OUTER JOIN @TAB_REST_DEP_OUT TR_DEP_OUT ON (TR_DEP_OUT.DEP = ALL_REC.DEP)
	LEFT OUTER JOIN @TAB_REST_KBK_OUT TR_KBK_OUT ON
		(TR_KBK_OUT.DEP = ALL_REC.DEP
		AND TR_KBK_OUT.OSNOV = ALL_REC.OSNOV
		AND TR_KBK_OUT.KBK = ALL_REC.KBK)
	LEFT OUTER JOIN @TAB_REST_AP1_OUT TR_AP1_OUT ON
		(TR_AP1_OUT.DEP = ALL_REC.DEP
		AND TR_AP1_OUT.OSNOV = ALL_REC.OSNOV)
	LEFT OUTER JOIN @TAB_OUT_REST TR_OUT ON
		(TR_OUT.DEP = ALL_REC.DEP
		AND TR_OUT.KBK = ALL_REC.KBK
		AND TR_OUT.EKR = ALL_REC.EKR
		AND TR_OUT.OSNOV = ALL_REC.OSNOV)

	SELECT * FROM @TAB_RES
		ORDER BY DEP_CODE1, DEP_CODE2, OSNOV, KBK_CODE, OSNOV_INFO, EKR_CODE, dDOC_DATE

	DROP TABLE #TABLE_ACCT
END



GO


GRANT EXECUTE ON dbo.[BK_REPORT_AKT_RESIVE_DEP1] TO PUBLIC

GO


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

GO
CREATE PROCEDURE [dbo].UNLOAD_XOZ_OPER (@GROUP_CODE VARCHAR(2) = NULL, @XOZ_CODE VARCHAR(2) = NULL)
--EXECUTE [dbo].UNLOAD_XOZ_OPER @GROUP_CODE='16', @XOZ_CODE='19'
AS

BEGIN

SET NOCOUNT ON

IF OBJECT_ID('TEMPDB..#OUT') IS NOT NULL
	DROP TABLE #OUT

CREATE TABLE #OUT (ORD INT IDENTITY(1,1), TXT VARCHAR(8000) )

INSERT INTO #OUT (TXT)
SELECT
'--Добавление системной Хозяйственной операции
--Сгенерировано скриптом: EXECUTE [dbo].UNLOAD_XOZ_OPER ' 
+ CASE WHEN @GROUP_CODE IS NULL THEN ', @GROUP_CODE=NULL' ELSE ', @GROUP_CODE=''' + LTRIM(RTRIM(@GROUP_CODE)) + '''' END
+ CASE WHEN @XOZ_CODE IS NULL THEN ', @XOZ_CODE=NULL' ELSE ', @XOZ_CODE=''' + LTRIM(RTRIM(@XOZ_CODE)) + '''' END

INSERT INTO #OUT (TXT)
SELECT
'

' + CHAR(13) + CHAR(10)

INSERT INTO #OUT (TXT)
SELECT
'

IF OBJECT_ID(''TEMPDB..#TMP_XOZ_OPER_GROUP'') IS NOT NULL
	DROP TABLE #TMP_XOZ_OPER_GROUP

CREATE TABLE #TMP_XOZ_OPER_GROUP (
	[CODE] char(2) NOT NULL ,
	[NAME] varchar(150) NOT NULL)
' + CHAR(13) + CHAR(10)

INSERT INTO #OUT (TXT)
SELECT 'INSERT INTO #TMP_XOZ_OPER_GROUP ([CODE],[NAME]) 
VALUES(''' + T.CODE+ ''',''' + T.NAME + ''')'
FROM 
	dbo.XOZ_OPER_GROUP T
WHERE
	@GROUP_CODE IS NULL OR @GROUP_CODE LIKE T.CODE	

INSERT INTO #OUT (TXT)
SELECT '' + CHAR(13) + CHAR(10)


INSERT INTO #OUT (TXT)
SELECT
'

IF OBJECT_ID(''TEMPDB..#TMP_XOZ_OPER'') IS NOT NULL
	DROP TABLE #TMP_XOZ_OPER

CREATE TABLE #TMP_XOZ_OPER (
	[GROUP_CODE] char(2) NOT NULL ,
	[CODE] char(2) NOT NULL ,
	[NAME] varchar(254) NOT NULL ,
	[SYSTEM] tinyint NOT NULL ,
	[BO] tinyint NOT NULL ,
	[ZP] tinyint NOT NULL ,
	[RBS] tinyint NOT NULL ,
	[USED] tinyint NOT NULL ,
	[GZ] tinyint NOT NULL ,
	[GZ2] tinyint NOT NULL ,
	[DO] tinyint NOT NULL ,
	[BO_DT_KT] tinyint NOT NULL ,
	[DO_DT_KT] tinyint NOT NULL ,
	[BO_MIN] tinyint NOT NULL ,
	[DO_MIN] tinyint NOT NULL)
' + CHAR(13) + CHAR(10)

INSERT INTO #OUT (TXT)
SELECT 'INSERT INTO #TMP_XOZ_OPER ([GROUP_CODE],[CODE],NAME,SYSTEM,BO,ZP,RBS,USED,GZ,GZ2,DO,BO_DT_KT,DO_DT_KT,BO_MIN,DO_MIN) 
VALUES(''' 
 + + XOG.CODE + ''','''
 + T.CODE + ''','''
 + T.NAME + ''','''
 + CAST(T.SYSTEM AS VARCHAR(20))+ ''','''
 + CAST(T.BO AS VARCHAR(20))+ ''','''
 + CAST(T.ZP AS VARCHAR(20))+ ''','''
 + CAST(T.RBS AS VARCHAR(20))+ ''','''
 + CAST(T.USED AS VARCHAR(20))+ ''','''
 + CAST(T.GZ AS VARCHAR(20))+ ''','''
 + CAST(T.GZ2 AS VARCHAR(20))+ ''','''
 + CAST(T.DO AS VARCHAR(20))+ ''','''
 + CAST(T.BO_DT_KT AS VARCHAR(20))+ ''','''
 + CAST(T.DO_DT_KT AS VARCHAR(20))+ ''','''
 + CAST(T.BO_MIN AS VARCHAR(20))+ ''','''
 + CAST(T.DO_MIN AS VARCHAR(20))+ ''')'+ CHAR(13) + CHAR(10)
FROM 
	dbo.XOZ_OPER T
	INNER JOIN dbo.XOZ_OPER_GROUP XOG ON T.GROUP_LINK = XOG.LINK
WHERE
	(@GROUP_CODE IS NULL OR @GROUP_CODE LIKE XOG.CODE)
	AND
	(@XOZ_CODE IS NULL OR @XOZ_CODE LIKE T.CODE)


INSERT INTO #OUT (TXT)
SELECT
'

IF OBJECT_ID(''TEMPDB..#TMP_XOZ_OPER_JURN'') IS NOT NULL
	DROP TABLE #TMP_XOZ_OPER_JURN

CREATE TABLE #TMP_XOZ_OPER_JURN (
	[GROUP_CODE] char(2) NOT NULL ,
	[XOZ_CODE] char(2) NOT NULL ,
	[JURN_CODE] char(10) NOT NULL ,
	[GK] tinyint NOT NULL)
' + CHAR(13) + CHAR(10)

INSERT INTO #OUT (TXT)
SELECT 'INSERT INTO #TMP_XOZ_OPER_JURN (GROUP_CODE,XOZ_CODE,JURN_CODE,GK) 
VALUES(''' + XOG.CODE+ ''',''' + LTRIM(RTRIM(B.CODE))+ ''',''' + LTRIM(RTRIM(C.CODE)) + ''',''' + LTRIM(RTRIM(CAST(A.GK AS VARCHAR(20)))) + ''')'+ CHAR(13) + CHAR(10)
FROM 
	dbo.XOZ_OPER_JURN A
	INNER JOIN dbo.XOZ_OPER B ON B.LINK = A.XOZ_LINK
	INNER JOIN dbo.XOZ_OPER_GROUP XOG ON B.GROUP_LINK = XOG.LINK	
	INNER JOIN dbo.JOURNAL_OPERATION C ON C.LINK = A.JURN_LINK
WHERE
	(@GROUP_CODE IS NULL OR @GROUP_CODE LIKE XOG.CODE)
	AND
	(@XOZ_CODE IS NULL OR @XOZ_CODE LIKE B.CODE)
		

INSERT INTO #OUT (TXT)
SELECT '' + CHAR(13) + CHAR(10)


INSERT INTO #OUT (TXT)
SELECT
'
IF OBJECT_ID(''TEMPDB..#TMP_CORRECT_PROV'') IS NOT NULL
	DROP TABLE #TMP_CORRECT_PROV

CREATE TABLE #TMP_CORRECT_PROV (
	[GROUP_CODE] char(2) NOT NULL ,
	[XOZ_CODE] char(2) NOT NULL ,
	[CODE_DT] VARCHAR(20) NOT NULL ,
	[CODE_KT] VARCHAR(20) NOT NULL ,
	[CODE_DT_SGU] VARCHAR(20) NULL ,
	[CODE_KT_SGU] VARCHAR(20) NULL ,
	[LINK] INT  IDENTITY(1,1))
' + CHAR(13) + CHAR(10)


INSERT INTO #OUT (TXT)
SELECT 'INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES(''' + XOG.CODE+ ''',''' + B.CODE+ ''',''' 
+ SAD.CODE+ ''','''+ SAK.CODE+ ''',' 
+ ISNULL(''+GD.CODE+'','NULL')+ ','+ ISNULL(''+GK.CODE+'','NULL')+ ')'+ CHAR(13) + CHAR(10)
FROM 
	dbo.CORRECT_PROV A
	INNER JOIN dbo.XOZ_OPER B ON B.LINK = A.LINK_HOZ
	INNER JOIN dbo.XOZ_OPER_GROUP XOG ON B.GROUP_LINK = XOG.LINK	
	INNER JOIN dbo.S_ACCOUNTS SAD ON SAD.LINK = A.LINK_DT
	INNER JOIN dbo.S_ACCOUNTS SAK ON SAK.LINK = A.LINK_KT
	LEFT JOIN dbo.KOSGU GD ON GD.LINK = A.DT_SGU
	LEFT JOIN dbo.KOSGU GK ON GK.LINK = A.KT_SGU
WHERE
	(@GROUP_CODE IS NULL OR @GROUP_CODE LIKE XOG.CODE)
	AND
	(@XOZ_CODE IS NULL OR @XOZ_CODE LIKE B.CODE)
		

INSERT INTO #OUT (TXT)
SELECT '' + CHAR(13) + CHAR(10)

INSERT INTO #OUT (TXT)
SELECT
'
IF OBJECT_ID(''TEMPDB..#TMP_XOZ_OPER_DOC'') IS NOT NULL
	DROP TABLE #TMP_XOZ_OPER_DOC

CREATE TABLE #TMP_XOZ_OPER_DOC (
	[GROUP_CODE] char(2) NOT NULL ,
	[XOZ_CODE] char(2) NOT NULL ,
	[CODE_OBJECT] VARCHAR(30) NOT NULL ,
)
' + CHAR(13) + CHAR(10)


INSERT INTO #OUT (TXT)
SELECT 'INSERT INTO #TMP_XOZ_OPER_DOC (GROUP_CODE,XOZ_CODE,CODE_OBJECT) 
VALUES(''' + XOG.CODE+ ''',''' + B.CODE+ ''','''+ SO.CODE+ ''')'+ CHAR(13) + CHAR(10)
FROM 
	dbo.XOZ_OPER_DOC A
	INNER JOIN dbo.S_OBJECTS SO ON SO.LINK = A.DOC_OBJECT
	INNER JOIN dbo.XOZ_OPER B ON B.LINK = A.XOZ_LINK
	INNER JOIN dbo.XOZ_OPER_GROUP XOG ON B.GROUP_LINK = XOG.LINK	
WHERE
	(@GROUP_CODE IS NULL OR @GROUP_CODE LIKE XOG.CODE)
	AND
	(@XOZ_CODE IS NULL OR @XOZ_CODE LIKE B.CODE)	

INSERT INTO #OUT (TXT)
SELECT 
'
UPDATE A
SET A.NAME = B.NAME
FROM dbo.XOZ_OPER_GROUP A INNER JOIN #TMP_XOZ_OPER_GROUP B ON A.CODE LIKE B.CODE
'

INSERT INTO #OUT (TXT)
SELECT 
'
INSERT INTO dbo.XOZ_OPER_GROUP (CODE,NAME)
SELECT CODE,NAME
FROM #TMP_XOZ_OPER_GROUP B 
WHERE NOT EXISTS (SELECT * FROM dbo.XOZ_OPER_GROUP A WHERE A.CODE LIKE B.CODE)
'

INSERT INTO #OUT (TXT)
SELECT 
'
--Сдвиг несистемных кодов
IF OBJECT_ID(''TEMPDB..#TMP_XO_USER_UPD'') IS NOT NULL
	DROP TABLE #TMP_XO_USER_UPD

CREATE TABLE #TMP_XO_USER_UPD (
	LINK		INT,
	GROUP_LINK	INT,
	CODE		VARCHAR (2)
	)

INSERT INTO #TMP_XO_USER_UPD	
SELECT
	XO.LINK,
	XO.GROUP_LINK,
--	CONVERT (VARCHAR (2), CONVERT (INT, XO.CODE) + 1),
	XO.CODE
FROM dbo.XOZ_OPER XO
INNER JOIN dbo.XOZ_OPER_GROUP XOG ON (XOG.LINK = XO.GROUP_LINK)
INNER JOIN #TMP_XOZ_OPER XO1 ON (XO1.CODE = XO.CODE
	AND XO1.GROUP_CODE = XOG.CODE)
WHERE
	XO.[SYSTEM]	= 0

WHILE EXISTS (
				SELECT *
				FROM dbo.XOZ_OPER XO
				INNER JOIN #TMP_XO_USER_UPD T1 ON (T1.GROUP_LINK = XO.GROUP_LINK
					AND T1.CODE = XO.CODE)
			)
			
	UPDATE #TMP_XO_USER_UPD
	SET CODE = CONVERT (VARCHAR (2), CONVERT (INT, CODE) + 1)

UPDATE XO
SET CODE = T1.CODE
FROM dbo.XOZ_OPER XO
INNER JOIN #TMP_XO_USER_UPD T1 ON (T1.LINK = XO.LINK)

'

INSERT INTO #OUT (TXT)
SELECT 
'

--обновление хо
UPDATE A SET 
	A.NAME = C.NAME,
	A.[SYSTEM] = C.[SYSTEM],
	A.[BO] = C.[BO],
	A.[ZP] = C.[ZP],
	A.[RBS] = C.[RBS],
	A.[USED] = C.[USED],
	A.[GZ] = C.[GZ],
	A.[GZ2] = C.[GZ2],
	A.[DO] = C.[DO],
	A.[BO_DT_KT] = C.[BO_DT_KT],
	A.[DO_DT_KT] = C.[DO_DT_KT],
	A.[BO_MIN] = C.[BO_MIN],
	A.[DO_MIN] = C.[DO_MIN]
FROM 
	dbo.XOZ_OPER A
	INNER JOIN dbo.XOZ_OPER_GROUP B ON A.GROUP_LINK = B.LINK
	INNER JOIN #TMP_XOZ_OPER C ON LTRIM(RTRIM(C.GROUP_CODE)) LIKE LTRIM(RTRIM(B.CODE)) AND LTRIM(RTRIM(C.CODE)) LIKE LTRIM(RTRIM(A.CODE))
	
	
INSERT INTO dbo.XOZ_OPER (GROUP_LINK,[CODE],NAME,SYSTEM,BO,ZP,RBS,USED,GZ,GZ2,DO,BO_DT_KT,DO_DT_KT,BO_MIN,DO_MIN)
SELECT B.LINK, A.[CODE], A.NAME, A.SYSTEM, A.BO, A.ZP, A.RBS, A.USED, A.GZ, A.GZ2, A.DO, A.BO_DT_KT, A.DO_DT_KT, A.BO_MIN, A.DO_MIN
FROM
	#TMP_XOZ_OPER A
	INNER JOIN dbo.XOZ_OPER_GROUP B ON LTRIM(RTRIM(A.GROUP_CODE)) LIKE LTRIM(RTRIM(B.CODE))
WHERE
	NOT EXISTS (SELECT * FROM dbo.XOZ_OPER C INNER JOIN dbo.XOZ_OPER_GROUP D ON C.GROUP_LINK = D.LINK
					WHERE 
						LTRIM(RTRIM(D.CODE)) LIKE LTRIM(RTRIM(B.CODE)) AND LTRIM(RTRIM(C.CODE)) LIKE LTRIM(RTRIM(A.CODE)) )

'

INSERT INTO #OUT (TXT)
SELECT 
'
--обновляем журналы
DELETE A
FROM 
	dbo.XOZ_OPER_JURN A 
	INNER JOIN dbo.XOZ_OPER B ON B.LINK = A.XOZ_LINK
	INNER JOIN dbo.XOZ_OPER_GROUP C ON C.LINK = B.GROUP_LINK
WHERE
	EXISTS (SELECT * FROM #TMP_XOZ_OPER T WHERE LTRIM(RTRIM(T.GROUP_CODE)) LIKE LTRIM(RTRIM(C.CODE)) 
				AND LTRIM(RTRIM(T.CODE)) LIKE LTRIM(RTRIM(B.CODE)) )

INSERT INTO dbo.XOZ_OPER_JURN (XOZ_LINK,JURN_LINK,GK)
SELECT 
	A.LINK, D.LINK, C.GK
FROM
	dbo.XOZ_OPER A
	INNER JOIN dbo.XOZ_OPER_GROUP B ON A.GROUP_LINK = B.LINK
	INNER JOIN #TMP_XOZ_OPER_JURN C ON LTRIM(RTRIM(C.GROUP_CODE)) LIKE LTRIM(RTRIM(B.CODE)) AND LTRIM(RTRIM(C.XOZ_CODE)) LIKE LTRIM(RTRIM(A.CODE))
	INNER JOIN dbo.JOURNAL_OPERATION D ON LTRIM(RTRIM(D.code)) LIKE LTRIM(RTRIM(C.JURN_CODE))
WHERE
	NOT EXISTS (SELECT * FROM dbo.XOZ_OPER_JURN E WHERE E.XOZ_LINK = A.LINK AND E.JURN_LINK = D.LINK)

'


INSERT INTO #OUT (TXT)
SELECT 
'
--обновление корректных проводок
DELETE A
FROM 
	dbo.CORRECT_PROV A 
	INNER JOIN dbo.XOZ_OPER B ON B.LINK = A.LINK_HOZ
	INNER JOIN dbo.XOZ_OPER_GROUP C ON C.LINK = B.GROUP_LINK	
WHERE
	EXISTS (SELECT * FROM #TMP_XOZ_OPER T WHERE LTRIM(RTRIM(T.GROUP_CODE)) LIKE LTRIM(RTRIM(C.CODE)) 
				AND LTRIM(RTRIM(T.CODE)) LIKE LTRIM(RTRIM(B.CODE)) )


;WITH tmp AS (
	SELECT 
	XO_LINK		= A.LINK
	,COR_PROV_LINK	= c.link
	FROM
		dbo.XOZ_OPER A
		INNER JOIN dbo.XOZ_OPER_GROUP B ON A.GROUP_LINK = B.LINK
		INNER JOIN #TMP_CORRECT_PROV C ON C.GROUP_CODE LIKE B.CODE AND C.XOZ_CODE LIKE A.CODE
) 
,DT_ACC AS (
	SELECT
		LINK	= t.LINK
		,ACC_LINK	= sa.LINK
	FROM #TMP_CORRECT_PROV t
		INNER JOIN dbo.S_ACCOUNTS sa ON sa.CODE LIKE t.CODE_DT
)
, KT_ACC AS (
	SELECT
		LINK	= t.LINK
		,ACC_LINK	= sa.LINK
	FROM #TMP_CORRECT_PROV t
		INNER JOIN dbo.S_ACCOUNTS sa ON sa.CODE LIKE t.CODE_KT
)
,DT_SGU AS (
	SELECT
		LINK		= t.link
		,SGU_LINK	= k.LINK
	FROM #TMP_CORRECT_PROV t
		INNER JOIN dbo.KOSGU k ON k.code LIKE t.CODE_DT_SGU
)
,KT_SGU AS (
	SELECT
		LINK		= t.link
		,SGU_LINK	= k.LINK
	FROM #TMP_CORRECT_PROV t
		INNER JOIN dbo.KOSGU k ON k.code LIKE t.CODE_DT_SGU
)
INSERT INTO dbo.CORRECT_PROV(LINK_HOZ, LINK_DT, LINK_KT, DT_SGU, KT_SGU)
SELECT 
	c.XO_LINK, SAD.ACC_LINK, SAK.ACC_LINK, GD.SGU_LINK, GK.SGU_LINK
FROM tmp c
	INNER JOIN dt_acc sad ON sad.LINk = c.COR_PROV_LINK
	INNER JOIN kt_acc SAK ON SAK.link = c.COR_PROV_LINK
	LEFT JOIN dt_sgu GD ON gd.LINK = c.COR_PROV_LINK
	LEFT JOIN kt_sgu GK ON gk.LINK = c.COR_PROV_LINK
WHERE
	NOT EXISTS (SELECT 1 FROM dbo.CORRECT_PROV E WHERE E.LINK_HOZ = c.XO_LINK AND E.LINK_DT = SAD.ACC_LINK AND E.LINK_KT = SAK.ACC_LINK 
			AND ISNULL(E.DT_SGU,0) = ISNULL(GD.SGU_LINK,0) AND ISNULL(E.KT_SGU,0) = ISNULL(GK.SGU_LINK,0)  )


'



INSERT INTO #OUT (TXT)
SELECT 
'
--- Переформирование корректных проводок ---
DECLARE
	@BUFER_XO	VARCHAR (100)
	
SET @BUFER_XO = ''SYS_LOAD_XO_'
	+ CASE
		WHEN ISNULL (@GROUP_CODE, '') = '' THEN 'XX'
		ELSE @GROUP_CODE
	END
	+ '_'	
	+ CASE
		WHEN ISNULL (@XOZ_CODE, '') = '' THEN 'XX'
		ELSE @XOZ_CODE
	END
	+ ''''

INSERT INTO #OUT (TXT)
SELECT 
'
INSERT INTO dbo.BUFFER ([ID], LINK)
SELECT
	@BUFER_XO,
	XO.LINK
FROM dbo.XOZ_OPER XO
INNER JOIN dbo.XOZ_OPER_GROUP XOG ON (XOG.LINK = XO.GROUP_LINK)
INNER JOIN #TMP_XOZ_OPER T1 ON (T1.GROUP_CODE = XOG.CODE
	AND T1.CODE = XO.CODE)
'

INSERT INTO #OUT (TXT)
SELECT 
'	

EXEC dbo.XD_CORRECT_PROV_FULL_BY_XO_BUF @BUFER_XO
GO' + CHAR(13) + CHAR(10)


SELECT TXT as [--txt] FROM #OUT ORDER BY ORD

SET NOCOUNT OFF

end


GO


GRANT EXECUTE ON dbo.[UNLOAD_XOZ_OPER] TO PUBLIC

GO


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


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

GO

CREATE   PROCEDURE [dbo].SA_SZV4_PACHKA_CALC_Buffer_2015_6 (@BufferCode varchar(10), @link int, @Year int, @Month tinyint) 
AS
/*
Список изменений по отношению к SA_SZV4_PACHKA_CALC_Buffer4
1. строку с кодом «АДМИНИСТР» исключить
ПОСТАНОВЛЕНИЕ 04 июня 2015 г № 194 п О внесении изменений в постановление Правления Пенсионного фонда Российской Федерации  от 16 января 2014 года  № 2п
п.п б) п. 2.10.5. В разделе «Исчисление страхового стажа: дополнительные сведения» ПРАВЛЕНИЕ ПЕНСИОННОГО ФОНДА РОССИЙСКОЙ ФЕДЕРАЦИИ 
*/
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)

------	у кого была инвалидность в заданном периоде
CREATE TABLE #PERS_INV (PERS_LINK INT, DATE_BEGIN DATETIME, DATE_END DATETIME)

INSERT INTO #PERS_INV (PERS_LINK, DATE_BEGIN, DATE_END) 
SELECT PERS_LINK, DATE_BEGIN = MIN(ISNULL(I.DATE_BEGIN,@PeriodBegin)), DATE_END = MAX(ISNULL(I.DATE_END,@PeriodEnd))
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)

--ЗАМЕНА КАТЕГОРИИ ИНВАЛИДОВ
UPDATE dbo.SZV4_SVEDENIA SET LINK_KATEG = @LINK_NR WHERE link_up = @link AND LINK_KATEG = @LINK_OZOI



---- РАСПРЕДЕЛЕНИЕ ПЕРЕЧИСЛЕННОЙ СУММЫ ПО ФИЗЛИЦАМ
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),	[NOT_LGOT_EXPIR] INT NULL)

	--/*Стаж сотрудников*/
	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 
		([TERR_USL_TRUD],[TERR_RK],[OSOB_USL_TRUD],[COD_POS_SPISOK],[COD_POS_SPISOK2],[USL_DOSROCH_PENS],[STAVKA_PED_MED],[VID],[IS_DOP],[COD_SPO_USL_TRUD])
	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)
	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
*/
	--ПРОЧИЕ КОДЫ ДЛЯ ВИДОВ ОТПУСКОВ
	INSERT INTO #ADD_TYPE (VID, IS_DOP) 	
	SELECT LEFT('P_' + LTRIM(RTRIM(CODE)),20), IS_DOP
	FROM dbo.VACATION_VID 
	WHERE	IS_DOP IS NOT NULL
			AND 
			NOT EXISTS (SELECT * FROM #ADD_TYPE WHERE VID = LEFT('P_' + LTRIM(RTRIM(CODE)),20))


	--Периоды работы на должности 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 
		im.DATE_end3 > st.DATE_BEGIN -- AND st.DATE_END	 -- для случаев если был приказ о переводе на другую должность  
		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],[NOT_LGOT_EXPIR])
	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,
		ISNULL( (SELECT TOP 1 TYPE FROM #ADD_TYPE AT WHERE AT.VID = LEFT('P_' + LTRIM(RTRIM(VV.CODE)),20) AND AT.IS_DOP = VV.IS_DOP ), @TMP_TYPE),
		[NOT_LGOT_EXPIR]
	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 NO_SAL <> 1*/
		INNER JOIN dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK AND WORK_D <> 7 -- Не по уходу за ребенком (Для него свой код)
		left join dbo.item_vacation_break ivb on ivb.vac_link = iv.link and ISNULL(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
		ISNULL(ISNULL(ivb.DATE_BREAK,iv.date_end),'20990101') >= @PeriodBegin

	/*Перерыв - командировки без кодов (для корр. льготных периодов)*/	
	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 DISTINCT
		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 DISTINCT
		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,[NOT_LGOT_EXPIR])
	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 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,'ДЕТИ')))),
		[NOT_LGOT_EXPIR]
	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,[NOT_LGOT_EXPIR])
	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 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,'АДМИНИСТР')))),
		[NOT_LGOT_EXPIR]
	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 #PERIODY WHERE 
			#PERIODY.[NOT_LGOT_EXPIR] = 1
			AND #PERIODY.link_face = #DAYS.link_face
			AND #DAYS.[DATE] BETWEEN #PERIODY.DATE1 AND #PERIODY.DATE2)


		
	--Пронумеровать группы
	DECLARE 
		@ID INT, @ID1 INT, @ID2 INT, @LINK_FACE INT, @DATE datetime, @LINK_KATEG INT, @TYPE INT, @NUM INT, @TYPE_ADD INT,
		@LINK_FACE1 INT, @LINK_KATEG1 INT, @TYPE1 INT,@TYPE_ADD1 INT,@DATE1 datetime

	--Убрать временные периоды, которые заводились для корректировки льготных периодов

------------------  если у сотрудника отпук а сотрудник все это время с дополнительными льготами
-------- период стажевый разделяется на несколько частей (работа - отпуск ежегодный -работа ) , включая отпуск  ... отпуск включать не нужно  
-------- расстановка типов #ADD_TYPE для временных периодов 

----
	SET @TMP_TYPE = (SELECT TOP 1 TYPE FROM #ADD_TYPE WHERE VID = 'TMP_TYPE')
----


	CREATE table #TDays(link_face int, id int,  date DATETIME ,LINK_KATEG int , [TYPE] INT, [TYPE_ADD] INT)
	INSERT INTO #TDays (link_face , id ,   date,LINK_KATEG, [TYPE], [TYPE_ADD])
	SELECT d.link_face,
		   d.id,
		   d.date,
		   d.LINK_KATEG,
		   d.[TYPE],
		   d.[TYPE_ADD]
	FROM #DAYS  d	WHERE d.[type] = @TMP_TYPE
	ORDER BY d.link_face, d.ID ,d.[date], d.[TYPE] ,d.[TYPE_ADD]	 




	DECLARE @Cur0 CURSOR , @F_TYPE int, @F_TYPE_ADD int
	SET @Cur0 = CURSOR FORWARD_ONLY
	FOR SELECT ID, LINK_FACE,[date],LINK_KATEG, [TYPE],  TYPE_ADD from  #TDays order by ID, LINK_FACE, [DATE]
	OPEN @Cur0
	FETCH NEXT FROM @Cur0 INTO @ID, @LINK_FACE,@DATE, @LINK_KATEG, @TYPE, @type_add 
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
				

			SELECT DISTINCT @F_TYPE =[TYPE], @F_TYPE_ADD = [type_add]  
			FROM #DAYS WHERE LINK_FACE = @LINK_FACE AND LINK_KATEG = @LINK_KATEG AND [DATE] = @DATE-1 
			

			UPDATE d
			SET [TYPE] = @F_TYPE ,[type_add] = @F_TYPE_ADD 
			FROM #DAYS d
			WHERE d.ID = @ID AND d.LINK_FACE = @LINK_FACE AND d.[DATE] = @DATE  and d.LINK_KATEG=@LINK_KATEG AND d.[TYPE] = @TMP_TYPE
			
			
			UPDATE td
			SET [TYPE] = @F_TYPE ,[type_add] = @F_TYPE_ADD 
			FROM #TDays td
			WHERE ID = @ID AND LINK_FACE = @LINK_FACE AND [date] = @DATE and LINK_KATEG = @LINK_KATEG AND [TYPE]= @TYPE and type_add = @type_add 
			

		END

		FETCH NEXT FROM @Cur0 INTO @ID, @LINK_FACE,@DATE, @LINK_KATEG, @TYPE, @type_add 
	END

	CLOSE @Cur0
	DEALLOCATE @Cur0
	--

	/*		---------
				UPDATE #DAYS SET [type] = 0 WHERE [type] = @TMP_TYPE
			---------*/

			DROP TABLE #TDays 
-------------

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


--------------------------------------------------------------------------
/* не должно быть физлиц, по которым в данном периоде нет сумм и сведений о стаже 
C 14 ГОДА распределять уплату не нужно
*/	
DELETE FROM dbo.SZV4_SVEDENIA
WHERE 
LINK_UP = @link
AND
EXISTS (		
	Select  1
	from dbo.sa_szv4_svedenia S inner join  dbo.szv4_pachka p on p.link = s.link
	WHERE 
		S.LINK1 = dbo.SZV4_SVEDENIA.LINK
		AND s.sum_doh = 0 AND s.INSUR = 0 AND s.GAIN = 0 AND s.DOP = 0 and s.sum_uplata_dolga_str = 0 and s.sum_uplata_dolga_nak = 0 AND S.INCOME_M1 = 0 
		and p.vid_kor != 3
		AND NOT EXISTS (SELECT * FROM dbo.SZV4_STAZH ST WHERE ST.LINK_UP = S.LINK1)
)



--------------------------------------------------------------------------
exec dbo.SZV4_NUMERATOR @link


GO


GRANT EXECUTE ON dbo.[SA_SZV4_PACHKA_CALC_Buffer_2015_6] TO PUBLIC

GO



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

GO
CREATE   PROCEDURE [dbo].SD_EMPL_INCOM_VKR_VED
	@NMODE	SMALLINT	= 0, 
	@nMONTH INT		= 0,
	@nYEAR	INT		= 0,
	@DEP_LINK INT = NULL,
	@DO_EKR TINYINT = 0 -- вразрезе ЭКР
AS

IF @DEP_LINK IS NULL
	EXEC DBO.XD_WHATS_ZB @DEP_LINK OUTPUT
	
DECLARE @LINK_211EKR INT, @LINK_212EKR INT, @SHOW_212 TINYINT, @LINK_213EKR INT
		  
SET @LINK_211EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '211')
SET @LINK_212EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '212')
SET @LINK_213EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '213')
SET @SHOW_212 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_3')

DECLARE @ESN_213 INT --Начислять страховые взносы на доходы с 213 ЭКР                                                    
SET @ESN_213 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_5')

DECLARE @DATE DATETIME	
SET @DATE = dbo.ConvertDMY2Date(1,@nMONTH,@nYEAR)
SET @DATE = dbo.DateEndOfMonth(@DATE)

SELECT DISTINCT
	LINK= E.PERS_LINK,
	LINK_EMPL= E.LINK,
	TAB_NUM= E.TAB,
	[NAME_EMPL]= RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.', 
	D.[STATUS],
	D.NUM_STAKE,	
	JC.LINK_VKR, 
	NAME_VKR = KBK.CODE,
	LINK_EKR = EKR.LINK,
	CODE_EKR = EKR.CODE
FROM
	DBO.PERSON P with (nolock)
	INNER JOIN DBO.EMPL E with (nolock) ON E.PERS_LINK = P.LINK AND E.DEP_LINK = COALESCE(@DEP_LINK,E.DEP_LINK)
	INNER JOIN DBO.SA_EMPLS_INFO(@DATE, DEFAULT) D ON E.LINK = D.EMPL_LINK	
	INNER JOIN dbo.CALCULATE_JURNAL JC ON JC.LINK_EMPL = E.LINK
	INNER JOIN dbo.PAYS PS ON JC.LINK_PAYS = PS.LINK
	INNER JOIN DBO.SAL_SFIN KBK ON JC.LINK_VKR = KBK.LINK
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = 'R211') R211
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = '211') T211	
	INNER JOIN DBO.KOSGU EKR ON 
		@SHOW_212 = 1 AND (EKR.LINK = (CASE WHEN R211.LINK = JC.LINK_EKR THEN T211.LINK ELSE JC.LINK_EKR END) OR ((CASE WHEN R211.LINK = JC.LINK_EKR THEN T211.LINK ELSE JC.LINK_EKR END) = @LINK_212EKR AND EKR.LINK = @LINK_211EKR)) --Источники с 212 ЭКР дублируем с 211 ЭКР --Временно до конца года
		OR 
		@SHOW_212 = 0 AND EKR.LINK = (CASE WHEN (CASE WHEN R211.LINK = JC.LINK_EKR THEN T211.LINK ELSE JC.LINK_EKR END) <> @LINK_212EKR THEN (CASE WHEN R211.LINK = JC.LINK_EKR THEN T211.LINK ELSE JC.LINK_EKR END) ELSE @LINK_211EKR END)	
		OR 
		@DO_EKR = 1 AND EKR.LINK = (CASE WHEN R211.LINK = JC.LINK_EKR THEN T211.LINK ELSE JC.LINK_EKR END)
WHERE
	E.DEP_LINK = @DEP_LINK
	AND
	PS.[OBJECT] IN (1,2)
	AND
	YEAR(JC.PERIOD_BEGIN) = @nYEAR
	AND
	JC.SUMMA<>0
	AND
	(
		(MONTH(JC.PERIOD_BEGIN) <= @nMONTH AND @NMODE <> 0)
		OR
		(MONTH(JC.PERIOD_BEGIN) = @nMONTH AND @NMODE = 0)
	)
	AND
	(@ESN_213 = 1 OR @ESN_213 = 0 AND EKR.LINK <> @LINK_213EKR)

ORDER BY
	4,6,8


GO


GRANT EXECUTE ON dbo.[SD_EMPL_INCOM_VKR_VED] 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].[RMSGetRecipients]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[RMSGetRecipients]
GO

-- Назначение: возвращет подготовленную строку для вставки в исходящее сообщение сервиса обмена
-- Параметры: 
--   @cWhere - sql запрос, возвращающий линки из таблицы rms_contacts
--   @cRes - возвратное строковое значение со списком получателей
    
-- Пример вызова:
-- exec [dbo].[RMSGetRecipients] @cWhere = 'select record from dbo.get_val_refer(''SERVICE_NSI_NASTR'',''NSI_SERVICE_CLIENTS'',null)', @cRes = @cRes output

-- Keysystems
-- Петров А.Н. 2012

create procedure [dbo].[RMSGetRecipients] 
    @cWhere nvarchar(2000) = ''
   ,@cRes nvarchar(2000) = null output
as   
begin
  declare @cSql nvarchar(2000)
  
  declare @sys_value table (link int, orders int, value nvarchar(2000))     
  declare @RID uniqueidentifier set @RID = newid()
  
  if len(@cWhere)>0
    set @cSql = '
    insert dbo.sys_link(RID,link)
    select distinct @RID, r.link
    from dbo.rms_contacts r
    where r.contact_id in (' + @cWhere + ')'      

  execute sp_ExecuteSQL @cSql,N'@RID uniqueidentifier', @RID=@RID

  declare @Value nvarchar(2000), @Orders integer, @Link integer
  
  insert @sys_value(link,orders,value)
  select r.link, 100, r.address
  from dbo.rms_contacts r
  where r.link in (select link from dbo.syslink(@RID))      
  order by 2,1

  update t set
    @Value  = value = convert(nvarchar(2000), (case when @Link = link and (@Orders = orders or (@Orders is null and orders is null)) then isnull(@Value + ', ', '') else '' end) + isnull(rtrim(ltrim(value)), '')),
    @Link   = link,
    @Orders = orders
  from @sys_value t
  where orders = 100
  
  
--  set @cExecStmt = '
--update t set
--  @Value  = ' + @ValueField + ' = convert(varchar(' + @LenValue + '), (case when @Link = ' + @LinkField + ' and (@Orders = ' + @OrdersField + ' or (@Orders is null and ' + @OrdersField + ' is null)) then isnull(@Value + @Delim, '''') else '''' end) + isnull(rtrim(ltrim(' + @ValueField + ')), '''')),
--  @Link   = ' + @LinkField + ',
--  @Orders = ' + @OrdersField + '
--from ' + @TabName + ' t' + @Where
  
  --select * from @sys_value
  
  select top 1 @cRes = convert(nvarchar(2000),left(max(value),2000)) from @sys_value where orders = 100


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.[BB_DOH_PAY_REPORT]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[BB_DOH_PAY_REPORT]

GO

CREATE PROCEDURE [dbo].BB_DOH_PAY_REPORT
			@dDateB			datetime,
			@dDateE			datetime,
			@nCheck1		tinyint,
			@cVal1 			char(1), 
			@nOtborLink1 	int,
			@cVal2 			char(1), 
			@nOtborLink2 	int,
			@cVal3 			char(1), 
			@nOtborLink3 	int

AS
declare @cCROSS_TABLE char(100)
DECLARE @DEP  TABLE (LINK INT)	
DECLARE @SGU  TABLE (LINK INT)
DECLARE @KBK  TABLE (LINK INT)
declare @iDepLink int
set @iDepLink = isnull(dbo.BK_GetDepZB(),dbo.GetOwnDepLink())

IF LEN (@cVal1) > 0
	INSERT INTO @DEP
	SELECT RECORD
	FROM OBJECT_VAR_DEPARTMENT
	WHERE LINK_UP = @nOtborLink1
ELSE
	INSERT INTO @DEP
	SELECT distinct DA.LINK_UP
	FROM dbo.FINANSE_PAYS P
	left join dbo.DEPARTMENT_ACCOUNTS DA on P.D_ACC = DA.LINK

IF LEN (@cVal2) > 0
	INSERT INTO @SGU
	SELECT RECORD
	FROM OBJECT_VAR_KOSGU
	WHERE LINK_UP = @nOtborLink2
ELSE
	INSERT INTO @SGU
	SELECT LINK
	FROM dbo.KOSGU

IF LEN (@cVal3) > 0
	INSERT INTO @KBK
	SELECT RECORD
	FROM OBJECT_VAR_KBK
	WHERE LINK_UP = @nOtborLink3
ELSE
	INSERT INTO @KBK
	SELECT LINK_KBK
	FROM dbo.KL_KBK_KD


create table #TAB_TEMP(SUMMA NUMERIC(19,2), 
						DOH_CODE varchar(30), 
						DOH_NAME varchar(250), 
						SGU_CODE varchar(3), 
						SGU_NAME varchar(250), 
						D_NAME varchar(255))

create table #TAB_TEMP1(SUMMA NUMERIC(19,2), 
						DOH_CODE varchar(30), 
						SGU_CODE varchar(3))


insert into #TAB_TEMP	    
select SUMMA = sum(G.SUMMA), PA.DOH_CODE, PA.DOH_NAME, PA.SGU_CODE, PA.SGU_NAME, D.NAME 
from dbo.G_PROV G
inner join dbo.FINANSE_PAYS FP on FP.Link = G.LINK
inner join dbo.DEPARTMENT_ACCOUNTS DA on FP.D_Acc = DA.LINK
inner join dbo.DEPARTMENTS D on D.LINK = DA.LINK_UP
inner join dbo.DOCUMENTS_PAY_ADD PA on PA.LINK = G.LINK and PA.DOH_LINK is not null
inner join @DEP DEP on DEP.LINK = D.LINK
inner join @SGU SGU on SGU.LINK = PA.SGU_LINK
inner join @KBK KBK on KBK.LINK = PA.DOH_LINK

where G.DATE_PROV between @dDateB and @dDateE and
		(@nCheck1 = 1 or @nCheck1 = 0 and G.DEP = @iDepLink)
group by PA.DOH_CODE, PA.DOH_NAME, PA.SGU_CODE, PA.SGU_NAME, D.NAME

insert into #TAB_TEMP1	    
select SUMMA = sum(SUMMA), DOH_CODE, SGU_CODE
from dbo.#TAB_TEMP
group by DOH_CODE, SGU_CODE

-- Разворачиваем таблицу по организации
EXEC X_GET_TABLE_NAME @cCROSS_TABLE OUTPUT
EXEC M_CROSS_TABLE 'DOH_CODE, DOH_NAME, SGU_CODE, SGU_NAME', 'D_NAME', 'VARCHAR (250)', 'SUMMA', 'NUMERIC (28,4)', 'SUM (SUMMA) AS SUMMA', '#TAB_TEMP', @cCROSS_TABLE
EXEC ('select  T.*, TI.SUMMA as SUMMAI from ' + @cCROSS_TABLE + ' T
		left join #TAB_TEMP1 TI on T.DOH_CODE = TI.DOH_CODE and T.SGU_CODE = TI.SGU_CODE
		ORDER BY T.DOH_CODE, T.DOH_NAME')

DROP TABLE #TAB_TEMP
DROP TABLE #TAB_TEMP1
EXEC ('DROP TABLE ' + @cCROSS_TABLE)


RETURN




GO


GRANT EXECUTE ON dbo.[BB_DOH_PAY_REPORT] TO PUBLIC

GO


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

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

CREATE PROCEDURE dbo.BK_REPORT_REESTR_DEPON
	@varKSdDate1	DATETIME	,
	@varKSdDate2	DATETIME	,
        @intSVOD_ZB     int     , -- Сводный отчет (ЦБ) --

	@cVal_ACCT char(1), @nOtborLink_ACCT int,	-- Отбор субсчетов --
	@cVal_KBK char(1), @nOtborLink_KBK int,	-- Отбор КБК --
	@cVal_EMPL char(1), @nOtborLink_EMPL int
AS
BEGIN
	DECLARE	@varKSDEP_LINK	INT,
		@varKSDIC_EMP	INT,
		@varKSORGNAME	VARCHAR(254),
		@OKPO	VARCHAR (20),
		@strDATE_NEXT	VARCHAR (10),
		@strREP_NAME	VARCHAR (254)

	SET @intSVOD_ZB = ISNULL (@intSVOD_ZB, 0)
	SET @varKSDEP_LINK = dbo.BK_GetDepZB ()

	IF @intSVOD_ZB = 1 OR @varKSDEP_LINK IS NULL
		SET @varKSDEP_LINK = dbo.GetOwnDepLink()

	SELECT  @varKSORGNAME = [NAME],
		@OKPO = OKPO
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @varKSDEP_LINK

	IF @intSVOD_ZB = 1
		SET @varKSORGNAME = RTRIM (@varKSORGNAME) + ' (ЦБ)'

	SET @strDATE_NEXT = CONVERT (VARCHAR (10), DATEADD (DAY, 1, @varKSdDate2), 104)

	-- Отбор субсчетов --
	DECLARE @ACCT  TABLE (LINK_ACCT INT)	
	IF LEN (@cVal_ACCT) > 0
		INSERT INTO @ACCT
		SELECT RECORD
		FROM dbo.OBJECT_VAR_ACCT
		WHERE LINK_UP = @nOtborLink_ACCT
	ELSE
		INSERT INTO @ACCT
		SELECT ACCT.LINK
		FROM dbo.BK_GetAcctTableByCode ('304', '02', DEFAULT, DEFAULT) ACCT

	--- Отбор КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLink_KBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	-- Отбор сотрудников --
	DECLARE @EMP  TABLE (LINK_EMP [INT], EMP_CODE  [VARCHAR] (20), EMP_NAME [VARCHAR] (254) )
	IF LEN(@cVal_EMPL)>0 BEGIN
		INSERT INTO @EMP
		SELECT OVR.RECORD, D.TAB, D.[NAME_EMPL]
		FROM dbo.OBJECT_VAR_EMPL OVR, dbo.KU_EMPL_PLACING D
		WHERE D.LINK = OVR.RECORD AND OVR.LINK_UP = @nOtborLink_EMPL
	END
	ELSE
	BEGIN
		INSERT INTO @EMP
		SELECT D.LINK_AP, D.AP_CODE, D.AP_NAME 
		FROM dbo.BK_GetTableDictionByAP ('EMP') D
	END

	CREATE TABLE #TABLE1 (DEP [INT], ACCOUNT [INT], EMP [INT], KBK [INT], 	SUMMA [NUMERIC] (20,3),
			ACC1 VARCHAR (30), KBK_CODE VARCHAR (30),
			SUB_CODE VARCHAR (20), SUB_NAME VARCHAR (254),
			EMP_CODE VARCHAR (20), EMP_NAME VARCHAR (254),
			EMP_NAME1 VARCHAR (254))

	INSERT INTO #TABLE1
	SELECT T1.DEP_LINK,
		T1.ACCOUNT,
		T1.EMP,
		T1.KBK,
		T1.SUMMA,
		SA.CODE,
		K1.KBK_CODE,
		X_EMP.SUBDIV_CODE,
		X_EMP.SUBDIV_NAME,
		X_EMP.TAB,
		X_EMP.NAME_EMPL,
		X_EMP.NAME_EMPL1
	FROM dbo.BK_GetTableOborotByDate1 (@varKSdDate1, @varKSdDate2, 1, DEFAULT, DEFAULT) T1
	INNER JOIN @ACCT AC ON (AC.LINK_ACCT = T1.ACCOUNT)
	INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = AC.LINK_ACCT)
	INNER JOIN @TAB_KBK K1 ON (K1.LINK_KBK = T1.KBK)
	INNER JOIN @EMP E1 ON (E1.LINK_EMP = T1.EMP)
	INNER JOIN dbo.XK_EMPL_PLACING_FN (@varKSdDate2) X_EMP ON (X_EMP.LINK = E1.LINK_EMP)
	WHERE (@intSVOD_ZB = 1)
		OR (@intSVOD_ZB = 0 AND T1.DEP_LINK = @varKSDEP_LINK)

	SELECT @varKSORGNAME AS ORGNAME,
		@OKPO AS OKPO,
		CONVERT (VARCHAR (10), @varKSdDate2, 104) AS DOC_DATE,
		*
	FROM #TABLE1 ORDER BY SUB_NAME, EMP_NAME

	DROP TABLE #TABLE1
END

GO


GRANT EXECUTE ON dbo.[BK_REPORT_REESTR_DEPON] TO PUBLIC

GO



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

GO


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

CREATE	PROCEDURE dbo.BI_SAVE_CSR
	@varKSparLINK	int	OUTPUT,
	@varKSparCODE        CHAR(10) = null,
	@varKSparNAME        VARCHAR(250) = null
AS
DECLARE @varKSERROR	tinyint,
	@varKSRowCount INT,
	@varKSstrVALUE	varchar(7000),
	@varKStrancount	int,
	@varKSEventText	varchar(254),
	@varKSintObj		int
SET LOCK_TIMEOUT 30000
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	
	IF EXISTS(Select * FROM KL_TARGET_ITEM Where CODE = @varKSparCODE AND LINK <> @varKSparLINK)
	BEGIN
		ROLLBACK
		RETURN 4
	END
	
	IF @varKSparCODE IS NULL OR len(@varKSparCODE) > 10
	BEGIN
		ROLLBACK
		RETURN 5
	END
	IF @varKSparNAME IS NULL OR @varKSparNAME = ''
	BEGIN
		ROLLBACK
		RETURN 5
	END

	
		UPDATE KL_TARGET_ITEM
		SET 
			CODE = @varKSparCODE,
			NAME = @varKSparNAME
		WHERE LINK = @varKSparLINK
		
		SELECT @varKSRowCount = @@ROWCOUNT, @varKSERROR = @@ERROR
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END

		IF @varKSRowCount = 0
		BEGIN
			INSERT INTO KL_TARGET_ITEM
				(CODE, NAME)
			VALUES (@varKSparCODE, @varKSparNAME)
			SELECT @varKSERROR = @@ERROR, @varKSparLINK = @@IDENTITY
			IF @varKSERROR <> 0
			BEGIN
				ROLLBACK
				RETURN 7
			END
		END
/*		ELSE 
		BEGIN
			UPDATE KL_KBK SET CODE = left(code, 9) + rtrim(@varKSparCODE) + right(rtrim(code),4)
				FROM KL_KBK WHERE link in (select link_kbk from kl_vkr where link_CSR = @varKSparLINK)
		END
*/
	SELECT @varKSintObj = LINK FROM S_OBJECTS WHERE CODE = 'BI_DICTION_CSR'
	EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @varKSEventText, @varKSintObj, 'KL_TARGET_ITEM', @varKSparLINK
IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0












GO


GRANT EXECUTE ON dbo.[BI_SAVE_CSR] TO PUBLIC

GO




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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE  PROCEDURE [dbo].SD_N_VACATION_PROV

@varKSparLINK int,
@varKSparObjCode varchar(30)
AS


if len(rtrim(@varKSparObjCode)) = 0
begin
	RETURN 7
end


IF (SELECT SO.CODE FROM S_OBJECTS SO,SDOC DOC WHERE DOC.LINK = @varKSparLINK AND
		 DOC.OBJECT = SO.LINK) <> @varKSparObjCode
	RETURN 5
	
IF EXISTS (SELECT * FROM DBO.CALCULATE_JURNAL WHERE LINK_DOC = @varKSparLINK)
BEGIN
		RAISERROR('Документ уже проведен!', 11, 1)
		RETURN 0
END	

Declare @varKStrancount int

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

EXEC SALARY_SDOC_FLAG_JC @varKSparLINK,0

IF NOT EXISTS (SELECT * FROM dbo.[KOSGU] WHERE CODE = 'R211')
	INSERT INTO dbo.[KOSGU]([CODE], [NAME], [DB_KR], [Is_Ekr])  
	VALUES ('R211', 'Заработная плата за счет резерва', 1, 1)

DECLARE @DATE DATETIME
SET @DATE = (SELECT S.[DATE] FROM dbo.SDOC S WHERE S.LINK = @varKSparLINK)

/*
Если в настройках по зарплате стоит признак "Использовать резерв"
и у начисления признак (алгоритм) "Отпуск", то подствлять спец ЭКР = R211
*/
DECLARE @LINK_EKR INT
IF isnull((SELECT TOP 1 RESERV FROM dbo.MINROT WHERE PERIOD<=@DATE order by PERIOD DESC),0) > 0
	AND EXISTS (SELECT * FROM dbo.SDOC_AVAC SD INNER JOIN dbo.PAYS P ON SD.LINK_PAY = P.LINK
				WHERE SD.LINK_UP = @varKSparLINK AND P.WAY_CALC = 15)

	SET @LINK_EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = 'R211')

IF @varKSparObjCode = 'DOCUMENTS_ADD_FURLOUGH'
BEGIN

	INSERT INTO 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)
	SELECT [LINK_EMPL] = DOC.REF_EMPL,
		[LINK_PAYS] = DOC.REF_PAY,
		[LINK_DOC] = DOC.LINK,
	  	[PERIOD_BEGIN] = dbo.DateBeginOfMonth(DOC.DATE),	
		[PERIOD_END] = dbo.DateEndOfMonth(DOC.DATE),	
		[DAYS] = TAB.[Day],
		[HOURS] = TAB.[Hour],
		[SUMMA_BASE] =DOC.SUMMA_BASE,
		[SUMMA] = TAB.Summa,
		[ORDERS] = tab.orders,
		[DATE_BEGIN] =TAB.Date1, 
		[DATE_END] = TAB.Date2,
		[LINK_DEP] = DOC.LINK_DEP,
		[LINK_ORG] = NULL,
		[LINK_VKR] = COALESCE(TAB.LINK_KBK,DEF.LINK_KBK),
		[LINK_EKR] = ISNULL(@LINK_EKR,DOC.LINK_EKR)
	FROM dbo.DOCUMENTS_ADD_FUR DOC 
		INNER JOIN dbo.DOCUMENTS_ADD_FUR_TABLE0 TAB on TAB.LINK = DOC.LINK
		INNER JOIN USER_INFO UI on 1=1
		LEFT JOIN dbo.KU_EmplStafKBK(default) DEF ON DEF.LINK_EMPL = DOC.REF_EMPL
	WHERE 
		UI.SID = SUSER_SID()  AND  DOC.LINK = @varKSparLINK  and TAB.Summa<>0
END

DECLARE @CALC_TRAVEL_OPT3 INT
SET @CALC_TRAVEL_OPT3 = dbo.sa_get_option_by_code('CALC_TRAVEL_OPT3')
/*
Опция CALC_TRAVEL_OPT3 устанавливает, каким образом формировать операции по расчету. 
Если опция не установлена, то операции формируются по дате документа (расчета). 
Если опция установлена, то операции формируются по периодам расчета.
*/

IF @varKSparObjCode = 'DOCUMENTS_CALC_TRAVEL'
BEGIN
	INSERT INTO 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)
	SELECT [LINK_EMPL] = DOC.REF_EMPL,
		[LINK_PAYS] = DOC.REF_PAY,
		[LINK_DOC] = DOC.LINK,
	  	[PERIOD_BEGIN] = CASE WHEN @CALC_TRAVEL_OPT3 = 0 THEN dbo.DateBeginOfMonth(DOC.DATE) ELSE dbo.DateBeginOfMonth(TAB.Date1) END,	
		[PERIOD_END] = CASE WHEN @CALC_TRAVEL_OPT3 = 0 THEN dbo.DateEndOfMonth(DOC.DATE) ELSE dbo.DateEndOfMonth(TAB.Date2) END,	
		[DAYS] = TAB.[Day],
		[HOURS] = TAB.[Hour],
		[SUMMA_BASE] =DOC.SUMMA_BASE,
		[SUMMA] = TAB.Summa,
		[ORDERS] = tab.orders,
		[DATE_BEGIN] =TAB.Date1, 
		[DATE_END] = TAB.Date2,
		[LINK_DEP] = DOC.LINK_DEP,
		[LINK_ORG] = NULL,
		[LINK_VKR] = COALESCE(TAB.LINK_KBK,DEF.LINK_KBK),
		[LINK_EKR] = DOC.LINK_EKR
	FROM 
		dbo.DOCUMENTS_CALC_TRAVEL DOC 
		INNER JOIN dbo.DOCUMENTS_ADD_FUR_TABLE0 TAB ON TAB.LINK = DOC.LINK
		INNER JOIN USER_INFO UI ON 1=1
		LEFT JOIN dbo.KU_EmplStafKBK(default) DEF ON DEF.LINK_EMPL = DOC.REF_EMPL
	WHERE UI.SID = SUSER_SID()  AND  DOC.LINK = @varKSparLINK AND TAB.Summa<>0
		and @varKSparObjCode = 'DOCUMENTS_CALC_TRAVEL'
END


IF @varKSparObjCode = 'DOCUMENTS_CALC_AVG'
BEGIN
	INSERT INTO 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)
	SELECT [LINK_EMPL] = DOC.REF_EMPL,
		[LINK_PAYS] = DOC.REF_PAY,
		[LINK_DOC] = DOC.LINK,
	  	[PERIOD_BEGIN] = dbo.DateBeginOfMonth(DOC.DATE),	
		[PERIOD_END] = dbo.DateEndOfMonth(DOC.DATE),	
		[DAYS] = TAB.[Day],
		[HOURS] = TAB.[Hour],
		[SUMMA_BASE] =DOC.SUMMA_BASE,
		[SUMMA] = TAB.Summa,
		[ORDERS] = tab.orders,
		[DATE_BEGIN] =TAB.Date1, 
		[DATE_END] = TAB.Date2,
		[LINK_DEP] = DOC.LINK_DEP ,
		[LINK_ORG] = NULL,
		[LINK_VKR] = COALESCE(TAB.LINK_KBK,DEF.LINK_KBK),
		[LINK_EKR] = ISNULL(@LINK_EKR,DOC.LINK_EKR)
	FROM 
		dbo.DOCUMENTS_CALC_AVG DOC
		INNER JOIN dbo.DOCUMENTS_ADD_FUR_TABLE0 TAB ON TAB.LINK = DOC.LINK
		INNER JOIN dbo.USER_INFO UI ON 1=1
		LEFT JOIN dbo.KU_EmplStafKBK(default) DEF ON DEF.LINK_EMPL = DOC.REF_EMPL
	WHERE UI.SID = SUSER_SID()  AND  DOC.LINK = @varKSparLINK AND TAB.Summa<>0
		and @varKSparObjCode = 'DOCUMENTS_CALC_AVG'
END

EXEC SALARY_SDOC_FLAG_JC @varKSparLINK,1


IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0

GO


GRANT EXECUTE ON dbo.[SD_N_VACATION_PROV] TO PUBLIC

GO

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

GO

--- НАКОПИТЕЛЬНАЯ ВЕДОМОСТЬ ПО РАСХОДУ ПРОДУКТОВ ПИТАНИЯ --- 
CREATE PROCEDURE dbo.PK_REPORT_EXPENSE_FEEDING
	@dDATE_WORK	DATETIME,
	@intLINK_MOL	INT,
	@cVal_KBK char(1), @nOtborLinkKBK int,	-- Отбор КБК 
	@cVal_DOP char(1), @nOtborLinkDOP int	--  Отбор по доп. классификации 
AS
BEGIN
	DECLARE
		@dDATE_BEGIN	DATETIME,
		@cMONTH_NAME	VARCHAR (20),
		@cDEP_NAME	VARCHAR (254),
		@cDEP_OKPO	VARCHAR (20),
		@intDEP_LINK	INT,
		@TAB_INVENTORY	VARCHAR (100),
		@strEXEC	VARCHAR (4000),
		@intCOUNTER		INT,
		@cCOUNTER		VARCHAR (10),
		@intMAX_REC		INT,
		@intCOUNT_COLROW	INT

	SET @dDATE_BEGIN = dbo.DateBeginOfMonth (@dDATE_WORK)
	SELECT @cMONTH_NAME = MON FROM dbo.MONTHS WHERE NUM = MONTH (@dDATE_WORK)

	SELECT @intDEP_LINK = LINK,
		@cDEP_NAME = [NAME],
		@cDEP_OKPO = OKPO 
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = COALESCE (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())

	--- ОТБОР КБК --- 
	DECLARE @TAB_KBK TABLE (LINK_KBK INT, KBK_CODE VARCHAR (30))
	IF LEN (@cVal_KBK) > 0
		INSERT INTO @TAB_KBK
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.KL_KBK AP 
		INNER JOIN dbo.OBJECT_VAR_KBK OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkKBK
	ELSE
		INSERT INTO @TAB_KBK
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('KBK')

	--- ОТБОР ПО доп классификации --- 
	DECLARE @TAB_DOP TABLE (LINK_DOP INT, DOP_CODE VARCHAR (20))
	IF LEN (@cVal_DOP) > 0
		INSERT INTO @TAB_DOP
		SELECT AP.LINK,
			AP.CODE
		FROM dbo.DOP_CLASSIF AP 
		INNER JOIN dbo.OBJECT_VAR_DOP_CLASSIF OVR ON (OVR.RECORD = AP.LINK)
		WHERE OVR.LINK_UP = @nOtborLinkDOP
	ELSE
		INSERT INTO @TAB_DOP
		SELECT LINK_AP, AP_CODE
		FROM dbo.BK_GetTableDictionByAP ('AP2')

	DECLARE @TAB0 TABLE
		(LINK_DOC INT,
		QTY NUMERIC (28,4))
		
	INSERT INTO	@TAB0
	SELECT
		LINK_DOC,
		SUM (QTY)
	FROM dbo.PV_MENU_EATING
	GROUP BY LINK_DOC
		
	--- ПРОВОДКИ КРЕДИТОВЫЕ --- 
	CREATE TABLE #TABLE_PROV
		(DOC_PROV DATETIME,
		MDAY TINYINT,
		NDOC VARCHAR (30),
		PE NUMERIC (28, 4),
		EMP INT,
		NOMEN INT, 
		QTY NUMERIC (28,4),
		SUMMA NUMERIC (28,4))

	INSERT INTO #TABLE_PROV
	SELECT
		GP.DATE_PROV,
		DAY (GP.DATE_PROV),
		GP.NUMBER,
		ISNULL (T1.QTY, 0),
		GP.KT_EMP,
		GP.KT_NOMEN,
		GP.QUANTITY,
		GP.SUMMA
	FROM dbo.AProvByBufferConditionsShort (@dDATE_BEGIN, @dDATE_WORK, DEFAULT, DEFAULT) GP
	INNER JOIN dbo.BK_GetAcctTableByCode ('105', '02, 12, 22, 32, 42', DEFAULT, DEFAULT) AC
				ON (AC.LINK = GP.KT_ACCOUNT)
	INNER JOIN @TAB_KBK K ON (K.LINK_KBK = ISNULL (GP.KT_VKR, 0))
	INNER JOIN @TAB_DOP D ON (D.LINK_DOP = GP.KT_AP2)
	LEFT OUTER JOIN @TAB0 T1 ON (T1.LINK_DOC = GP.LINK)
	WHERE GP.KT_EMP = @intLINK_MOL
		AND GP.DEP_LINK = @intDEP_LINK

--SELECT * FROM #TABLE_PROV
--SELECT * FROM dbo.AProvByBufferConditionsShort (@dDATE_BEGIN, @dDATE_WORK, DEFAULT, DEFAULT) GP

	EXEC dbo.X_GET_TABLE_NAME @TAB_INVENTORY OUTPUT

	--- Продукты --- 
	EXEC dbo.M_CROSS_TABLE 'NOMEN', 'MDAY',
				'INT',
				'QTY, PE',
				'NUMERIC (28,4)#NUMERIC (28,4)',
				'SUM (QTY) AS QTY, SUM (PE) AS PE',
				'#TABLE_PROV',
				@TAB_INVENTORY

	--- Готовим для вывода --- 
	SET @intMAX_REC = 27
	SELECT @intCOUNTER = COUNT (*) FROM (SELECT MDAY, NDOC
						FROM #TABLE_PROV
						GROUP BY MDAY, NDOC) S1
	SET @intCOUNTER = ISNULL (@intCOUNTER, 0)
	SET @intCOUNT_COLROW = @intCOUNTER
	WHILE @intCOUNTER < @intMAX_REC
	BEGIN
		SET @intCOUNTER = @intCOUNTER + 1
		SET @cCOUNTER = LTRIM (STR (@intCOUNTER))
	
 		SET @strEXEC = 'ALTER TABLE ' + @TAB_INVENTORY		
			+ ' ADD MDAY_' + @cCOUNTER + ' INT '
			+ ', QTY_' + @cCOUNTER + ' [NUMERIC] (28,4)'
			+ ', PE_' + @cCOUNTER + ' [NUMERIC] (28,4)'
		EXECUTE (@strEXEC)
	END

	--- Общие итоги --- 
	CREATE TABLE #TAB_TOTAL (INV INT, PRICE NUMERIC (28,4), QTY NUMERIC (28,4), SUMMA NUMERIC (28,4))
	INSERT INTO #TAB_TOTAL 
	SELECT NOMEN,
		0,
		SUM (QTY),
		SUM (SUMMA)
	FROM #TABLE_PROV
	GROUP BY NOMEN 

	UPDATE #TAB_TOTAL SET PRICE = SUMMA / QTY
	WHERE QTY <> 0
--SELECT * FROM #TAB_TOTAL

	--- Вывод данных --- 
	SET @strEXEC = 'SELECT ISNULL (T2.CODE, '''') AS INV_CODE, ISNULL (T2.NAME, '''') AS INV_NAME, '
		+ 'ISNULL (T2.NAME_UM, '''') AS UM_NAME, '
		+ 'ISNULL (T3.PRICE, 0) AS PRICE, '
		+ 'ISNULL (T3.QTY, 0) AS TOTAL_QTY, '
		+ 'ISNULL (T3.SUMMA, 0) AS TOTAL_SUM, '
		+ ' T1.* FROM ' + @TAB_INVENTORY
		+ ' T1 LEFT OUTER JOIN BV_NOMENCLATURE T2 '
		+ ' ON (T2.LINK = T1.NOMEN)'
		+ ' LEFT OUTER JOIN #TAB_TOTAL T3 ON (T3.INV = T1.NOMEN) ORDER BY 2 '
	exec (@strEXEC)

	-- Шапка документа --- 
	SELECT ISNULL (@cDEP_NAME, '') AS DEP_NAME,
		ISNULL (@cDEP_OKPO, '') AS DEP_OKPO,
		ISNULL (@cMONTH_NAME, '') AS MONTH_NAME,
		ISNULL (YEAR (@dDATE_WORK), 0) AS DYEAR,
		ISNULL (dbo.SD_GetEmplName (@intLINK_MOL), '') AS EMP_NAME,
		ISNULL ((SELECT POST_NAME FROM KU_EMPL_PLACING WHERE LINK = @intLINK_MOL), '') AS EMP_POST

	EXEC ('DROP TABLE ' + @TAB_INVENTORY)
	
	DROP TABLE #TABLE_PROV
	DROP TABLE #TAB_TOTAL
END



GO


GRANT EXECUTE ON dbo.[PK_REPORT_EXPENSE_FEEDING] TO PUBLIC

GO




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

GO

CREATE   PROCEDURE dbo.SA_PRINT_TABEL_421m
	@varKSnLINKDoc INT,
	@varKSnOption1 INT= 1,
	@varKSnCheck1 INT = 0,
	@nSort3 int = 0 /*сортировка 3*/,
	@nCheck3 tinyint = 0 /*Фио полностью*/,
	@nCheck5 tinyint = 0 /* Пустой табель */,
	@varKSSUBDIV VARCHAR(254) OUTPUT, 
	@varKSSUBDIV_CODE VARCHAR(10) OUTPUT,
	@varKSDIV_CODE VARCHAR(10) OUTPUT, 
	@varKSDIV_NAME VARCHAR(254) OUTPUT,
	@varKSTI_CODE VARCHAR(10) OUTPUT, 
	@varKSTI_NAME VARCHAR(254) OUTPUT,
	@varKSEXP_CODE VARCHAR(10) OUTPUT, 
	@varKSEXP_NAME VARCHAR(254) OUTPUT

AS
BEGIN

	declare @varKSdDate1 DATETIME, @varKSdDate2 DATETIME
	SELECT @varKSdDate1 = PERIOD FROM TABELS WHERE LINK_DOC = @varKSnLINKDoc
	SELECT @varKSdDate1 = dbo.DateBeginOfMonth(@varKSdDate1)
	SELECT @varKSdDate2 = dbo.DateEndOfMonth(@varKSdDate1)

	CREATE TABLE #T_RES00 (
		ID VARCHAR(20),
		LINK_FACE INT, 
		LINK_EMPL INT,
		LINK_SOVM INT,
		FIO VARCHAR(254),
		NAME_EMPL VARCHAR(254),
		TN VARCHAR(10) ,
		SUBDIV_LINK INT, 
		CODE_SUB VARCHAR(10),
		SUBDIV VARCHAR(254) ,
		POST_LINK INT,
		CODE_POST VARCHAR(10),
		POST VARCHAR(254) ,
		
		DAY_1 VARCHAR(4),	DAY_2 VARCHAR(4),	DAY_3 VARCHAR(4),	DAY_4 VARCHAR(4),	DAY_5 VARCHAR(4),
		DAY_6 VARCHAR(4),	DAY_7 VARCHAR(4),	DAY_8 VARCHAR(4),	DAY_9 VARCHAR(4),	DAY_10 VARCHAR(4),
		DAY_11 VARCHAR(4),	DAY_12 VARCHAR(4),	DAY_13 VARCHAR(4),	DAY_14 VARCHAR(4),	DAY_15 VARCHAR(4),
		DAY_16 VARCHAR(4),	DAY_17 VARCHAR(4),	DAY_18 VARCHAR(4),	DAY_19 VARCHAR(4),	DAY_20 VARCHAR(4),
		DAY_21 VARCHAR(4),	DAY_22 VARCHAR(4),	DAY_23 VARCHAR(4),	DAY_24 VARCHAR(4),	DAY_25 VARCHAR(4),
		DAY_26 VARCHAR(4),	DAY_27 VARCHAR(4),	DAY_28 VARCHAR(4),	DAY_29 VARCHAR(4),	DAY_30 VARCHAR(4),
		DAY_31 VARCHAR(4),
		
		HALF_D INT, --HALF_H NUMERIC(6,2), 	
		--HALF2_D INT, HALF2_H NUMERIC(6,2), 	
		--ALL_D INT, ALL_H NUMERIC(6,2), 		
		NONE_DAYS INT, 
		--NONE_HOURS NUMERIC(6,2)	,
		
		TYPE_1 INT, 
		--TYPE_1H NUMERIC(6,2),
		--TYPE_2H INT, 
		TYPE_2 NUMERIC(6,2), 
		TYPE_3 INT, TYPE_4 INT, TYPE_5 INT, TYPE_6 INT, TYPE_7 INT, TYPE_8 INT, TYPE_9 INT, 
		--TYPE_10 INT, 
		TYPE_11 INT, 
		--TYPE_12 INT,

		--TYPE_13 INT,	-- ОТРАБОТАНО В МЕСЯЦ СВЕРУХРОЧНЫХ ЧАСОВ
		--TYPE_14 INT,	-- ОТРАБОТАНО В МЕСЯЦ НОЧНЫХ ЧАСОВ
		--TYPE_15 INT,	-- ОТРАБОТАНО В МЕСЯЦ ЧАСОВ В ВЫХОДНЫЕ И ПРАЗДНИЧНЫЕ ДНИ
	) 

	---
	DECLARE @ISMINUTES TINYINT
	SET @ISMINUTES = DBO.SA_GET_OPTION_BY_CODE('TABEL_OPT10') --УЧЕТ ВРЕМЕНИ В ЧАСАХ И МИНУТАХ

	---
	declare @def_tdlink int, @def_tdname varchar(254), @def_tdsymb varchar(4)
	Select @def_tdlink = LINK, @def_tdname = [NAME], @def_tdsymb = SYMB from dbo.TYP_DAYS where WORK_D = 1 AND TYP_YAVKA = 1

	select  LINK_DOC, NUMBER, DATE, LINK_EMPL, PERIOD, [DAY], 
		SUM([HOUR]) as [HOUR], 
		MAX(WORK_D) as WORK_D,
		MAX(TYP_YAV) AS TYP_YAV,
		(CASE when count(TYPE_DAY) = 1 then MAX(TYPE_DAY) else @def_tdlink end) as TYPE_DAY,
		(CASE when count(SYMB) = 1 then MAX(SYMB) else @def_tdsymb end) as SYMB,	
		(CASE when count(SYMB) = 1 then MAX(TYPE_DATY_NAME) else @def_tdname end) as TYPE_DATY_NAME
	into #tabel 
	from TABEL WHERE LINK_DOC = @varKSnLINKDoc
	group by LINK_DOC, NUMBER, DATE, LINK_EMPL, PERIOD, [DAY]
--	having count(SYMB) > 1
--AND TYPE_DAY not in (Select KOD from [dbo].[SA_TYPES_DOP_TAB])

	--- Информация об отработанных днях
	SELECT W.LINK_UP1, W.LINK_SOVM,
	DAYS_H1 = 
		CASE WHEN SUM(W.D1) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D2) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D3) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D4) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D5) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D6) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D7) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D8) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D9) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D10) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D11) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D12) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D13) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D14) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D15) > 0 THEN 1 ELSE 0 END,

	DAYS_H2 = 
		CASE WHEN SUM(W.D16) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D17) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D18) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D19) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D20) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D21) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D22) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D23) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D24) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D25) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D26) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D27) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D28) > 0 THEN 1 ELSE 0 END
	+	CASE WHEN SUM(W.D29) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D30) > 0 THEN 1 ELSE 0 END 
	+	CASE WHEN SUM(W.D31) > 0 THEN 1 ELSE 0 END,
	

	[HOURS] = 
			DBO.MINUTES_TO_NUM( 
			SUM(
			DBO.NUM_TO_MINUTES(W.D1,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D2,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D3,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D4,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D5,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D6,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D7,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D8,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D9,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D10,@ISMINUTES)

		+	DBO.NUM_TO_MINUTES(W.D11,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D12,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D13,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D14,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D15,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D16,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D17,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D18,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D19,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D20,@ISMINUTES)

		+	DBO.NUM_TO_MINUTES(W.D21,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D22,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D23,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D24,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D25,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D26,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D27,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D28,@ISMINUTES)
		+	DBO.NUM_TO_MINUTES(W.D29,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D30,@ISMINUTES) +	DBO.NUM_TO_MINUTES(W.D31,@ISMINUTES)
		)
		,@ISMINUTES)
	INTO 
		#WORK_DAYS
	FROM 
		DBO.SA_TABELS_W W
	WHERE 
		LINK_UP = @varKSnLINKDoc
	GROUP BY 
		W.LINK_UP1, W.LINK_SOVM
		
	--- Информация об отработанных днях
	SELECT W.LINK_UP1, W.LINK_SOVM,
	DAYS_Y7 = 
			CASE WHEN SUM(W.D1) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D2) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D3) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D4) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D5) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D6) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D7) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D8) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D9) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D10) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D11) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D12) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D13) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D14) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D15) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D16) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D17) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D18) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D19) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D20) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D21) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D22) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D23) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D24) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D25) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D26) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D27) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D28) > 0 THEN 1 ELSE 0 END
		+	CASE WHEN SUM(W.D29) > 0 THEN 1 ELSE 0 END +	CASE WHEN SUM(W.D30) > 0 THEN 1 ELSE 0 END 
		+	CASE WHEN SUM(W.D31) > 0 THEN 1 ELSE 0 END
	INTO 
		#WORK_DAYS1
	FROM 
		DBO.SA_TABELS_W W
	WHERE 
		LINK_UP = @varKSnLINKDoc
		AND
		TYP_YAVKA = 7
	GROUP BY 
		W.LINK_UP1, W.LINK_SOVM		

	--- Информация о неявках сотрудников
	SELECT 
		N.LINK_UP1,
		T.WORK_D,
		COUNT_DAYS = 
			CASE WHEN N.D1 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D2 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D3 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D4 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D5 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D6 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D7 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D8 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D9 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D10 = T.LINK THEN 1 ELSE 0 END

			+ CASE WHEN N.D11 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D12 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D13 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D14 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D15 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D16 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D17 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D18 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D19 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D20 = T.LINK THEN 1 ELSE 0 END

			+ CASE WHEN N.D21 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D22 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D23 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D24 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D25 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D26 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D27 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D28 = T.LINK THEN 1 ELSE 0 END
			+ CASE WHEN N.D29 = T.LINK THEN 1 ELSE 0 END + CASE WHEN N.D30 = T.LINK THEN 1 ELSE 0 END 
			+ CASE WHEN N.D31 = T.LINK THEN 1 ELSE 0 END 
	INTO 
		#NOTWORK_DAYS
	FROM
		DBO.SA_TABELS_N N, DBO.TYP_DAYS T
	WHERE
		LINK_UP = @varKSnLINKDoc

	CREATE TABLE #WS (LINK_EMPL INT, LINK_SOVM INT,
		W1 VARCHAR(6), W2 VARCHAR(6), W3 VARCHAR(6), W4 VARCHAR(6), W5 VARCHAR(6), W6 VARCHAR(6), W7 VARCHAR(6), W8 VARCHAR(6), W9 VARCHAR(6), W10 VARCHAR(6),
		W11 VARCHAR(6), W12 VARCHAR(6), W13 VARCHAR(6), W14 VARCHAR(6), W15 VARCHAR(6), W16 VARCHAR(6), W17 VARCHAR(6), W18 VARCHAR(6), W19 VARCHAR(6), W20 VARCHAR(6), 
		W21 VARCHAR(6), W22 VARCHAR(6), W23 VARCHAR(6), W24 VARCHAR(6), W25 VARCHAR(6), W26 VARCHAR(6), W27 VARCHAR(6), W28 VARCHAR(6), W29 VARCHAR(6), W30 VARCHAR(6), W31 VARCHAR(6)
		)
	---
	INSERT INTO #WS
	SELECT 
		WP.LINK_EMPL, WP.LINK_SOVM, 
		W1 = LEFT(MAX(CASE WHEN W.D1 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W2 = LEFT(MAX(CASE WHEN W.D2 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W3 = LEFT(MAX(CASE WHEN W.D3 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W4 = LEFT(MAX(CASE WHEN W.D4 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W5 = LEFT(MAX(CASE WHEN W.D5 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W6 = LEFT(MAX(CASE WHEN W.D6 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W7 = LEFT(MAX(CASE WHEN W.D7 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W8 = LEFT(MAX(CASE WHEN W.D8 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W9 = LEFT(MAX(CASE WHEN W.D9 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W10 = LEFT(MAX(CASE WHEN W.D10 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),

		W11 = LEFT(MAX(CASE WHEN W.D11 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W12 = LEFT(MAX(CASE WHEN W.D12 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W13 = LEFT(MAX(CASE WHEN W.D13 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W14 = LEFT(MAX(CASE WHEN W.D14 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W15 = LEFT(MAX(CASE WHEN W.D15 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W16 = LEFT(MAX(CASE WHEN W.D16 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W17 = LEFT(MAX(CASE WHEN W.D17 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W18 = LEFT(MAX(CASE WHEN W.D18 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W19 = LEFT(MAX(CASE WHEN W.D19 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W20 = LEFT(MAX(CASE WHEN W.D20 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),

		W21 = LEFT(MAX(CASE WHEN W.D21 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W22 = LEFT(MAX(CASE WHEN W.D22 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W23 = LEFT(MAX(CASE WHEN W.D23 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W24 = LEFT(MAX(CASE WHEN W.D24 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W25 = LEFT(MAX(CASE WHEN W.D25 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W26 = LEFT(MAX(CASE WHEN W.D26 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W27 = LEFT(MAX(CASE WHEN W.D27 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W28 = LEFT(MAX(CASE WHEN W.D28 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W29 = LEFT(MAX(CASE WHEN W.D29 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),
		W30 = LEFT(MAX(CASE WHEN W.D30 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6),

		W31 = LEFT(MAX(CASE WHEN W.D31 <> 0 THEN SPACE((ISNULL(DOP_TAB-1,0))*2) + SYMB ELSE '' END),6)
	FROM 
		DBO.TABELS T 
		INNER JOIN DBO.SA_TABELS_EMPLS TE ON T.LINK = TE.LINK
		INNER JOIN DBO.SA_TABELS_EMPLS_WP WP ON TE.LINK = WP.LINK_UP1
		LEFT JOIN DBO.TABELS_W W ON TE.LINK = W.link_up AND WP.LINK_SOVM = COALESCE(W.link_sovm,0)
		LEFT JOIN dbo.TYP_DAYS TD ON TD.LINK = W.LINK_DAY
	WHERE			
		T.LINK_DOC = @varKSnLINKDoc
	GROUP BY 
		WP.LINK_EMPL, WP.LINK_SOVM		
	ORDER BY
		 WP.LINK_EMPL, WP.LINK_SOVM

	---
	CREATE TABLE #S (LINK_EMPL INT, LINK_SOVM INT,
		W1 VARCHAR(4), W2 VARCHAR(4), W3 VARCHAR(4), W4 VARCHAR(4), W5 VARCHAR(4), W6 VARCHAR(4), W7 VARCHAR(4), W8 VARCHAR(4), W9 VARCHAR(4), W10 VARCHAR(4),
		W11 VARCHAR(4), W12 VARCHAR(4), W13 VARCHAR(4), W14 VARCHAR(4), W15 VARCHAR(4), W16 VARCHAR(4), W17 VARCHAR(4), W18 VARCHAR(4), W19 VARCHAR(4), W20 VARCHAR(4), 
		W21 VARCHAR(4), W22 VARCHAR(4), W23 VARCHAR(4), W24 VARCHAR(4), W25 VARCHAR(4), W26 VARCHAR(4), W27 VARCHAR(4), W28 VARCHAR(4), W29 VARCHAR(4), W30 VARCHAR(4), W31 VARCHAR(4)
		 )	

	INSERT INTO #S (LINK_EMPL, LINK_SOVM, W1, W2, W3, W4, W5, W6, W7, W8, W9, W10, W11, W12, W13, W14, W15, W16, W17, W18, W19, W20, W21, W22, W23, W24, W25, W26, W27, W28, W29, W30, W31 )
	SELECT 
		T.LINK_EMPL, T.LINK_SOVM,
		LTRIM(RTRIM(MAX(W1))), LTRIM(RTRIM(MAX(W2))), LTRIM(RTRIM(MAX(W3))), LTRIM(RTRIM(MAX(W4))), LTRIM(RTRIM(MAX(W5))), LTRIM(RTRIM(MAX(W6))), LTRIM(RTRIM(MAX(W7))), LTRIM(RTRIM(MAX(W8))), LTRIM(RTRIM(MAX(W9))), LTRIM(RTRIM(MAX(W10))), 
		LTRIM(RTRIM(MAX(W11))), LTRIM(RTRIM(MAX(W12))), LTRIM(RTRIM(MAX(W13))), LTRIM(RTRIM(MAX(W14))), LTRIM(RTRIM(MAX(W15))), LTRIM(RTRIM(MAX(W16))), LTRIM(RTRIM(MAX(W17))), LTRIM(RTRIM(MAX(W18))), LTRIM(RTRIM(MAX(W19))), LTRIM(RTRIM(MAX(W20))), 
		LTRIM(RTRIM(MAX(W21))), LTRIM(RTRIM(MAX(W22))), LTRIM(RTRIM(MAX(W23))), LTRIM(RTRIM(MAX(W24))), LTRIM(RTRIM(MAX(W25))), LTRIM(RTRIM(MAX(W26))), LTRIM(RTRIM(MAX(W27))), LTRIM(RTRIM(MAX(W28))), LTRIM(RTRIM(MAX(W29))), LTRIM(RTRIM(MAX(W30))), LTRIM(RTRIM(MAX(W31))) 
	FROM
	(	
		SELECT 
			LINK_EMPL, LINK_SOVM, W1, W2, W3, W4, W5, W6, W7, W8, W9, W10, W11, W12, W13, W14, W15, W16, W17, W18, W19, W20, W21, W22, W23, W24, W25, W26, W27, W28, W29, W30, W31 
		FROM #WS
		UNION ALL
		SELECT 
			WP.LINK_EMPL, WP.LINK_SOVM, 
			SPACE(4) + ISNULL(SYMB1,''), SPACE(4) + ISNULL(SYMB2,''), SPACE(4) + ISNULL(SYMB3,''), SPACE(4) + ISNULL(SYMB4,''), SPACE(4) + ISNULL(SYMB5,''), SPACE(4) + ISNULL(SYMB6,''), SPACE(4) + ISNULL(SYMB7,''), SPACE(4) + ISNULL(SYMB8,''), SPACE(4) + ISNULL(SYMB9,''), SPACE(4) + ISNULL(SYMB10,''),
			SPACE(4) + ISNULL(SYMB11,''), SPACE(4) + ISNULL(SYMB12,''), SPACE(4) + ISNULL(SYMB13,''), SPACE(4) + ISNULL(SYMB14,''), SPACE(4) + ISNULL(SYMB15,''), SPACE(4) + ISNULL(SYMB16,''), SPACE(4) + ISNULL(SYMB17,''), SPACE(4) + ISNULL(SYMB18,''), SPACE(4) + ISNULL(SYMB19,''), SPACE(4) + ISNULL(SYMB20,''), 
			SPACE(4) + ISNULL(SYMB21,''), SPACE(4) + ISNULL(SYMB22,''), SPACE(4) + ISNULL(SYMB23,''), SPACE(4) + ISNULL(SYMB24,''), SPACE(4) + ISNULL(SYMB25,''), SPACE(4) + ISNULL(SYMB26,''), SPACE(4) + ISNULL(SYMB27,''), SPACE(4) + ISNULL(SYMB28,''), SPACE(4) + ISNULL(SYMB29,''), SPACE(4) + ISNULL(SYMB30,''), SPACE(4) + ISNULL(SYMB31,'')
		FROM 
			DBO.TABELS T 
			INNER JOIN DBO.SA_TABELS_EMPLS TE ON T.LINK = TE.LINK
			INNER JOIN DBO.SA_TABELS_EMPLS_WP WP ON TE.LINK = WP.LINK_UP1
			LEFT JOIN DBO.SA_TABELS_N N ON TE.LINK = N.LINK_UP1
		WHERE			
			T.LINK_DOC = @varKSnLINKDoc
	) T
	GROUP BY
		T.LINK_EMPL, T.LINK_SOVM
	ORDER BY 1,2

	
	INSERT INTO #T_RES00
		(ID,LINK_FACE, LINK_EMPL, LINK_SOVM, FIO, NAME_EMPL, TN, SUBDIV_LINK, CODE_SUB, SUBDIV, POST_LINK, CODE_POST, POST,

		DAY_1,  DAY_2,  DAY_3,  DAY_4,  DAY_5,  DAY_6,  DAY_7,  DAY_8,  DAY_9,  DAY_10, 
		DAY_11, DAY_12, DAY_13, DAY_14, DAY_15, DAY_16, DAY_17, DAY_18, DAY_19, DAY_20, 
		DAY_21, DAY_22, DAY_23, DAY_24, DAY_25, DAY_26, DAY_27, DAY_28, DAY_29, DAY_30, DAY_31,
		HALF_D,
		NONE_DAYS, 

		TYPE_1, 

		TYPE_2, 

		TYPE_3, TYPE_4, TYPE_5, TYPE_6, TYPE_7, TYPE_8, TYPE_9, 

		TYPE_11 

	)
	SELECT
		ID = RIGHT( REPLACE(SPACE(20),SPACE(1),'0') + CONVERT(VARCHAR(20),WP.LINK_EMPL),10) +RIGHT( REPLACE(SPACE(20),SPACE(1),'0') + CONVERT(VARCHAR(20),WP.LINK_SOVM),10) ,
		[LINK_FACE] = P.LINK,
		WP.LINK_EMPL,
		WP.LINK_SOVM,
		[FIO]  = (case when coalesce(@nCheck3,0) = 1 then  coalesce(LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(P.FM)) + ' ' + LTRIM(RTRIM(P.IM)) + ' ' + LTRIM(RTRIM(P.OT)),'Не заполнено'))),100), SPACE(100)) 
					else coalesce(LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(FM)) + ' ' + LEFT(LTRIM(RTRIM(IM)),1) + '.' + LEFT(LTRIM(RTRIM(OT)),1) + '.', 'Не заполнено'))),30), SPACE(100)) end),
		[NAME_EMPL] = LEFT(LTRIM(RTRIM(COALESCE(LTRIM(RTRIM(FM)) + ' ' + LEFT(LTRIM(RTRIM(IM)),1) + '.' + LEFT(LTRIM(RTRIM(OT)),1) + '.', 'Не заполнено'))),30),
		[TN] 		= ISNULL(TE.TAB, SPACE(10)),
		[SUBDIV_LINK] = TE.SUBDIV_LINK,
		[CODE_SUB] = ISNULL( TE.SUBDIV_CODE, SPACE(10) ),
		[SUBDIV] = ISNULL( TE.SUBDIV_NAME, SPACE(254) ),
		[POST_LINK] = WP.POST_LINK,
		[CODE_POST] = ISNULL( WP.POST_CODE, SPACE(10) ),
		[POST] 		= ISNULL( WP.POST_NAME, SPACE(120) ),

		W1, W2, W3, W4, W5, W6, W7, W8, W9, W10, 
		W11, W12, W13, W14, W15, W16, W17, W18, W19, W20, 
		W21, W22, W23, W24, W25, W26, W27, W28, W29, W30, W31, 
		[HALF_D] = case when @nCheck5 = 1 then 0 else isnull(WD.DAYS_H1,0) END,
		--
		[NONE_DAYS] = case when @nCheck5 = 1 then 0 else ISNULL((SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1),0) end,
		--Дни явок		
		[TYPE_1] = case when @nCheck5 = 1 then 0 else ISNULL(WD.DAYS_H1,0) + ISNULL(WD.DAYS_H2,0) end,
		----Часы явок
		[TYPE_2] = case when @nCheck5 = 1 then 0 else ISNULL((SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D = 2),0) + ISNULL(Y.DAYS_Y7,0) end,		-- командировка (дни)
		[TYPE_3] = case when @nCheck5 = 1 then 0 else ISNULL((SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D = 3),0) end,		-- повышение квалификации (дни)
		[TYPE_4] = case when @nCheck5 = 1 then 0 else ISNULL((SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D = 4),0) end,		-- очередной ежегодный отпуск НЕЯВКА (дни)
		[TYPE_5] = case when @nCheck5 = 1 then 0 else ISNULL((SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D = 5),0) end,		-- учебный отпуск НЕЯВКА (дни)
		[TYPE_6] = case when @nCheck5 = 1 then 0 else ISNULL((SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D = 6),0) end,		-- больничный НЕЯВКА (дни)
		[TYPE_7] = case when @nCheck5 = 1 then 0 else ISNULL((SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D IN (7,13)),0) end, 	-- уход за ребенком НЕЯВКА (дни)
		[TYPE_8] = case when @nCheck5 = 1 then 0 else ISNULL((SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D = 8),0) end,		-- с разрешения администрации НЕЯВКА (дни)
		[TYPE_9] = case when @nCheck5 = 1 then 0 else ISNULL((SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D = 9),0) end,		-- прогул НЕЯВКА (дни)
		[TYPE_11] = case when @nCheck5 = 1 then 0 else ISNULL((SELECT SUM(COUNT_DAYS) FROM #NOTWORK_DAYS WHERE TE.LINK = LINK_UP1 AND WORK_D IN (11,14)),0) end	-- выходные и праздничые НЕЯВКА (дни)
	FROM 
		DBO.TABELS T 
		INNER JOIN DBO.SA_TABELS_EMPLS TE ON T.LINK = TE.LINK
		INNER JOIN DBO.SA_TABELS_EMPLS_WP WP ON TE.LINK = WP.LINK_UP1
		INNER JOIN DBO.EMPL E ON E.LINK = TE.LINK_EMPL
		INNER JOIN DBO.PERSON P ON P.LINK = E.PERS_LINK
		LEFT JOIN #S S ON WP.LINK_EMPL = S.LINK_EMPL AND WP.LINK_SOVM = S.LINK_SOVM
		LEFT JOIN #WORK_DAYS WD ON TE.LINK = WD.LINK_UP1 AND WD.LINK_SOVM = WP.LINK_SOVM
		LEFT JOIN #WORK_DAYS1 Y ON TE.LINK = Y.LINK_UP1 AND Y.LINK_SOVM = WP.LINK_SOVM
	WHERE 
		T.LINK_DOC = @varKSnLINKDoc
	ORDER BY 
		1

IF (SELECT COUNT(DISTINCT SUBDIV_LINK) FROM #T_RES00) <> 1 BEGIN
		SELECT @varKSSUBDIV = '', @varKSSUBDIV_CODE = ''
	END
	ELSE 
		BEGIN
			SELECT TOP 1 @varKSSUBDIV = SUBDIV, @varKSSUBDIV_CODE = CODE_SUB FROM  #T_RES00
		END

	DECLARE 
		@varKSCNT1 INT, @varKSCNT2 INT, @varKSCNT3 INT
	
	SELECT TOP 1 
		@varKSCNT1 = COUNT(DISTINCT LINK_FKR_D), 
		@varKSCNT2 = COUNT(DISTINCT LINK_FKR_T), 
		@varKSCNT3 = COUNT(DISTINCT LINK_FKR_E),
		@varKSDIV_CODE = MAX(CODE_FKR_D),
		@varKSDIV_NAME = MAX(NAME_FKR_D),
		@varKSTI_CODE = MAX(CODE_FKR_T),
		@varKSTI_NAME = MAX(NAME_FKR_T),
		@varKSEXP_CODE = MAX(CODE_FKR_E),
		@varKSEXP_NAME = MAX(NAME_FKR_E)
	FROM DICTIONARY_PAYS_EMPL DPE
	INNER JOIN dbo.PAYS P ON DPE.LINK_PAYS = P.LINK
	INNER JOIN bi_diction_vkr VKR ON VKR.LINK = DPE.LINK_KBK
	INNER JOIN #T_RES00 R ON DPE.LINK_EMPL = R.LINK_EMPL
	where date_begin <= @varKSdDate2
		AND (DATE_END >= @varKSdDate1 OR DATE_END IS NULL) 


	declare @LINK_DEP int
	Set @LINK_DEP = Coalesce( (SELECT TOP 1 ZB_LINK FROM dbo.KS_OPTIONS_ZB), dbo.GetOwnDepLink())

	declare @nAVGCount numeric(18,2), @nMCount numeric(18,2)

	Select @nAVGCount = dbo.sa_ssch_empls(@varKSdDate1, @varKSdDate2, null, 0, 1, 0, DEFAULT)
	Select @nMCount = dbo.sa_sch_empls(@varKSdDate2, null, 0, 1, 0, DEFAULT)

	IF @varKSCNT1 <> 1
		SELECT @varKSDIV_CODE = '', @varKSDIV_NAME = ''
	IF @varKSCNT2 <> 1
		SELECT @varKSTI_CODE = '', @varKSTI_NAME = ''
	IF @varKSCNT3 <> 1
		SELECT @varKSEXP_CODE = '', @varKSEXP_NAME = ''

	SELECT *, @nAVGCount as AVGCount, @nMCount as MCount 
	FROM #T_RES00
	ORDER BY 
		LTRIM(RTRIM(CASE @varKSnOption1 
			WHEN 1 THEN REPLICATE ('0',10 - len(ltrim(rtrim((TN))))) + ltrim(rtrim((TN))) 
			WHEN 2 THEN REPLICATE ('0',10 - len(ltrim(rtrim((CODE_POST))))) + ltrim(rtrim((CODE_POST)))
			WHEN 3 THEN POST
			WHEN 4 THEN FIO
			WHEN 5 THEN REPLICATE ('0',10 - len(ltrim(rtrim((CODE_SUB))))) + ltrim(rtrim((CODE_SUB)))
			WHEN 6 THEN SUBDIV
			ELSE ''
		END)),

		LTRIM(RTRIM(CASE @varKSnCheck1 
			WHEN 2 THEN REPLICATE ('0',10 - len(ltrim(rtrim((TN))))) + ltrim(rtrim((TN))) 
			WHEN 3 THEN REPLICATE ('0',10 - len(ltrim(rtrim((CODE_POST))))) + ltrim(rtrim((CODE_POST)))
			WHEN 4 THEN POST
			WHEN 5 THEN FIO
			WHEN 6 THEN REPLICATE ('0',10 - len(ltrim(rtrim((CODE_SUB))))) + ltrim(rtrim((CODE_SUB)))
			WHEN 7 THEN SUBDIV
			ELSE ''
		END)),
		
		LTRIM(RTRIM(CASE @nSort3 
			WHEN 2 THEN '' + REPLICATE ('0',10 - len(ltrim(rtrim((TN))))) + ltrim(rtrim((TN))) 
			WHEN 3 THEN '' +REPLICATE ('0',10 - len(ltrim(rtrim((CODE_POST))))) + ltrim(rtrim((CODE_POST)))
			WHEN 4 THEN '' +POST
			WHEN 5 THEN '' +FIO
			WHEN 6 THEN '' +REPLICATE ('0',10 - len(ltrim(rtrim((CODE_SUB))))) + ltrim(rtrim((CODE_SUB)))
			WHEN 7 THEN '' +SUBDIV
			ELSE ''
		END))

END



GO


GRANT EXECUTE ON dbo.[SA_PRINT_TABEL_421m] TO PUBLIC

GO


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


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

GO

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

SET NOCOUNT OFF

DECLARE @LINK_DOC_SAL as INT,
	@NUM_DOC_SAL as VARCHAR(25),
	@DATE_DOC_SAL as datetime,
	@SUM_DOC_SAL as NUMERIC(18,2),
	@ACC_CODE VARCHAR(30),
	@KD_FULL_CODE_ACC VARCHAR(13)

DECLARE @varKStrancount int, @varKSERROR as INT

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

DECLARE @Cur CURSOR, @FIN VARCHAR(5), @SRC VARCHAR(30), @LINK_EKR INT, @SUM_PROV numeric(20,2), @order int, @Account1 INT, @Account2 INT, @KD_CODE_ACC VARCHAR(6),	
	@HOZ_OPER int, @P1 float, @P2 float, @SGU INT, 	@OSNOVANIE VARCHAR(254), @LINK_KD1 INT, @LINK_KD2 INT,
	@LINK_PAYS int, @CODE_PAYS VARCHAR(10), @LINK_KBK int, @LINK_KAU int, @LINK_DOP_KL int, @USER_ACC varchar(4), @CODE_SFIN VARCHAR(30), @Fin_Source CHAR(1),
	@LINK_ORG int,  @LINK_ORG_ACC int, @LINK_EMPL INT, @SUBDIV_HEAD INT, @SUBDIV_NAME VARCHAR(254)

Set @order = 0
DECLARE @DEPONIR_LINK_PAYS INT
SET @DEPONIR_LINK_PAYS = dbo.sa_get_option_by_code('VEDOM_OPTIONS_OPT10')

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

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

---
SET @Cur = CURSOR FORWARD_ONLY
FOR 
-- Данные для проводок
SELECT  
	LINK_EMPL = CASE WHEN JC.LINK_PAYS = @DEPONIR_LINK_PAYS THEN JC.LINK_EMPL ELSE NULL END,
	[DATE] = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@nMONTH,@nYear)),
	COALESCE(JC.LINK_EKR,@LinkEKR211), 
	LINK_PAYS = JC.LINK_PAYS,
	CODE_PAYS = P.CODE,
	OSNOVANIE = LEFT(RTRIM(P.[NAME]) 
				+ CASE WHEN JC.LINK_PAYS = @DEPONIR_LINK_PAYS THEN ' (' + RTRIM(O.[NAME]) ELSE '' END
				+ CASE WHEN JC.LINK_PAYS = @DEPONIR_LINK_PAYS THEN ' №' + RTRIM(D.[NUMBER]) ELSE '' END
				+ CASE WHEN JC.LINK_PAYS = @DEPONIR_LINK_PAYS THEN ' от ' + CONVERT(varchar(10),D.[DATE], 104) + ')' ELSE '' END
				,254),
	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)),''),
	P.CODE_ACC, SUMMA= SUM(JC.SUMMA),
	LINK_ORG = COALESCE(JC.LINK_ORG,TA.LINK_ORG),
	LINK_ORG_ACC = (CASE WHEN COALESCE(JC.LINK_ORG,0) = 0 THEN TA.LINK_ACC ELSE NULL END),
	CASE WHEN O.CODE = 'DOCUMENTS_INCOME_TAX' AND @GROUP_BY_SUB = 1 THEN SUBDIV_HEAD ELSE NULL END,
	CASE WHEN O.CODE = 'DOCUMENTS_INCOME_TAX' AND @GROUP_BY_SUB = 1 THEN SUBDIV_NAME ELSE NULL END
FROM	
	dbo.SDOC D INNER JOIN dbo.CALCULATE_JURNAL JC ON JC.LINK_DOC = D.LINK
			INNER JOIN dbo.PAYS P ON JC.LINK_PAYS = P.LINK
			INNER JOIN dbo.SAL_SFIN F ON F.LINK = JC.LINK_VKR
			LEFT JOIN dbo.TAX2_APP TA ON P.LINK = TA.LINK_UP
			LEFT JOIN dbo.S_OBJECTS O ON O.LINK = D.OBJECT
			LEFT JOIN DBO.SD_EMPL E ON E.LINK = JC.LINK_EMPL
WHERE   
	P.[OBJECT] = 2
	AND NOT JC.LINK_PAYS IS NULL AND JC.LINK_PAYS<>0  
	AND MONTH(JC.PERIOD_BEGIN) = @nMONTH AND YEAR(JC.PERIOD_BEGIN) = @nYEAR
	AND JC.LINK_DEP = @LINK_DEP
	AND -- Проводки будут в расходнике
	(	O.CODE NOT IN ('DOCUMENTS_DED_PAYROLL','DOCUMENTS_DED_PAYROLL_DGH')
		OR
		JC.LINK_PAYS = @DEPONIR_LINK_PAYS
	)	
GROUP BY 
	CASE WHEN JC.LINK_PAYS = @DEPONIR_LINK_PAYS THEN JC.LINK_EMPL ELSE NULL END, 
	LEFT(RTRIM(P.[NAME]) 
				+ CASE WHEN JC.LINK_PAYS = @DEPONIR_LINK_PAYS THEN ' (' + RTRIM(O.[NAME]) ELSE '' END
				+ CASE WHEN JC.LINK_PAYS = @DEPONIR_LINK_PAYS THEN ' №' + RTRIM(D.[NUMBER]) ELSE '' END
				+ CASE WHEN JC.LINK_PAYS = @DEPONIR_LINK_PAYS THEN ' от ' + CONVERT(varchar(10),D.[DATE], 104) + ')' ELSE '' END
				,254),
	JC.LINK_EKR, JC.LINK_PAYS, P.CODE, P.[NAME], F.KBK, F.KAU, F.DOP_KL, F.USER_ACC, 
	F.CODE, F.SOURCE, P.CODE_ACC, JC.LINK_ORG, TA.LINK_ORG, TA.LINK_ACC, (CASE WHEN O.CODE = 'DOCUMENTS_INCOME_TAX' AND @GROUP_BY_SUB = 1 THEN SUBDIV_HEAD ELSE NULL END) ,
	CASE WHEN O.CODE = 'DOCUMENTS_INCOME_TAX' AND @GROUP_BY_SUB = 1 THEN SUBDIV_NAME ELSE NULL END
ORDER BY
	P.[NAME], F.SOURCE

-------------------
OPEN @Cur
FETCH NEXT FROM @Cur INTO @LINK_EMPL, @DATE_DOC_SAL,@LINK_EKR, @LINK_PAYS, @CODE_PAYS, @OSNOVANIE, @LINK_KBK, @LINK_KAU, @LINK_DOP_KL, @USER_ACC, @CODE_SFIN, @Fin_Source, @KD_CODE_ACC, @SUM_PROV, @LINK_ORG, @LINK_ORG_ACC, @SUBDIV_HEAD, @SUBDIV_NAME
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN
		IF COALESCE(@SUM_PROV,0) <> 0 BEGIN

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

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

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

			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 'Не сформированы проводки для удержания с кодом ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),''),
					'Не указан счет кредита в настройках этого вида удержания.',
					'Укажите в настройках удержания '+COALESCE(LTRIM(RTRIM(@CODE_PAYS)),'')+' счет кредита.',
					'SALARY'
				GOTO DO_NEXT			
			END
			
			-- Сохраняем документ
			SELECT @LINK_DOC_SAL = 0, @NUM_DOC_SAL = NULL
			-- определим максимальный номер
			exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'DOCUMENTS_SALARY', @NUM_DOC_SAL output, @LINK_DEP

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

			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 'Не сформированы проводки для удержания: ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),''),
					'Не указан cчет начислений на оплату труда в общих настройках по зарплате.',
					'Укажите cчет начислений на оплату труда в общих настройках по зарплате.',
					'SALARY'
				GOTO DO_NEXT
			END	

			IF RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> ''
				Set @Account1 = (SELECT TOP 1 link FROM dbo.S_ACCOUNTS WHERE BUH_TYPE > 0 AND 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 BUH_TYPE > 0 AND 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 'Не сформированы проводки для удержания ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),'') + ' по источнику финансирования зарплаты "' + RTRIM(LTRIM(@CODE_SFIN)) + '" с видом деятельности "' + ISNULL((SELECT TOP 1 FS.CODE + '.' + FS.NAME FROM dbo.BB_FIN_SOURCE FS WHERE FS.CODE = CONVERT(VARCHAR(1),@Fin_Source)),'') +  '"',
					'В плане счетов не найден счет ' + @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 'Не сформированы проводки для удержания ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),''),
					'У источника финансирования ' + 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 BUH_TYPE > 0 AND 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 'Не сформированы проводки для удержания ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),'') + ' по источнику финансирования зарплаты "' + RTRIM(LTRIM(@CODE_SFIN)) + '" с видом деятельности "' + ISNULL((SELECT TOP 1 FS.CODE + '.' + FS.NAME FROM dbo.BB_FIN_SOURCE FS WHERE FS.CODE = CONVERT(VARCHAR(1),@Fin_Source)),'') +  '"',
					'В плане счетов не найден счет ' + @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 'Не сформированы проводки для удержания: ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),''),
					'У источника финансирования ' + 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 'Не сформированы проводки для удержания: ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),''),
						'Не найдено подходящей хоз. операции для проводки ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account1) + '-' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account2),
						'Вероятно в настройках удержания ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),'') + ' указан некорректный счет кредита или в общих настройках по зарплате указан неправильно счет для начисления на оплату труда.',
						'SALARY'
					GOTO DO_NEXT
				END	

				IF EXISTS (SELECT * FROM dbo.XD_XOZ_OPER WHERE LINK = @HOZ_OPER AND GROUP_CODE = '99') BEGIN
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформированы проводки для удержания: ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),''),
						'Недопустимая корреспонденция счетов в проводке ' + (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 'Не сформированы проводки для удержания: ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),''),
						'У счета ' + (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 'Не сформированы проводки для удержания: ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),''),
						'У счета ' + (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, @SUBDIV_HEAD, @LINK_EMPL, NULL, NULL, @LINK_KAU, @LINK_ORG_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_EMPL, @DATE_DOC_SAL,@LINK_EKR, @LINK_PAYS, @CODE_PAYS, @OSNOVANIE, @LINK_KBK, @LINK_KAU, @LINK_DOP_KL, @USER_ACC, @CODE_SFIN, @Fin_Source, @KD_CODE_ACC, @SUM_PROV, @LINK_ORG, @LINK_ORG_ACC, @SUBDIV_HEAD, @SUBDIV_NAME
END

CLOSE @Cur
DEALLOCATE @Cur

exec X_SALDO_CommitChanges

SET NOCOUNT OFF
Return 0
END




GO


GRANT EXECUTE ON dbo.[SA_CREATE_PROV_U] TO PUBLIC

GO

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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE [dbo].SD_U_VEDOM_4DOC
 @varKSlinkDoc int
AS
SELECT 
	ep.*,sj.summa, sj.days, sj.hours, sj.period_end, sj.LINK_PAYS, sj.CODE_PAYS, sj.NAME_PAYS, sj.LINK_VKR, sj.NAME_VKR, S.LINK AS LINK_EKR, S.CODE AS CODE_EKR
FROM 
	dbo.SALARY_JURNAL_CALCULAT sj
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = 'R211') R211
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = '211') T211	
	INNER JOIN dbo.KOSGU S ON S.LINK = (CASE WHEN R211.LINK = LINK_EKR THEN T211.LINK ELSE LINK_EKR END)
	INNER JOIN dbo.ku_empl_placing ep ON sj.LINK_EMPL = ep.LINK
WHERE 
	sj.LINK_DOC = @varKSlinkDoc and sj.TYP_OPER = 1

GO


GRANT EXECUTE ON dbo.[SD_U_VEDOM_4DOC] TO PUBLIC

GO

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

GO

CREATE	PROCEDURE dbo.BI_SAVE_KBK
	@varKSparLINK	int	OUTPUT,
	@varKSType	tinyint,
	@varKSparNAME	VARCHAR(250) = '',
	@varKSLink_Adm	int,
	@varKSLink_KD	int = null,
	@varKSLink_IVF	int = null,
	@varKSLink_prog	int = null,
	@varKSLink_Div	int = null,
	@varKSLink_CSR	int = null,
	@varKSLink_Exp	int = null,
	@varKSLink_SGU	int = null,
	@iKBKL_Link		int = null,
	@iKBK14_Link	int = null,
	@iUsed			bit = 1,
	@iUsedAll		bit = 0,
	@iOsn			bit = 0

AS
DECLARE @iRes	int,
		@cDelim char(1),
		@iDepLink int
set @cDelim = '.' -- брать из настройки!!!
set @iDepLink = isnull(dbo.BK_GetDepZB(),dbo.GetOwnDepLink())
IF @varKSLink_SGU IS NOT NULL AND @varKSLink_SGU = 0
	SET @varKSLink_SGU = null
--select @varKSType , @varKSparLINK , @varKSparNAME, @varKSLink_Adm, @varKSLink_KD,@varKSLink_prog, @varKSLink_SGU,@varKSLink_Div, @varKSLink_Csr, @varKSLink_Exp, @iUsedAll, @cDelim
IF @varKSType = 1
	EXEC @iRes = dbo.BI_SAVE_VKR @varKSparLINK OUTPUT, @varKSparNAME, @varKSLink_Adm, @varKSLink_Div, @varKSLink_Csr, @varKSLink_Exp, @iUsedAll, @cDelim
IF @varKSType = 2
	EXEC @iRes = dbo.BI_SAVE_KBK_KD @varKSparLINK OUTPUT, @varKSparNAME, @varKSLink_Adm, @varKSLink_KD, @varKSLink_prog,@varKSLink_SGU, @iUsedAll, @cDelim
IF @varKSType = 3
	EXEC @iRes = dbo.BI_SAVE_KBK_IVF @varKSparLINK OUTPUT, @varKSparNAME, @varKSLink_Adm, @varKSLink_IVF, @varKSLink_prog,@varKSLink_SGU, @iUsedAll, 4,@cDelim
IF @varKSType = 4
	EXEC @iRes = dbo.BI_SAVE_KBK_IVF @varKSparLINK OUTPUT, @varKSparNAME, @varKSLink_Adm, @varKSLink_IVF, @varKSLink_prog,@varKSLink_SGU, @iUsedAll, 8,@cDelim
if @iRes <> 0
	return @iRes

-- Исправляем неверные коды
	UPDATE KL_KBK
	SET Code = A.Right_Code
--	select *
	FROM KL_KBK K left join 
	    (SELECT Link, 
		[Right_Code] = adm_code + @cDelim 
			+ (case when type=1 then rtrim(div_code) + @cDelim + rtrim(csr_code) + @cDelim + rtrim(exp_code)
				when type=2 then rtrim(KD_code) + PROG_CODE + SGU_CODE
				when type>2 then rtrim(IVF_code) + PROG_CODE + SGU_CODE end)
		FROM bi_diction_kbk_full) A on K.link = A.link
	WHERE A.Right_Code <> K.Code

--SELECT @@ROWCOUNT
update dbo.DEPARTMENT_KBK
set OSN = @iOsn 
where KBK_LINK = @varKSparLINK and DEP_LINK = @iDepLink

if @@rowcount = 0 and (@iOsn = 1 or @iUsedAll = 0 and @iUsed = 1)
	insert into dbo.DEPARTMENT_KBK (DEP_LINK,KBK_LINK, OSN)
	values (@iDepLink,@varKSparLINK,@iOsn)



if @iUsedAll = 1 or @iUsed = 0
	delete 
	from dbo.DEPARTMENT_KBK
	where KBK_LINK = @varKSparLINK AND OSN <> 1


if @iKBKL_Link is null
	delete from dbo.KL_KBK_LINKED where LINK = @varKSparLINK
else
begin
	update dbo.KL_KBK_LINKED 
	set LINK_KBK = @iKBKL_Link
	where LINK = @varKSparLINK
	if @@ROWCOUNT = 0
			insert into dbo.KL_KBK_LINKED (LINK, LINK_KBK) values(@varKSparLINK, @iKBKL_Link)
end		


if @iKBK14_Link is null
	delete from dbo.KBK14_LINKED where LINK = @varKSparLINK
else
begin
	update dbo.KBK14_LINKED 
	set LINK_KBK = @iKBK14_Link
	where LINK = @varKSparLINK
	if @@ROWCOUNT = 0
			insert into dbo.KBK14_LINKED (LINK, LINK_KBK) values(@varKSparLINK, @iKBK14_Link)
end		



RETURN @iRes





GO


GRANT EXECUTE ON dbo.[BI_SAVE_KBK] TO PUBLIC

GO



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

GO

CREATE  PROCEDURE [dbo].[SA_CREATE_XML_TO_SYNCH] @varKSnMonth INT, @varKSnYear INT, @DEP_LINK INT
/*
Процедура формирует проводки по отчислениям
*/
AS BEGIN

SET NOCOUNT OFF


	IF  convert(tinyint,dbo.sa_get_option_by_code('SAL_OPT_INTEGR_PROV_ZP_EXP')) = 1
	BEGIN
		
		IF convert(int, dbo.sa_get_option_by_code('SAL_OPT_INTEGR_CHANAL'))  IS NOT NULL 
		BEGIN
			
			DECLARE @CHANAL_LINK INT, 
					@PROV_ZP_EXP TINYINT ,
					@OBJECT varchar(50),
					@MSG VARCHAR(500),
					@iERROR INT,
					@iRowCount int
					
			SET @CHANAL_LINK =  (select convert(int, dbo.sa_get_option_by_code('SAL_OPT_INTEGR_CHANAL')))
			SET @PROV_ZP_EXP = (SELECT convert(tinyint,dbo.sa_get_option_by_code('SAL_OPT_INTEGR_PROV_ZP_EXP')))
 			IF @PROV_ZP_EXP = 1 
 			BEGIN
 				SET @OBJECT = 'DOCUMENTS_SALARY' 	
	 	
	 			
 				/* СОЗДАЕМ ВРЕМЕНННУЮ ТАБЛИЦУ */
				DECLARE @DOC_TABLE VARCHAR(20)
				DECLARE @SQL NVARCHAR(1000)
				EXEC DBO.X_GET_TABLE_NAME @DOC_TABLE OUTPUT
				
				DECLARE @varKSDateS DATETIME
				SET @varKSDateS = dbo.ConvertDMY2Date(1,@varKSnMonth,@varKSnYear)

				DECLARE @DATE_PROV VARCHAR(10),@DEP VARCHAR (10)
				SET @DATE_PROV = CONVERT(VARCHAR(10),dbo.DateEndOfMonth(@varKSDateS),112)
				SET @DEP = @DEP_LINK
				------------------------------- ВЫБИРАЮТСЯ ЛИНКИ ИЗ ЖУРНАЛА ПРОВОДОК по дате проводки и  линку организации и  закидываются в буфер  ------------
			
				SET @SQL = 'INSERT INTO DBO.BUFFER (ID, LINK)
						SELECT DISTINCT ''' + @DOC_TABLE + ''', T.LINK
						FROM DBO.SALARY_ALL_PROV T where t.date_prov = '''+@DATE_PROV+'''  and LINK_DEP = '+@DEP+' '
				exec sp_executesql @SQL 
				SET @iERROR = @@ERROR 
				--SELECT @iERROR
				SET @MSG = ''
				IF @iERROR <> 0
				BEGIN
				   	SET @MSG = 'Операция передачи в ПК Смета-Смарт не выполнена' + CHAR(13) + CHAR(10) + 'Не выбрано ни одной проводки' 
					raiserror(@MSG,11,0)	
					RETURN 0
				END		
				
				
									
				----------В этой таблице будут лежать выгружаемые проводки в XML формате--------------
				DECLARE @SYNC_TABLE VARCHAR(20)
				EXEC DBO.X_GET_TABLE_NAME @SYNC_TABLE OUTPUT
					
				SET @SQL = ''
				SET @SQL  ='CREATE table ' + @SYNC_TABLE + '(ID int, F_NAME VARCHAR(254), XML_DATA TEXT)
								INSERT INTO ' + @SYNC_TABLE + ' (ID , F_NAME, XML_DATA)
								exec @iERROR = dbo.SS_PROV_EXPORT ' + @DOC_TABLE + ''
				exec sp_executesql @SQL , N' @iERROR int output', @iERROR = @iERROR OUTPUT
				SELECT @iRowCount = @@ROWCOUNT
				--SET @iERROR = @@ERROR 
				SET @MSG = ''
				IF @iERROR <> 0 OR @iRowCount  = 0 
				BEGIN
				   	SET @MSG = 'Операция передачи в ПК Смета-Смарт не выполнена' + CHAR(13) + CHAR(10) + 'Не сформированно сообщение для передачи в ПК Смета-Смарт ' 
					raiserror(@MSG,11,0)	
					RETURN 0
				END		
				
				-----------------------
 				-------Выгрузка/удаление в Смету-Смарт
 				DECLARE @Protocol_Text VARCHAR(8000), -- текст ошибки
 						@CH_LINK VARCHAR(10) 
 				SET	@CH_LINK = @CHANAL_LINK	 
					
			 		
				SET @SQL = '  EXEC  @iERROR =  dbo.SMETA_SMART_SYNC ''' + @SYNC_TABLE + ''', '+ @CH_LINK +','''+@OBJECT+''',0 ,@protocol_text output '
				exec sp_executesql @SQL, N'@protocol_text varchar(8000) output, @iERROR int output', @protocol_text = @protocol_text OUTPUT, @iERROR = @iERROR OUTPUT
				SET @MSG = ''
				----Подготовим таблицу с гайдами для обновления статусов
				DECLARE @DOC_UPD_T VARCHAR(20)
				EXEC DBO.X_GET_TABLE_NAME @DOC_UPD_T OUTPUT
				
				IF @iERROR <> 0 OR ISNULL(@protocol_text,'') <>''  --- Если ошибка выполнения в хранике  dbo.SMETA_SMART_SYNC
				BEGIN
					SET @MSG = 'Операция передачи в ПК Смета-Смарт не выполнена' + CHAR(13) + CHAR(10) + ''+@protocol_text+'' 
						raiserror(@MSG,11,0)	
						
					-----ПРОСТАВЛЕНИЕ СТАТУСА ---ОШИБКА ПЕРЕДАЧИ--------------------------
 					/* ОБНОВЛЕНИЕ СТАТУСОВ ПРОВОДОК */
					---- Таблица с гайдами для обновления статусов
					SET @SQL = ''
					SET @SQL  ='SELECT LINK = b.LINK, S.DOC_LINK , G.GUID ,[STATUS]= CONVERT(INT,-1), STATUS_DATE = GETDATE()   
								INTO '+@DOC_UPD_T+' 
					            FROM BUFFER B 
								INNER JOIN DBO.SALARY_ALL_PROV S on s.link = b.link
								INNER JOIN DBO.G_PROV G  ON G.LINK= S.DOC_LINK		
								WHERE B.ID = '''+@DOC_TABLE+''''
					
					exec sp_executesql @SQL
					SELECT @iRowCount = @@ROWCOUNT , @iERROR = @@ERROR 

					--SET @iERROR = @@ERROR 
					SET @MSG = ''
					IF @iERROR <> 0 OR @iRowCount  = 0 
					BEGIN
				   		SET @MSG = 'Операция обновления статусов проводок не выполнена' + CHAR(13) + CHAR(10) + 'Отсутствуют проводки для обновления' 
						raiserror(@MSG,11,0)	
						RETURN 0
					END						
					--------Проверка статусов проводок, на существование , для обновления или добавления--------
					SET @SQL = ''
					SET @SQL = ' DECLARE @doc_link int, @status tinyint, @STATUS_DATE datetime
					DECLARE @cur CURSOR 
					
					SET @cur = CURSOR FAST_FORWARD FOR
					SELECT doc_link, status, STATUS_DATE FROM '+@DOC_UPD_T+' order by doc_link
							OPEN @cur
							FETCH NEXT FROM @cur INTO @doc_link, @status, @STATUS_DATE
							WHILE @@fetch_status=0 BEGIN
								IF  not exists( select * from dbo.GP_EXCH_STATUS where link_gp = @doc_link) 
  								begin 
									INSERT INTO dbo.GP_EXCH_STATUS (link_GP, STATUS, DATE)
									SELECT @doc_link , @status , @STATUS_DATE
  								END
  								BEGIN
  									UPDATE dbo.GP_EXCH_STATUS 
  									SET STATUS = @status, DATE = @STATUS_DATE
  									WHERE link_GP = @doc_link 
  								END	
  									
								FETCH NEXT FROM @cur INTO @doc_link, @status, @STATUS_DATE
							
							END
						CLOSE @cur
						DEALLOCATE @cur '
					-----------------------------------------------------------
					exec sp_executesql @SQL
					SELECT  @iERROR = @@ERROR 
					SET @MSG = ''
					IF @iERROR <> 0 
					BEGIN
				   		SET @MSG = 'Операция обновления статусов проводок не выполнена' + CHAR(13) + CHAR(10) + 'Отсутствуют проводки для обновления' 
						raiserror(@MSG,11,0)	
						RETURN 0
					END		
					------ окончание работы со статусом "ОШИБКА ПЕРЕДАЧИ"					
					RETURN 0
					
					
				END	ELSE   --- Если нет ошибки выполнения в хранике  dbo.SMETA_SMART_SYNC
					BEGIN
						--ПРОСТАВЛЕНИЕ СТАТУСА ---ОТПРАВЛЕНО--------------------
						/* ОБНОВЛЕНИЕ СТАТУСОВ ПРОВОДОК */

							
							SET @SQL = ''
							SET @SQL  ='SELECT LINK = b.LINK, S.DOC_LINK , G.GUID ,[STATUS]= 1, STATUS_DATE = GETDATE()   
										INTO '+@DOC_UPD_T+' 
										FROM BUFFER B 
										INNER JOIN DBO.SALARY_ALL_PROV S on s.link = b.link
										INNER JOIN DBO.G_PROV G  ON G.LINK= S.DOC_LINK		
										WHERE B.ID = '''+@DOC_TABLE+''''
							
							exec sp_executesql @SQL
							SELECT @iRowCount = @@ROWCOUNT , @iERROR = @@ERROR 

							--SET @iERROR = @@ERROR 
							SET @MSG = ''
							IF @iERROR <> 0 OR @iRowCount  = 0 
							BEGIN
			   					SET @MSG = 'Операция обновления статусов проводок не выполнена' + CHAR(13) + CHAR(10) + 'Отсутствуют проводки для обновления' 
								raiserror(@MSG,11,0)	
								RETURN 0
							END						
							--------Проверка статусов проводок, на существование , для обновления или добавления--------
							SET @SQL = ''
							SET @SQL = ' DECLARE @doc_link int, @status tinyint, @STATUS_DATE datetime
							DECLARE @cur CURSOR 
							
							SET @cur = CURSOR FAST_FORWARD FOR
							SELECT doc_link, status, STATUS_DATE FROM '+@DOC_UPD_T+' order by doc_link
									OPEN @cur
									FETCH NEXT FROM @cur INTO @doc_link, @status, @STATUS_DATE
									WHILE @@fetch_status=0 BEGIN
										IF  not exists( select * from dbo.GP_EXCH_STATUS where link_gp = @doc_link) 
										begin 
											INSERT INTO dbo.GP_EXCH_STATUS (link_GP, STATUS, DATE)
											SELECT @doc_link , @status , @STATUS_DATE
										END
										BEGIN
											UPDATE dbo.GP_EXCH_STATUS 
											SET STATUS = @status, DATE = @STATUS_DATE
											WHERE link_GP = @doc_link 
										END	
		  									
										FETCH NEXT FROM @cur INTO @doc_link, @status, @STATUS_DATE
									
									END
								CLOSE @cur
								DEALLOCATE @cur '
							-----------------------------------------------------------
							exec sp_executesql @SQL
							SELECT  @iERROR = @@ERROR 
							SET @MSG = ''
							IF @iERROR <> 0 
							BEGIN
			   					SET @MSG = 'Операция обновления статусов проводок не выполнена' + CHAR(13) + CHAR(10) + 'Отсутствуют проводки для обновления' 
								raiserror(@MSG,11,0)	
								RETURN 0
							END	
						--окончание работы со статусом "ОТПРАВЛЕНО" --------------------	
					end 
				
				EXEC dbo.BufferClear @DOC_TABLE 
	 		end 	
		 END	
		 ELSE BEGIN
				SET @MSG = 'Операция передачи в ПК Смета-Смарт не выполнена' + CHAR(13) + CHAR(10) + 'Не выбран Канал для передачи в ПК Смета-Смарт' + CHAR(13) + CHAR(10) +'В настройках интеграции ПК Зарплата-КС'
				raiserror(@MSG,11,0)	
				RETURN 0
		 END
		 
		 
	END
	
SET NOCOUNT OFF
Return 0
END



GO


GRANT EXECUTE ON dbo.[SA_CREATE_XML_TO_SYNCH] TO PUBLIC

GO


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

GO


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

CREATE   PROCEDURE [dbo].KU_MONEY_SAVE
	@parLINK	int	OUTPUT,
	@parNUMBER  varchar(30),
	@parDATE   datetime,
	@parEMPL_LINK	int = null,
	@parDATE_BEGIN datetime = null,
	@parDATE_END2 datetime = null,
	@parORDER_LINK INT = null,
	@parREF_ATT int = NULL,
	@parDEP_LINK int = null,
	@parORDER_STATUS int = 0
	
AS
DECLARE @ERROR	tinyint,
		@strVALUE	varchar(7000),	
		@trancount	int,
		@ObjectLink int,
		@EventText	varchar(254),
		@SQLError int,
		@RowCount int
		
DECLARE @staff_link int, @num_stake numeric(5, 2), @status int, @DEP_LINK int, @comment varchar(254), @item_link int,
		@temp_link int, @date_end2 datetime
SET @trancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	
	IF @parEMPL_LINK is null or @parDATE_BEGIN is null
		BEGIN
			ROLLBACK
			RETURN 5
		END
	SELECT @parORDER_LINK = link FROM ORDERS WITH (UPDLOCK) WHERE LINK = @parORDER_LINK
	SELECT @SQLError = @@ERROR, @RowCount = @@ROWCOUNT
	IF @SQLError <> 0
	BEGIN
		ROLLBACK
		RETURN 7
	END
	IF @RowCount = 0
	BEGIN
		SET @comment='Об изменении оплаты труда '+dbo.ku_GetEmplFIO(@parEMPL_LINK)
		EXECUTE @ERROR = KU_ORDER_SAVE @parORDER_LINK OUTPUT, 18, @parNumber, @parDate, @comment, 0, @parDEP_LINK
		IF @ERROR <> 0
			RETURN @ERROR
	END
	
	IF (select [type] from orders where link = @parORDER_LINK) <>18
	BEGIN
		SELECT @staff_link = staff_link, @status = status, @num_stake = im.num_stake,
			@temp_link = temp_link, @date_end2 = DATE_END2
		FROM item_move im WHERE im.empl_link=@parEMPL_LINK and @parDATE_BEGIN between date_begin and date_end
			and active=1
	END
	ELSE 
		BEGIN
			SELECT @staff_link = staff_link, @status = status, @num_stake = im.num_stake,
				@temp_link = temp_link, @date_end2 = @parDATE_END2
			FROM item_move im WHERE im.empl_link=@parEMPL_LINK and @parDATE_BEGIN between date_begin and date_end
				and active=1
		END	
	IF isnull(@staff_link,0) = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END

	IF @parLINK is null or @parLINK=0 BEGIN
		IF @parDATE_END2 IS NULL BEGIN 
			INSERT INTO item_move (new_face, staff_link, num_stake, date_begin, type, status, empl_link, order_link, temp_link, date_end2, ref_att) 
				VALUES (3, @staff_link, @num_stake, @parDATE_BEGIN, 1, @status, @parEMPL_LINK, @parORDER_LINK, @temp_link, @date_end2, @parREF_ATT)
			SELECT @SQLError = @@ERROR, @parLINK = @@IDENTITY
			IF @SQLError <> 0
			BEGIN
				ROLLBACK
				RETURN 7
			END
		END ELSE BEGIN 
			INSERT INTO item_move (new_face, staff_link, num_stake, date_begin, type, status, empl_link, order_link, temp_link, date_end2, ref_att) 
				VALUES (3, @staff_link, @num_stake, @parDATE_BEGIN, 1, @status, @parEMPL_LINK, @parORDER_LINK, @temp_link, @parDATE_END2, @parREF_ATT)
			SELECT @SQLError = @@ERROR, @parLINK = @@IDENTITY
			IF @SQLError <> 0
			BEGIN
				ROLLBACK
				RETURN 7
			END
		END 	
	END
	ELSE BEGIN
		UPDATE item_move SET date_begin=@parDATE_BEGIN, date_end = '99991231',date_end2=@parDATE_END2 WHERE link=@parLINK
		SELECT @SQLError = @@ERROR, @RowCount = @@ROWCOUNT
		IF @SQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		IF @RowCount = 0
		BEGIN
			ROLLBACK
			RETURN 2
		END
		UPDATE money_period SET date_begin = @parDATE_BEGIN WHERE item_link = @parLINK
		SELECT @SQLError = @@ERROR
		IF @SQLError <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END

	SELECT @ObjectLink = LINK FROM S_OBJECTS WHERE CODE = 'MONEY_CHANGE'
	SET @EventText = 'Изменение оплаты труда'
	EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @EventText, @ObjectLink, 'ITEM_MOVE', @parLINK
IF @@TRANCOUNT > @trancount
	COMMIT TRAN
RETURN 0






GO


GRANT EXECUTE ON dbo.[KU_MONEY_SAVE] TO PUBLIC

GO



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

GO

CREATE PROCEDURE dbo.SD_REP_2NDFL
	@varKScYear varchar(4),			
	@varKSnFirstNum INT,	
	@nCHECK_S int = 0,					   /*Определить перечисленную сумму по проводкам*/
	@nSumm_For_Check numeric(18,2) = null, /*Перечисленная сумма НДФЛ за период*/			
	@varKScVal1 char(1), @varKSnOtborLink1 int,	
	@varKScVal2 char(1), @varKSnOtborLink2 int,
	@nLinkEmpl int = 0,
	@nMonth int = 12,
	@LINK_PERS INT = NULL

	
AS BEGIN

SET NOCOUNT ON
	Set @nMonth = ISNULL(@nMonth,12)

	DECLARE @varKSnYear INT
	SET @varKSnYear = CAST(@varKScYear AS INT)

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

	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK OUTPUT
	


	

	CREATE TABLE #RES0 (
		ID INT IDENTITY,
		NOM_SPR INT,
		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),		

		ksv1 varchar(3), ssv1 numeric(11,2),
		ksv2 varchar(3), ssv2 numeric(11,2),
		ksv3 varchar(3), ssv3 numeric(11,2),
		ksv4 varchar(3), ssv4 numeric(11,2),
		ksv5 varchar(3), ssv5 numeric(11,2),
		ksv6 varchar(3), ssv6 numeric(11,2),
		ksv7 varchar(3), ssv7 numeric(11,2),
		ksv8 varchar(3), ssv8 numeric(11,2),
		ksv9 varchar(3), ssv9 numeric(11,2),
		ksv10 varchar(3), ssv10 numeric(11,2),
		ksv11 varchar(3), ssv11 numeric(11,2),
		ksv12 varchar(3), ssv12 numeric(11,2),
		ssv numeric(11,2), siv numeric(11,2),
		osd13 numeric(11,2), sdo13 numeric(11,2), 
		nalogn13 numeric(18), nalogu13 numeric(18),
		NALOG13S numeric(18),
		err int,
		S_5_6 NUMERIC(18,2), S_5_7 NUMERIC(18,2),		
		dolg_np numeric(8), dolg_na numeric(8),
		kbkcode1 varchar(30), kbkcode2 varchar(30), kbkcode3 varchar(30), kbkcode4 varchar(30), 
		kbksum1 numeric(18,2), kbksum2 numeric(18,2),kbksum3 numeric(18,2),kbksum4 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

		IF (len(@varKScVal1) = 0) AND (len(@varKScVal2) = 0 )
			INSERT INTO #FACES
			SELECT distinct PERS_LINK,PERS_LINK FROM dbo.empl WHERE DEP_LINK = @DEP_LINK --AND dbo.ku_GetEmplSack(link,default) = 0
		ELSE 
		if len(@varKScVal1) <> 0
			INSERT INTO #FACES 
			SELECT distinct Min(RECORD),E.PERS_LINK 
			FROM dbo.EMPL E INNER JOIN dbo.OBJECT_VAR_EMPL OVE ON OVE.RECORD = E.LINK
			WHERE LINK_UP = @varKSnOtborLink1
			GROUP BY E.PERS_LINK

		IF (len(@varKScVal1) = 0) AND (len(@varKScVal2) = 0 )
			INSERT INTO #FACES
			SELECT distinct PERS_LINK,PERS_LINK FROM dbo.SALARY_REESTR_DGH WHERE DEP_LINK = @DEP_LINK
				AND PERS_LINK NOT IN (SELECT PERS_LINK FROM #FACES)
		ELSE 
		IF len(@varKScVal2) <> 0
			INSERT INTO #FACES 
			SELECT distinct Min(RECORD), P.LINK 
			FROM dbo.PERSON P INNER JOIN dbo.OBJECT_VAR_PERSON OVE ON OVE.RECORD = P.LINK  
			WHERE LINK_UP = @varKSnOtborLink2 AND P.LINK NOT IN (SELECT PERS_LINK FROM #FACES)
			GROUP BY P.LINK
	END
	IF @nLinkEmpl > 0
	BEGIN
		INSERT INTO #FACES
		SELECT distinct LINK,PERS_LINK FROM dbo.empl WHERE LINK = @nLinkEmpl and DEP_LINK = @DEP_LINK
	END
	
	IF @nLinkEmpl IS NULL
		INSERT INTO #FACES (LINK, PERS_LINK)
		VALUES (0, @LINK_PERS)

	-----------------------------
	delete from dbo.SAL_DED_MONTH
	where 
	YEAR(DATE_DED) = @varKSnYear
	AND
	Month(DATE_DED) <= @nMonth
	AND
	LINK_EMPL IN (Select EM.LINK from dbo.EMPL EM INNER JOIN #FACES F on EM.PERS_LINK = F.PERS_LINK)
	AND
	LINK IN 
	(
		select D.LINK 
		from dbo.SAL_DED_MONTH D inner join dbo.empl E on D.link_empl = E.link
		where YEAR(D.DATE_DED) = @varKSnYear AND Month(D.DATE_DED) <= @nMonth
		and not exists (Select * from dbo.CALCULATE_JURNAL JC where YEAR(JC.PERIOD_BEGIN) = @varKSnYear AND Month(JC.PERIOD_BEGIN) <= @nMonth AND JC.LINK_EMPL = E.LINK AND JC.LINK_VKR = D.LINK_VKR)
	)
	-----------------------------	

	EXEC dbo.BufferClear
	EXEC dbo.BufferPushTable '#faces', 'REP2NDFL', 'pers_link'

	/*Временная таблица*/
	Declare @isPrevPreiod tinyint
	--Суммы начислений включать в базу расчета в том месяце, в котором он был начислен.                   
	Set @isPrevPreiod = dbo.sa_get_option_by_code('NDFL_OPT6')

	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 
		E.PERS_LINK, JC.PERS_LINK, JC.LINK_EMPL, P.LINK, link_vkr, ISNULL(JC.LINK_EKR,P.LINK_EKR), P.TYP_PER, P.OBJECT, summa, P.LINK_INC,
		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
	from 
		dbo.CALCULATE_JURNAL JC 
		INNER JOIN dbo.NDFL_GroupTax() T ON JC.LINK_PAYS=T.LINK_PAYS
		LEFT JOIN dbo.EMPL E ON JC.LINK_EMPL = E.LINK
		LEFT 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 ISNULL(d.code,'') <> 'DOCUMENTS_ADD_TABEL') and @nMonth >= month(JC.PERIOD_BEGIN) and @varKSnYear = year(JC.PERIOD_BEGIN)
				or 
				@isPrevPreiod = 1 and ISNULL(d.code,'') = 'DOCUMENTS_ADD_TABEL'
				and (@nMonth >= month(JC.DATE_BEGIN) or @nMonth >= month(JC.PERIOD_BEGIN) )
				and (@varKSnYear = year(JC.DATE_BEGIN) or @varKSnYear = year(JC.PERIOD_BEGIN) )

			)
		AND  
			(	-->>NEW
			E.PERS_LINK in (select PERS_LINK from #FACES )
			or
			JC.PERS_LINK in (select PERS_LINK from #FACES )
			)	
		AND JC.LINK_DEP = @DEP_LINK 
	union all --Удержания
	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_TYP_INCOMS DTI ON DTI.LINK = SJC.LINK_INC 
	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) = @varKSnYear
		and Month(SJC.PERIOD_BEGIN) <= @nMonth
		and TYP_OPER = 2

-----------------------------------------------------------
--Для обособленных подразделений
DECLARE @DATE DATETIME
SET @DATE = DBO.ConvertDMY2Date(1,@nMonth, @varKSnYear)
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.NDFL_GET_ADDRESS() ADR ON P.LINK = ADR.LINK_FACE
		LEFT JOIN #P_OBOSOB PO ON PO.PERS_LINK = F.PERS_LINK
	ORDER BY 
		RTRIM(P.FM) + ',' + RTRIM(P.IM) + ',' + RTRIM(P.OT)

	select distinct LINK_FACE, Y = year(PERIOD_BEGIN), M = month(PERIOD_BEGIN),  LINK_INC, LINK_VKR  
	into #spr_pays_kbk
	from 	#S_J_C_SHORT where TYP_OPER = 1
	

	CREATE TABLE #PAYS_0_tmp
	(
		ID INT IDENTITY,
		LINK_FACE INT,
		mes int, 
		LINK_INC INT, CODE_INC VARCHAR(4), SUMMA_INC NUMERIC(13,2),
		LINK_DED INT, CODE_DED VARCHAR(3), SUMMA_DED NUMERIC(13,2)
	)

	CREATE TABLE #PAYS_0
	(
		ID INT IDENTITY,
		LINK_FACE INT, 
		mes int, 
		LINK_INC INT, CODE_INC VARCHAR(4), SUMMA_INC NUMERIC(13,2),
		LINK_DED INT, CODE_DED VARCHAR(3), SUMMA_DED NUMERIC(13,2)
	)

	INSERT INTO #PAYS_0_tmp
	(LINK_FACE, mes, 
	LINK_INC, CODE_INC, SUMMA_INC,
	LINK_DED, CODE_DED, SUMMA_DED)
	SELECT 
		F.PERS_LINK,
		mes = MONTH(SJC.PERIOD_BEGIN),
		LINK_INC, ISNULL(DTI.SNAME,'0000'),
		SUM(SUMMA) AS SUMMA_INC,
		DTI.REF_DEDUCT AS LINK_DED, DTI.COD_DED,
		CAST(0 AS NUMERIC(20,2)) AS SUMMA_DED
	FROM 
		#S_J_C_SHORT SJC 
		LEFT JOIN dbo.DICTIONARY_TYP_INCOMS DTI ON DTI.LINK = SJC.LINK_INC
		INNER JOIN #FACES F ON SJC.LINK_FACE = F.PERS_LINK
	WHERE 
		SJC.TYP_OPER = 1
		AND
		YEAR(SJC.PERIOD_BEGIN) = @varKSnYear
		and
		Month(SJC.PERIOD_BEGIN) <= @nMonth
		AND
		ISNULL(SJC.PERS_LINK,0) = 0
		AND
		SJC.LINK_DEP = @DEP_LINK 
	GROUP BY 
		F.PERS_LINK, SJC.TYP_PER, SJC.PERIOD_BEGIN, LINK_INC, DTI.REF_DEDUCT, ISNULL(DTI.SNAME,'0000'), DTI.COD_DED

	---<< Добавление информации по внештатникам	
	union all 

	SELECT 
		F.PERS_LINK,
		mes = MONTH(SJC.PERIOD_BEGIN),
		LINK_INC, ISNULL(DTI.SNAME,'0000'),
		SUM(SUMMA) AS SUMMA_INC,
		DTI.REF_DEDUCT AS LINK_DED, DTI.COD_DED,
		CAST(0 AS NUMERIC(20,2)) AS SUMMA_DED
	FROM #S_J_C_SHORT SJC 	
		LEFT JOIN dbo.DICTIONARY_TYP_INCOMS DTI ON DTI.LINK = SJC.LINK_INC --AND DTI.SNAME <> '0000'
		INNER JOIN #FACES F ON SJC.PERS_LINK = F.PERS_LINK
	WHERE 	SJC.TYP_OPER = 1
		AND
		YEAR(SJC.PERIOD_BEGIN) = @varKSnYear
		and
		Month(SJC.PERIOD_BEGIN) <= @nMonth
		AND
		ISNULL(SJC.LINK_FACE,0) = 0
		AND
		SJC.LINK_DEP = @DEP_LINK
	GROUP BY 
		F.PERS_LINK, SJC.TYP_PER, SJC.PERIOD_BEGIN, LINK_INC, DTI.REF_DEDUCT, ISNULL(DTI.SNAME,'0000'), DTI.COD_DED
	ORDER BY 
		1, ISNULL(DTI.SNAME,'0000'), COD_DED


	INSERT INTO #PAYS_0
	Select LINK_FACE, mes, LINK_INC, CODE_INC, sum(SUMMA_INC), LINK_DED, CODE_DED, sum(SUMMA_DED)
	from #PAYS_0_tmp
	group by LINK_FACE, mes, LINK_INC, CODE_INC, LINK_DED, CODE_DED
	having Sum(SUMMA_INC) <> 0

	drop table #PAYS_0_tmp

	---->>
	--СКИДКИ
	SELECT D.LINK_FACE, D.mes, SUM(D.SUMMA) as SUMMA, D.REF_DED INTO #DED 
	FROM 
		dbo.SA_NDFL_MONTH_DED_ALL(@varKSnYear) D 
		inner join #spr_pays_kbk kbk on kbk.LINK_FACE = d.LINK_FACE and kbk.m = d.mes and kbk.link_inc = d.REF_INC and kbk.LINK_VKR = d.LINK_VKR
	where 
		kbk.y = @varKSnYear
		and kbk.m <= @nMonth
	GROUP BY 
		D.LINK_FACE, d.mes, d.REF_DED

	UPDATE #PAYS_0
	SET SUMMA_DED = 
		(SELECT SUM(SUMMA) FROM #DED D WHERE D.LINK_FACE = R.LINK_FACE AND D.REF_DED = R.LINK_DED AND D.mes = R.mes ) 
	FROM #PAYS_0 R 
	WHERE LINK_DED IS NOT NULL


	update #PAYS_0 
		Set CODE_DED = ''
		where ISNULL(SUMMA_DED,0) = 0


	CREATE TABLE #P0 (LINK_FACE INT, ID1 INT)

	--- 1

	CREATE TABLE #PAYS1(LINK_FACE INT, SM NUMERIC(11,2), MONTH_NUM INT)
	INSERT INTO #PAYS1
	SELECT LINK_FACE, SM, [MONTH]
	FROM dbo.NDFL_BASE_SUM_TAX_MONTH_ALL(@nMonth, @varKSnYear)

	---<< Добавление информации по внештатникам
	insert into #pays1

	SELECT 
		F.PERS_LINK,
		SUM(SUMMA) AS SUMMA_INC,
		Month(SJC.PERIOD_BEGIN)
	FROM 
		#S_J_C_SHORT SJC 
		INNER JOIN dbo.DICTIONARY_TYP_INCOMS DTI ON DTI.LINK = SJC.LINK_INC
		INNER JOIN #FACES F ON SJC.PERS_LINK = F.PERS_LINK
	WHERE 
		YEAR(SJC.PERIOD_BEGIN) = @varKSnYear
		and Month(SJC.PERIOD_BEGIN) <= @nMonth
		AND ISNULL(SJC.LINK_FACE,0) = 0
		AND SJC.LINK_DEP = @DEP_LINK 
	GROUP BY F.PERS_LINK, SJC.PERIOD_BEGIN

	---->>

	SELECT LINK_FACE, SUM(SM) AS SM
	INTO #PAYS_R
	FROM #PAYS1
	GROUP BY LINK_FACE

	INSERT INTO #PAYS1
	SELECT 
		EP.PERS_LINK, -SUM(SUMMA), MONTH(DATE_DED)
	FROM    
		dbo.empl EP 
		inner join SAL_DED_MONTH S ON (EP.LINK = S.LINK_EMPL AND YEAR(DATE_DED) = @varKSnYear and Month(DATE_DED) <= @nMonth AND [TYPE] = 2)
		INNER JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = EP.pers_link --Было: EP.LINK
	where 
		EP.DEP_LINK = @DEP_LINK	
	GROUP BY 
		EP.PERS_LINK, MONTH(DATE_DED)

	CREATE TABLE #PAYS3(ID INT IDENTITY, LINK_FACE INT, LINK_DED INT, CODE_DED VARCHAR(6), SUMMA NUMERIC(18,2), SUMMA_FAKT NUMERIC(18,2))
	--Стандартные и скидки на мат помощь
	--ПО СОТРУДНИКАМ
	INSERT INTO #PAYS3 (LINK_FACE, LINK_DED, CODE_DED, SUMMA, SUMMA_FAKT)
	SELECT 	
		EP.PERS_LINK, min(S.REF_DED), T.CODE, 
		CONVERT(NUMERIC(18,2), SUM((case when KOEF_VKR is not null then DTD.SUMMA * KOEF_VKR else DTD.SUMMA end) * ISNULL(S.KOL,0) )), 
		SUM(S.SUMMA) 
	FROM 
		dbo.empl EP 
		INNER JOIN SAL_DED_MONTH S ON (EP.LINK = S.LINK_EMPL AND YEAR(DATE_DED) = @varKSnYear and Month(DATE_DED) <= @nMonth AND TYPE = 1)
		INNER JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = EP.pers_link --Было: EP.LINK
		INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION T ON T.LINK = S.REF_DED 
		INNER JOIN dbo.Salary_deductions(@BEGIN_YEAR) DTD on DTD.REF_PAY = S.REF_DED
	where 
		T.NUMBER IN (	1, --Стандартные
						6 --скидки на мат помощь 
						)
		AND			
		EP.DEP_LINK = @DEP_LINK	and S.SUMMA <> 0
	GROUP BY 
		EP.PERS_LINK, T.CODE

	--ПО ДОГОВОРНИКАМ
	INSERT INTO #PAYS3 (LINK_FACE, LINK_DED, CODE_DED, SUMMA, SUMMA_FAKT)
	SELECT 	
		EP.PERS_LINK, min(S.REF_DED), T.CODE, 
		CONVERT(NUMERIC(18,2), SUM((case when KOEF_VKR is not null then DTD.SUMMA * KOEF_VKR else DTD.SUMMA end) * ISNULL(S.KOL,0) )), 
		SUM(S.SUMMA) 
	FROM 
		dbo.REESTR_DGH EP 
		INNER JOIN SAL_DED_MONTH S ON (EP.LINK = S.LINK_DGH AND YEAR(DATE_DED) = @varKSnYear and Month(DATE_DED) <= @nMonth AND S.[TYPE] = 1)
		INNER JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = EP.pers_link --Было: EP.LINK
		INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION T ON T.LINK = S.REF_DED 
		INNER JOIN dbo.Salary_deductions(@BEGIN_YEAR) DTD on DTD.REF_PAY = S.REF_DED
	where 
		T.NUMBER IN (	1, --Стандартные
						6 --скидки на мат помощь 
						)
		AND			
		EP.DEP_LINK = @DEP_LINK	and S.SUMMA <> 0
	GROUP BY 
		EP.PERS_LINK, T.CODE

	--UPDATE #PAYS3
	--SET
	--	SUMMA = (Select sum(SUM_DED) from dbo.TAX_DEDUCTIONS TD where TD.LINK_DEP = @DEP_LINK AND TD.link_person = #PAYS3.LINK_FACE and TD.LINK_DICTION = #PAYS3.LINK_DED and TD.[YEAR] = @varKSnYear and TD.Month1 <= @nMonth)	
	--where
	--	exists (Select * from dbo.TAX_DEDUCTIONS TD where TD.LINK_DEP = @DEP_LINK AND TD.link_person = #PAYS3.LINK_FACE and TD.LINK_DICTION = #PAYS3.LINK_DED and TD.[YEAR] = @varKSnYear and TD.Month1 <= @nMonth)	

	UPDATE #PAYS3
	SET
		SUMMA = ISNULL(SUMMA_FAKT,0)
	where
		ISNULL(SUMMA,0) = 0

	--Прочие вычеты (имущественные, добровольное пенс страхование и пр.)
	INSERT INTO #PAYS3 (LINK_FACE, LINK_DED, CODE_DED, SUMMA, SUMMA_FAKT)
	SELECT 	
		EP.PERS_LINK, min(S.REF_DED), T.CODE, SUM(S.SUMMA), SUM(S.SUMMA) 
	FROM 
		dbo.EMPL EP 
		INNER JOIN SAL_DED_MONTH S ON (EP.LINK = S.LINK_EMPL AND YEAR(DATE_DED) = @varKSnYear and Month(DATE_DED) <= @nMonth AND TYPE = 1)
		INNER JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = EP.pers_link --Было: EP.LINK
		INNER JOIN dbo.DICTIONARY_TYP_DEDUCTION T ON T.LINK = S.REF_DED 
	where 
		T.NUMBER NOT IN (	1, --Стандартные
							6 --скидки на мат помощь 
							)
		AND			
		EP.DEP_LINK = @DEP_LINK	and S.SUMMA <> 0
	GROUP BY 
		EP.PERS_LINK, T.CODE

	-- Общая сумма имущ. вычетов
	update #RES0
	Set siv = ISNULL( (Select sum(P3.SUMMA_FAKT) from #PAYS3 P3 where R.LINK_FACE = P3.LINK_FACE and P3.LINK_DED IN (SELECT DISTINCT LINK_DICTION FROM TAX_DEDUCTIONS td WHERE TD.LINK_DEP = @DEP_LINK AND TD.[YEAR] = @varKSnYear and TD.Month1 <= @nMonth)),0),
		ssv = ISNULL( (Select sum(P3.SUMMA_FAKT) from #PAYS3 P3 where R.LINK_FACE = P3.LINK_FACE and P3.LINK_DED NOT IN (SELECT DISTINCT LINK_DICTION FROM TAX_DEDUCTIONS td WHERE TD.LINK_DEP = @DEP_LINK AND TD.[YEAR] = @varKSnYear and TD.Month1 <= @nMonth)),0)		

	from #RES0 R
	--
	DELETE FROM #P0

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV1 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV1 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV2 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV2 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV3 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV3 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R

		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV4 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV4 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R

		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV5 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV5 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R

		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV6 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV6 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R

		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV7 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV7 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R

		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV8 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV8 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV9 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV9 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV10 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV10 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV11 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV11 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS3 GROUP BY LINK_FACE

	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET KSV12 = (SELECT top 1 P00.CODE_DED FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET SSV12 = (SELECT top 1 P00.SUMMA FROM #PAYS3 P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		DELETE FROM #PAYS3 WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END


	UPDATE #RES0 SET OSD13 = (SELECT top 1 SM FROM #PAYS_R PR WHERE PR.LINK_FACE = R.LINK_FACE) FROM #RES0 R

	----
	UPDATE #RES0 SET SDO13 = OSD13 - ISNULL(SK.SUM_SK, 0.00)
			- ISNULL(SSV1,0.00) - ISNULL(SSV2,0.00) - ISNULL(SSV3,0.00) - ISNULL(SSV4,0.00)
			- ISNULL(SSV5,0.00) - ISNULL(SSV6,0.00) - ISNULL(SSV7,0.00) - ISNULL(SSV8,0.00)
			- ISNULL(SSV9,0.00) - ISNULL(SSV10,0.00) - ISNULL(SSV11,0.00) - ISNULL(SSV12,0.00)
	from #RES0 R LEFT JOIN (Select LINK_FACE, SUM_SK= SUM(SUMMA_DED) from #PAYS_0 GROUP BY LINK_FACE) SK ON R.LINK_FACE = SK.LINK_FACE

	-----
	UPDATE #RES0 SET SDO13 = 0 WHERE SDO13 < 0


	CREATE TABLE #NDFL_TAX(LINK_TAX INT)
	INSERT INTO #NDFL_TAX
	SELECT LINK FROM PAYS P WHERE P.OBJECT = 2 AND P.WAY_CALC = 4

	Create table #NDLF13_tmp (LINK int, SUMMA numeric(18,2))
	Create table #NDLF13 (LINK int, SUMMA numeric(18,2))

	insert into  #NDLF13_tmp (LINK, SUMMA)
	SELECT B.LINK AS LINK, SUM(SUMMA) AS SUMMA
	FROM 
		#S_J_C_Short SJC 
		INNER JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = SJC.LINK_FACE --Было: EP.LINK
		INNER JOIN #NDFL_TAX T ON SJC.LINK_PAYS = T.LINK_TAX  
	WHERE 
		YEAR(PERIOD_BEGIN) = @varKSnYear 
		and month(PERIOD_BEGIN) <= @nMonth
		and sjc.LINK_DEP = @DEP_LINK	
	GROUP BY 
		B.LINK
	---<< Добавление информации по внештатникам
	union all
	SELECT B.LINK AS LINK, SUM(SUMMA) AS SUMMA
	FROM #S_J_C_Short SJC 
		INNER JOIN #NDFL_TAX T ON SJC.LINK_PAYS = T.LINK_TAX  
		INNER JOIN dbo.BufferGetTableById('REP2NDFL') B ON B.LINK = SJC.PERS_LINK --Было: EP.LINK
	WHERE YEAR(PERIOD_BEGIN) = @varKSnYear 
		and month(PERIOD_BEGIN) <= @nMonth
		and ISNULL(SJC.LINK_FACE,0) = 0
		and sjc.LINK_DEP = @DEP_LINK	
	GROUP BY B.LINK

	insert into #NDLF13 (LINK, SUMMA)
	Select LINK, Sum(SUMMA) from #NDLF13_tmp group by LINK
	
	drop table #NDLF13_tmp
	--->>

	UPDATE #RES0 SET NALOGU13 = ISNULL((SELECT SUM(SUMMA) FROM #NDLF13 N WHERE N.LINK = R.LINK_FACE), 0) FROM #RES0 R
	UPDATE #RES0 SET NALOGN13 = SDO13 * (CASE WHEN STATUS = '1' THEN 
		( SELECT  top 1 [PERCENT] / 100 FROM DICTIONARY_RANGE R inner join #NDFL_TAX T on R.LINK_PAYS = T.LINK_TAX WHERE TARIF = 1)
								ELSE 0.30 END)
	--Перечисленная сумма по всем за период
	DECLARE @SUMMA_PLAT_ALL NUMERIC(18,2)
		
	IF @nCHECK_S = 0
		BEGIN
			SET @SUMMA_PLAT_ALL =  @nSumm_For_Check 	
		END
	ELSE
		BEGIN 
			EXEC dbo.SA_NDFL_PLAT @BEGIN_YEAR, @DATE, @DEP_LINK, @SUMMA_PLAT_ALL OUT
		END 
	--Начисленная сумма по всем за период
	DECLARE @SUMMA_NACH_ALL NUMERIC(18,2)
	EXEC dbo.SA_NDFL_NACHISL @BEGIN_YEAR, @DATE, @DEP_LINK, @SUMMA_NACH_ALL OUT
	--Перечисленная за сотрудника	
	UPDATE #RES0 SET NALOG13S = CONVERT(NUMERIC(18,0), ISNULL( @SUMMA_PLAT_ALL * CASE WHEN @SUMMA_NACH_ALL > 0 THEN (NALOGU13	/ @SUMMA_NACH_ALL) ELSE 0 END, 0))
	UPDATE #RES0 SET NALOG13S = CASE WHEN NALOG13S > NALOGU13 THEN NALOGU13 ELSE NALOG13S END

	UPDATE #RES0 SET NOM_SPR = ID + @varKSnFirstNum - 1
	
	---Учет переплаты/недоплаты НДФЛ из остатков с прошлого года
	UPDATE A SET 
		S_5_6 = (CASE WHEN R.NDFL > 0 THEN R.NDFL ELSE 0 END),
		S_5_7 = (CASE WHEN R.NDFL <= 0 THEN - R.NDFL ELSE 0 END)
	FROM
		#RES0 A INNER JOIN 
		(SELECT E.PERS_LINK, NDFL = SUM(SR.NDFL) FROM dbo.SAL_REMAIN SR INNER JOIN dbo.EMPL E ON E.LINK = SR.LINK_EMPL WHERE SR.YEAR_SAL = @varKSnYear GROUP BY E.PERS_LINK) R 
			ON R.PERS_LINK = A.LINK_FACE
	--	
	UPDATE #RES0 SET DOLG_NP = CASE WHEN NALOGN13 - NALOGU13 > 0 THEN NALOGN13 - NALOGU13 ELSE 0 END - ISNULL(S_5_6,0)
	UPDATE #RES0 SET DOLG_NA = CASE WHEN NALOGU13 - NALOGN13 > 0 THEN NALOGU13 - NALOGN13 ELSE 0 END - ISNULL(S_5_7,0)

	--^^^^^^^^^Распределение налога по КБК^^^^^^^^^^
	create table  #PAYS_NDFL (ID INT IDENTITY, LINK_FACE int, LINK_PAYS int, kbk_code varchar(30), SUMMA numeric(18,2))

	INSERT INTO #PAYS_NDFL (LINK_FACE, LINK_PAYS, kbk_code, SUMMA)
	SELECT LINK_FACE, SJC.LINK_PAYS, left(kbk.CODE,30), sum(SJC.SUMMA)
	FROM #S_J_C_SHORT SJC inner join dbo.SAL_SFIN kbk on SJC.LINK_VKR = kbk.LINK
	WHERE 
			YEAR(CASE WHEN SJC.TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN SJC.TYP_PER = 2 THEN SJC.DATE1 END) = @varKSnYear
		and
			month(CASE WHEN SJC.TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN SJC.TYP_PER = 2 THEN SJC.DATE1 END) <= @nMonth
		AND	ISNULL(SJC.PERS_LINK,0) = 0
		AND	SJC.LINK_PAYS IN (Select LINK_TAX from #NDFL_TAX)
	GROUP BY 
		LINK_FACE, LINK_PAYS, kbk.CODE

	union all ---<< Добавление информации по внештатникам	

	SELECT  PERS_LINK, SJC.LINK_PAYS, left(kbk.CODE,20), sum(SJC.SUMMA)
	FROM #S_J_C_SHORT SJC inner join dbo.SAL_SFIN kbk on SJC.LINK_VKR = kbk.LINK
	WHERE 
			YEAR(CASE WHEN SJC.TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN SJC.TYP_PER = 2 THEN SJC.DATE1 END) = @varKSnYear
		and
			month(CASE WHEN SJC.TYP_PER = 1 THEN SJC.PERIOD_BEGIN WHEN SJC.TYP_PER = 2 THEN SJC.DATE1 END) <= @nMonth
		AND	ISNULL(SJC.LINK_FACE,0) = 0
		AND	SJC.LINK_PAYS IN (Select LINK_TAX from #NDFL_TAX)

	GROUP BY 
		PERS_LINK, LINK_PAYS, kbk.CODE
	ORDER BY 
		1, 2, 3



	DELETE FROM #P0

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS_NDFL GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET kbkcode1 = (SELECT top 1 P00.kbk_code FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET kbksum1 = (SELECT top 1 P00.SUMMA FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS_NDFL WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS_NDFL GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET kbkcode2 = (SELECT top 1 P00.kbk_code FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET kbksum2 = (SELECT top 1 P00.SUMMA FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS_NDFL WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS_NDFL GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET kbkcode3 = (SELECT top 1 P00.kbk_code FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET kbksum3 = (SELECT top 1 P00.SUMMA FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS_NDFL WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	END

	INSERT INTO #P0
	SELECT LINK_FACE, MIN(ID) FROM #PAYS_NDFL GROUP BY LINK_FACE
	IF @@ROWCOUNT <> 0 BEGIN
		UPDATE #RES0
		SET kbkcode4 = (SELECT top 1 P00.kbk_code FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
		UPDATE #RES0
		SET kbksum4 = (SELECT top 1 P00.SUMMA FROM #PAYS_NDFL P00, #P0 P0 WHERE P0.ID1 = P00.ID AND P0.LINK_FACE = R.LINK_FACE) FROM #RES0 R
	
		DELETE FROM #PAYS_NDFL WHERE ID IN (SELECT ID1 FROM #P0)
		DELETE FROM #P0
	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


	CREATE TABLE #LOG(
		LINK INT, ERR INT IDENTITY, 
		NUMBER VARCHAR(20), DETAIL VARCHAR(254) )

	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
	
	IF LEN(@varKScInn) = 0
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указан ИНН организации')
	ELSE BEGIN
		IF LEN(@varKScInn) <> 10 BEGIN
			INSERT INTO #LOG (LINK, NUMBER, DETAIL)
			VALUES (0, 'Общие ошибки', 'Неверный ИНН организации')
		END
		ELSE BEGIN
			EXEC SD_CHECK_INN @varKScInn, @varKSRESULT OUTPUT, 0
			IF @varKSRESULT = -1
				INSERT INTO #LOG (LINK, NUMBER, DETAIL)
				VALUES (0, 'Общие ошибки', 'Неверный ИНН организации')
		END
	END

	
	IF LEN(@varKScKPP) = 0
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указан КПП организации')
	ELSE BEGIN
		IF LEN(@varKScKPP) <>9  BEGIN
			INSERT INTO #LOG (LINK, NUMBER, DETAIL)
			VALUES (0, 'Общие ошибки', 'КПП организации должен быть 9 знаков')
		END
	END

	IF LEN(@varKSNALOG) = 0 
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указан код ИФНС')
	ELSE BEGIN
		IF LEN(@varKSNALOG) <> 4  
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Код ИФНС должен быть 4 знака')

	END

	IF LEN(@varKSFULL_NAME) = 0 
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указано наименование организации-отправителя')



	IF LEN(@varKSOKATO) = 0  
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)		VALUES (0, 'Общие ошибки', 'Не указан код ОКТМО')	

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT E.PERS_LINK, '', 'Не указан код ОКТМО у обособленного подразделения, в котором находится сотрудник ' + RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.'
	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
		INNER JOIN #FACES F ON F.PERS_LINK = E.PERS_LINK
		INNER JOIN DBO.PERSON P ON P.LINK = E.PERS_LINK
	WHERE
		LEN(O_OKATO) = 0 
		
	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT E.PERS_LINK, '', 'Не указан либо указан неверно код KPP у обособленного подразделения, в котором находится сотрудник ' + RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.'
	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
		INNER JOIN #FACES F ON F.PERS_LINK = E.PERS_LINK
		INNER JOIN DBO.PERSON P ON P.LINK = E.PERS_LINK		
	WHERE
		LEN(O_KPP) <> 9

	IF LEN(@varKSPHONE) = 0 
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указан контактный телефон')

	IF LEN(@varKSGLBUH) = 0 
		INSERT INTO #LOG (LINK, NUMBER, DETAIL)
		VALUES (0, 'Общие ошибки', 'Не указано ответственное лицо')

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT DISTINCT
		0, 'Общие ошибки', 'В настройках по зарплате не указан вычет с кодом ' + LTRIM(RTRIM(ISNULL(D.SNAME,'')))
	FROM
		dbo.TAX_DEDUCTIONS TD INNER JOIN DBO.DICTIONARY_TYP_DEDUCTION D ON D.LINK = TD.LINK_DICTION
	WHERE
		TD.[YEAR] = @varKSnYear and TD.Month1 <= @nMonth
		AND
		TD.LINK_DICTION NOT IN (SELECT REF_PAY FROM dbo.Salary_deductions(@BEGIN_YEAR))

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '', 'Не указана фамилия' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE LEN(ISNULL(FM, '')) = 0 AND OSD13 > 0 

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '', 'Не указано имя' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE LEN(ISNULL(IM, '')) = 0 AND OSD13 > 0 

/*	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указано отчество' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE LEN(ISNULL(Ot, '')) = 0 AND OSD13 > 0 
*/
/*	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT NOM_SPR, NOM_SPR,  'Неверный ИНН сотрудника' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE dbo.IsValidINNFiz(INNFIZ) = 0
*/
	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указан статус работника' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE STATUS = '' AND OSD13 > 0 

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указано гражданство' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE GRAZD IS NULL AND OSD13 > 0 
/*
	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT NOM_SPR, NOM_SPR,  'Не указан ИНН' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE ISNULL(INNFIZ, '') = ''
*/
	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указан ИНН либо документ, удостоверяющий личность' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE ISNULL(INNFIZ, '') = '' and KDVD IS NULL AND OSD13 > 0 

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указан ИНН либо номер документа' + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE ISNULL(INNFIZ, '') = '' AND ISNULL(SERNOM, '') = '' AND OSD13 > 0 

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указан ИНН либо дата рождения'  + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE ISNULL(INNFIZ, '') = '' AND BIRTH IS NULL AND OSD13 > 0 

	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Не указан адрес'  + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 WHERE ISNULL(INNFIZ, '') = '' AND link_adr IS NULL AND OSD13 > 0 

	SET @varKSCNT = 0
	SELECT @varKSCNT = COUNT(DISTINCT LINK) FROM #LOG WHERE LINK > 0

	UPDATE #RES0
	SET ERR = 1
	WHERE LINK_FACE IN (SELECT LINK_FACE FROM #LOG)

	/*заявленные имущественные вычеты*/
	Select LINK_PERSON, NUM_REF, DATE_REF, IFNS_CODE  into #td  from dbo.TAX_DEDUCTIONS td
	where TD.LINK_DEP = @DEP_LINK AND link = (select min(link) from dbo.TAX_DEDUCTIONS td1 where TD1.LINK_DEP = @DEP_LINK AND td1.LINK_PERSON =  td.LINK_PERSON and td1.[YEAR] = @varKSnYear and td1.Month1 <= @nMonth)

	declare @KBK_DEFAULT varchar(254)
	Set @KBK_DEFAULT = (select Top 1 CODE_KBK from dbo.sd_empl where LINK_KBK > 0)

	UPDATE #RES0 Set kbkcode1 = @KBK_DEFAULT, kbksum1 = 0 where ISNULL(kbksum1,0) = 0

	/*Контроль имущественных вычетов*/
	INSERT INTO #LOG (LINK, NUMBER, DETAIL)
	SELECT LINK_FACE, '',  'Указаны не все данные в уведомлении на имущественный вычет'  + ' ' + ISNULL(FM, '') + ' ' + ISNULL(IM, '') + ' '  + ISNULL(Ot, '')
	FROM #RES0 inner join  #td on #RES0.LINK_FACE = #td.LINK_PERSON 
	WHERE rtrim(ltrim(ISNULL(NUM_REF,''))) = '' or rtrim(ltrim(ISNULL(IFNS_CODE,''))) = '' or DATE_REF is null AND OSD13 > 0 

	CREATE TABLE #RES_OUT (ID INT,LINK_FACE INT,mes INT,LINK_INC INT,CODE_INC VARCHAR(4),SUMMA_INC NUMERIC(18,2),LINK_DED INT,CODE_DED VARCHAR(3),SUMMA_DED NUMERIC(18,2),ID2 INT)

	INSERT INTO #RES_OUT (ID, LINK_FACE, mes, LINK_INC, CODE_INC, SUMMA_INC, LINK_DED, CODE_DED, SUMMA_DED, ID2)
	SELECT ID, LINK_FACE, mes, LINK_INC, CODE_INC, SUMMA_INC, LINK_DED, CODE_DED, SUMMA_DED, ID2 = 0 
	FROM #PAYS_0 
	ORDER BY LINK_FACE, MES, CODE_INC
	
	---СОРТИРОВКА
	CREATE TABLE #RES_OUT_ORD (NUM_PP INT IDENTITY(1,1), ID INT, LINK_FACE INT)
	INSERT INTO #RES_OUT_ORD (ID, LINK_FACE)
	SELECT ID, LINK_FACE FROM #PAYS_0 ORDER BY LINK_FACE, MES, CODE_INC
	--
	CREATE TABLE #RES_OUT_ORD2 (LINK_FACE INT, MIN_NUM INT)
	INSERT INTO #RES_OUT_ORD2 (LINK_FACE, MIN_NUM)
	SELECT LINK_FACE, MIN(NUM_PP) FROM #RES_OUT_ORD GROUP BY LINK_FACE
	---СОРТИРОВКА ДЛЯ КАЖДОГО ФИЗЛИЦА
	UPDATE R
	SET R.ID2 = O.NUM_PP - O2.MIN_NUM + 1
	FROM 
		#RES_OUT R 
		INNER JOIN #RES_OUT_ORD O ON O.ID = R.ID
		INNER JOIN #RES_OUT_ORD2 O2 ON O2.LINK_FACE = R.LINK_FACE

	CREATE TABLE #ORDERS (ID int)
	DECLARE @SQL VARCHAR(1000)
	SET @SQL = 'ALTER TABLE #ORDERS ADD [NOM_SPR] INT IDENTITY(' + RTRIM(str(ISNULL(@varKSnFirstNum,1))) + ',1)'
	EXEC(@SQL)

	INSERT INTO #ORDERS (ID) 
	SELECT DISTINCT ID 
	FROM #RES0 
	WHERE LINK_FACE IN ( Select DISTINCT LINK_FACE from #RES_OUT where [ID2]%2 = 1 )
			--AND ISNULL(OSD13,0) > 0
	ORDER BY ID

	--UPDATE #ORDERS SET NOM_SPR = NOM_SPR + @varKSnFirstNum - 1

	--- общее количество документов
	UPDATE #DEP SET DOCCOUNT = ISNULL((SELECT MAX(NOM_SPR) FROM #ORDERS),0)

	-------------------
	SELECT 
		R.ID, O.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.ksv1, R.ssv1, R.ksv2, R.ssv2, R.ksv3, R.ssv3, R.ksv4, R.ssv4, R.ksv5, R.ssv5, R.ksv6, R.ssv6, 
		R.ksv7, R.ssv7, R.ksv8, R.ssv8, R.ksv9, R.ssv9, R.ksv10, R.ssv10, R.ksv11, R.ssv11, R.ksv12, R.ssv12, 
		R.ssv, R.siv, R.osd13, R.sdo13, R.nalogn13, R.nalogu13, R.nalog13s, R.err, R.S_5_6, R.S_5_7, R.dolg_np, R.dolg_na, 
		R.kbkcode1, R.kbkcode2, R.kbkcode3, R.kbkcode4, R.kbksum1, R.kbksum2, R.kbksum3, R.kbksum4, 
		R.VIFNSPL, R.ZSummPL, R.UdSumPL, R.VzkIFNS, 
		ndoc_td = NUM_REF,
		ddoc_td = DATE_REF,
		nalog	= @varKSNALOG,
		KPP1 = ISNULL(R.O_KPP,@varKScKPP),
		OKATO1 = replace(ISNULL(R.O_OKATO,@varKSOKATO),' ',''),
		OKATO2 = (Case when ISNULL(kbksum2,0) <> 0 then @varKSOKATO else '' end),
		OKATO3 = (Case when ISNULL(kbksum3,0) <> 0 then @varKSOKATO else '' end),
		OKATO4 = (Case when ISNULL(kbksum4,0) <> 0 then @varKSOKATO else '' end),
		OKTMO1 = replace(ISNULL(R.O_OKATO,@varKSOKTMO),' ',''),
		OKTMO2 = (Case when ISNULL(kbksum2,0) <> 0 then @varKSOKTMO else '' end),
		OKTMO3 = (Case when ISNULL(kbksum3,0) <> 0 then @varKSOKTMO else '' end),
		OKTMO4 = (Case when ISNULL(kbksum4,0) <> 0 then @varKSOKTMO else '' end),
		T.M1, T.CINC1, T.SINC1, T.CDED1, T.SDED1, T.M2, T.CINC2, T.SINC2, T.CDED2, T.SDED2,
		#td.LINK_PERSON, #td.NUM_REF, #td.DATE_REF, #td.IFNS_CODE
	FROM #RES0 R 
		INNER JOIN #ORDERS O ON O.ID = R.ID
		INNER JOIN ( 
			Select	T1.LINK_FACE, M1= T1.MES, CINC1= T1.CODE_INC, SINC1= T1.SUMMA_INC, CDED1= T1.CODE_DED, SDED1= T1.SUMMA_DED, M2= T2.MES, CINC2= T2.CODE_INC, SINC2= T2.SUMMA_INC, CDED2= T2.CODE_DED, SDED2= T2.SUMMA_DED
			from	(Select * from #RES_OUT where [ID2]%2 = 1) T1 left join (Select * from #RES_OUT where [ID2]%2 = 0) T2 on T1.link_FACE = T2.LINK_FACE AND T1.[ID2] = (T2.[ID2]-1)
		) T on R.LINK_FACE = T.LINK_FACE
		left join  #td on R.LINK_FACE = #td.LINK_PERSON
	--where OSD13 > 0 
	ORDER BY O.NOM_SPR, T.M1, T.CINC1, T.M2, T.CINC2

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

	UPDATE L SET
		NUMBER = O.NOM_SPR
	FROM 
		#LOG L
		INNER JOIN #RES0 R ON L.LINK = R.LINK_FACE
		INNER JOIN #ORDERS O ON O.ID = R.ID
	
	SELECT * FROM #LOG ORDER BY LINK, ERR
	---
	EXEC dbo.BufferClear

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






GO


GRANT EXECUTE ON dbo.[SD_REP_2NDFL] TO PUBLIC

GO



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

GO
CREATE PROCEDURE [dbo].SA_TABEL_FILL_EMPL
	@varKSYear 		int,  
	@varKSMonth 		int, 		
	@varKSLinkTab 	int = 0,
	@DEP_LINK int = null,
	@BufferCode varchar(10) = null 
AS

DECLARE @varKSDateBegin datetime,
		@varKSDateEnd	  datetime

set @DEP_LINK = coalesce(@DEP_LINK,(select DEP_LINK from user_dep))

SET @varKSDateBegin = dbo.ConvertDMY2Date(1,@varKSMonth,@varKSYear) 
SET @varKSDateEnd 	= dbo.DateEndOfMonth(@varKSDateBegin)

CREATE TABLE #empl (link int, num_stake numeric(5,2), DateAccept datetime, DateSack datetime, GRAPH_LINK int, ETS_RAZR tinyint)
CREATE INDEX #EMPL_LINK ON #empl (LINK ASC)

if ltrim(rtrim(coalesce(@BufferCode,''))) = ''
	insert into #empl 
	select e.link, st.num_stake, beg.DATE_BEGIN, dis.DIS_DATE, E.GRAPH_LINK, ISNULL(ST.ETS_RAZR,0)
	from dbo.empl E
		inner join (
		Select distinct IM.empl_link, IM.DATE_BEGIN from dbo.item_move IM where IM.active = 1 AND IM.new_face = 1
		) beg on E.link = beg.empl_link --определить дату приема
		left join (
		Select distinct IDF.empl_link, IDF.DIS_DATE from dbo.item_dis_face IDF where IDF.active=1 AND COALESCE(IDF.dis_date,@varKSDateEnd) < @varKSDateEnd
		) dis on E.link = dis.empl_link --определить дату увольнения
		left join (
		Select distinct IM.empl_link, IM.num_stake, IM.ETS_RAZR from 
			dbo.ORDERS o
			INNER JOIN dbo.sa_item_move im on im.order_link = o.link
			LEFT JOIN dbo.ORDER_TYPES ot  on ot.code = o.type
			where ISNULL(ot.CODE,0) IN (0,1,2,101,102) AND IM.active = 1 AND @varKSDateEnd BETWEEN IM.date_begin AND ISNULL(IM.date_end3,'29990101')
		) ST on E.link = ST.empl_link --определить кол-во ставок
	where DEP_LINK = @DEP_LINK order by e.link	
else
	insert into #empl 
	select B.link, st.num_stake, beg.DATE_BEGIN, dis.DIS_DATE, E.GRAPH_LINK, ISNULL(ST.ETS_RAZR,0)
	from dbo.empl E inner join dbo.Buffer B on E.link = B.link
		inner join (
		Select distinct IM.empl_link, IM.DATE_BEGIN from dbo.item_move IM where IM.active = 1 AND IM.new_face = 1
		) beg on B.link = beg.empl_link --определить дату приема
		left join (
		Select distinct IDF.empl_link, IDF.DIS_DATE from dbo.item_dis_face IDF where IDF.active=1 AND COALESCE(IDF.dis_date,@varKSDateEnd) < @varKSDateEnd
		) dis on B.link = dis.empl_link --определить дату увольнения
		left join (
		Select distinct IM.empl_link, IM.num_stake, IM.ETS_RAZR from 
			dbo.ORDERS o
			INNER JOIN dbo.sa_item_move im on im.order_link = o.link
			LEFT JOIN dbo.ORDER_TYPES ot  on ot.code = o.type			
			where ISNULL(ot.CODE,0) IN (0,1,2,101,102) AND IM.active = 1 AND @varKSDateEnd BETWEEN IM.date_begin AND ISNULL(IM.date_end3,'29990101')			
		) ST on B.link = ST.empl_link --определить кол-во ставок
	where RTRIM(LTRIM(B.ID)) = RTRIM(LTRIM(@BufferCode)) order by B.link

CREATE TABLE #varKSS
(
 LINK_EMPL int,
 [TYPE] int,
 [PRIOR] int,
 [HOUR]  numeric(6,2),
 [DATE_1] datetime,
 [DATE_2] datetime,
 [DOC]	int)

CREATE TABLE #ITEM_VACATION(
	[LINK] INT,
	[MOVED] int,
	[EMPL_LINK] int,
	[VAC_LINK] int ,
	[TYPE_LINK] int,
	[PERIOD_BEGIN] datetime ,
	[PERIOD_END] datetime,
	[DATE_BEGIN] datetime,
	[DATE_END] datetime,
	[REASON] varchar(254),
	[ORDER_LINK] int,
	[ACTIVE] TINYINT)

INSERT	#ITEM_VACATION (LINK, MOVED, EMPL_LINK, VAC_LINK, TYPE_LINK, PERIOD_BEGIN, PERIOD_END, DATE_BEGIN, DATE_END, REASON, ORDER_LINK, ACTIVE)
SELECT	LINK, MOVED, EMPL_LINK, VAC_LINK, TYPE_LINK, PERIOD_BEGIN, PERIOD_END, DATE_BEGIN, DATE_END, REASON, ORDER_LINK, ACTIVE FROM dbo.ITEM_VACATION WHERE COMPENS = 0


INSERT	#ITEM_VACATION
SELECT	0,
		IV.MOVED,
		IVB.EMPL_LINK,
		IV.VAC_LINK,
		IV.TYPE_LINK,
		IV.PERIOD_BEGIN,
		IV.PERIOD_END,
		DATEADD(DAY,IVB.BREAK_WORK_DAYS,IVB.DATE_BREAK) AS DATE_BEGIN,
		DATEADD(DAY,IVB.LEN_KAL_DAYS,IV.DATE_END) AS DATE_END,
		'',
		IV.ORDER_LINK,
		IV.ACTIVE
FROM	
	dbo.ITEM_VACATION_BREAK IVB 
	LEFT JOIN dbo.ITEM_VACATION IV ON IV.LINK = IVB.VAC_LINK
WHERE	
	EXISTS (SELECT * FROM dbo.Buffer B WHERE B.ID = RTRIM(LTRIM(@BufferCode)) AND B.LINK = IVB.EMPL_LINK)
	AND IVB.ACTIVE = 1
	AND IVB.BREAK_WORK_DAYS > 0
	

INSERT INTO #varKSS (LINK_EMPL,[TYPE],[PRIOR],[HOUR],[DATE_1],[DATE_2],[DOC])
-- БОЛЬНИЧНЫЕ --
SELECT LINK_EMPL,[TYPE],[PRIOR],[HOUR],[DATE_1],[DATE_2],[DOC] FROM 
(SELECT 
	SD.LINK_EMPL,
	[TYPE] = N.TYPE_LINK,
	[PRIOR] = TD.PRIORITET,
	[HOUR] = TD.[HOUR],
	[DATE_1] = (CASE WHEN SD.DATE1 < @varKSDateBegin THEN @varKSDateBegin ELSE SD.DATE1 END),
	[DATE_2] = (CASE WHEN SD.DATE2 > @varKSDateEnd  THEN @varKSDateEnd ELSE SD.DATE2 END),
	[DOC]	= 1 
FROM 
	dbo.SDOC S 
	INNER JOIN dbo.SDOC_DIS SD ON  S.LINK = SD.LINK_UP
	INNER JOIN dbo.NETRUD N ON SD.TYPE = N.LINK
	INNER JOIN dbo.TYP_DAYS TD ON TD.LINK = N.TYPE_LINK
	inner join #empl E on E.link = SD.LINK_EMPL
WHERE 
	(SD.DATE1 BETWEEN @varKSDateBegin AND @varKSDateEnd OR SD.DATE2 BETWEEN @varKSDateBegin AND @varKSDateEnd OR
	  ((SD.DATE1 < @varKSDateBegin) AND(SD.DATE2 > @varKSDateEnd)))
UNION
-- ОТПУСКА --
SELECT 	
	V.EMPL_LINK,
	[TYPE] = VV.TYPE_LINK,
	[PRIOR] = TD.PRIORITET,
	[HOUR] = TD.[HOUR],
	[DATE_1] = (CASE WHEN DATE_BEGIN < @varKSDateBegin THEN @varKSDateBegin ELSE DATE_BEGIN END),
	[DATE_2] = (CASE WHEN ISNULL((SELECT top 1 (CASE
							WHEN IVB.DATE_BREAK - 1 > (ISNULL((SELECT top 1 (CASE
													    WHEN IVD.NEW_DATE_END > V.DATE_END
														THEN IVD.NEW_DATE_END
													    ELSE V.DATE_END
													 END)  
 											   FROM ITEM_VACATION_DIS IVD
									                   WHERE IVD.VAC_LINK = V.LINK
												 AND IVD.ACTIVE = 1
											   ORDER BY IVD.NEW_DATE_END DESC),
											  V.DATE_END))
					                    THEN (ISNULL((SELECT top 1 (CASE
											    WHEN IVD.NEW_DATE_END > V.DATE_END
												THEN IVD.NEW_DATE_END
											    ELSE  V.DATE_END
											END)
					 				  FROM ITEM_VACATION_DIS IVD
									  WHERE IVD.VAC_LINK = V.LINK
										AND IVD.ACTIVE = 1
									  ORDER BY IVD.NEW_DATE_END DESC),
									 V.DATE_END))
							ELSE IVB.DATE_BREAK - 1
						     END) 
					FROM ITEM_VACATION_BREAK IVB
					WHERE IVB.VAC_LINK = V.LINK
					      AND IVB.ACTIVE = 1
					ORDER BY IVB.DATE_BREAK DESC), 
         			(ISNULL((SELECT top 1 (CASE
								   WHEN IVD.NEW_DATE_END > V.DATE_END
									THEN IVD.NEW_DATE_END
								   ELSE V.DATE_END
							       END)  
 						 FROM ITEM_VACATION_DIS IVD 
						 WHERE IVD.VAC_LINK = V.LINK
					      	       AND IVD.ACTIVE = 1
						 ORDER BY IVD.NEW_DATE_END DESC),
						V.DATE_END))
					) > @varKSDateEnd 
				THEN @varKSDateEnd  
                    	ELSE ISNULL((SELECT top 1 (CASE
						       WHEN IVB.DATE_BREAK - 1 > (ISNULL((SELECT top 1 (CASE
													    WHEN IVD.NEW_DATE_END > V.DATE_END
														THEN IVD.NEW_DATE_END
													    ELSE V.DATE_END
													END)  
 											  FROM ITEM_VACATION_DIS IVD
                    									  WHERE IVD.VAC_LINK = V.LINK
												AND IVD.ACTIVE = 1
											  ORDER BY IVD.NEW_DATE_END DESC),
											 V.DATE_END)) 
                   					    THEN (ISNULL((SELECT top 1 (CASE
											    WHEN IVD.NEW_DATE_END > V.DATE_END
											       THEN IVD.NEW_DATE_END
											    ELSE V.DATE_END
										        END)
	 								  FROM ITEM_VACATION_DIS IVD
									  WHERE IVD.VAC_LINK = V.LINK
									        AND IVD.ACTIVE = 1
									  ORDER BY IVD.NEW_DATE_END DESC),
								         V.DATE_END)) 
							ELSE IVB.DATE_BREAK - 1
						   END)
				     FROM ITEM_VACATION_BREAK IVB
				     WHERE IVB.VAC_LINK = V.LINK
					   AND IVB.ACTIVE = 1
				     ORDER BY IVB.DATE_BREAK DESC),
				    ISNULL((SELECT top 1 (CASE
							      WHEN IVD.NEW_DATE_END > V.DATE_END
								  THEN IVD.NEW_DATE_END
							      ELSE V.DATE_END
							  END)  
 					    FROM ITEM_VACATION_DIS IVD 
					    WHERE IVD.VAC_LINK = V.LINK
						  AND IVD.ACTIVE = 1
					    ORDER BY IVD.NEW_DATE_END DESC),
					   V.DATE_END))
		 END),
	[DOC] = 2
FROM 
	#item_vacation v 
	inner join dbo.VACATION_VID VV on V.TYPE_LINK = VV.LINK
	INNER JOIN dbo.TYP_DAYS TD ON TD.LINK = VV.TYPE_LINK
	inner join #empl E on E.link = V.EMPL_LINK
WHERE	
	V.ACTIVE = 1 
	AND (V.DATE_BEGIN BETWEEN @varKSDateBegin AND @varKSDateEnd 
		OR V.DATE_END BETWEEN @varKSDateBegin AND @varKSDateEnd 
		OR ((V.DATE_BEGIN<@varKSDateBegin) AND (V.DATE_END>@varKSDateEnd))
		OR EXISTS (SELECT * FROM dbo.VACATION_DIS VD WHERE VD.EMPL_LINK = V.EMPL_LINK AND VD.ACTIVE = 1 AND VD.NEW_DATE_END > @varKSDateBegin AND VD.VAC_LINK = V.LINK)
	)
UNION
-- КОМАНДИРОВКИ --
SELECT 
	T.EMPL_LINK,
	[TYPE] 	= KV.TYPE_LINK,
	[PRIOR] = TD.PRIORITET,
	[HOUR] 	= TD.[HOUR],
	[DATE_1] = (CASE WHEN [DATE_BEGIN]<@varKSDateBegin THEN @varKSDateBegin ELSE [DATE_BEGIN] END), 
	[DATE_2] = (CASE 
					WHEN ISNULL(ITL.NEW_DATE_END,T.DATE_END)> @varKSDateEnd 
					THEN @varKSDateEnd 
					ELSE ISNULL(ITL.NEW_DATE_END,T.DATE_END)
				END),	
	[DOC]= 3
FROM 
	#empl E
	INNER JOIN dbo.item_travel T on E.link = T.EMPL_LINK
	INNER JOIN dbo.KOMAND_VID KV on t.type_link = KV.LINK
	INNER JOIN dbo.TYP_DAYS TD ON KV.TYPE_LINK = TD.LINK		
	LEFT JOIN (
				SELECT ITL.TRAVEL_LINK, NEW_DATE_END = MAX(ITL.NEW_DATE_END) 
				FROM dbo.ITEM_TRAVEL_LONG ITL WHERE ITL.ACTIVE = 1 
				GROUP BY ITL.TRAVEL_LINK
			) ITL ON ITL.TRAVEL_LINK = T.LINK
WHERE 
	T.ACTIVE = 1 
	AND (
			T.DATE_BEGIN BETWEEN @varKSDateBegin AND @varKSDateEnd 
			OR T.DATE_END BETWEEN @varKSDateBegin AND @varKSDateEnd 
			OR ((T.DATE_BEGIN<@varKSDateBegin) AND(T.DATE_END>@varKSDateEnd)) 
		)
	
)  TAB



IF EXISTS(SELECT * FROM #varKSS WHERE [TYPE] IS NULL)
	BEGIN
		DECLARE @varKSMesStr varchar(1000)
		SET @varKSMesStr = 'Формирование прервано! Не заполнен тип дня в одном из справочников: "Виды отпусков","Причины нетрудоспособности", "Виды командировок"!'+CHAR(13)+CHAR(10)+'Заполните справочники и запустите формирование табеля снова!'
		RAISERROR (@varKSMesStr,11,1)
 		RETURN 1005
	END

DECLARE @varKSG TABLE
(
 LINK_EMPL int,
 [DATE1] 	datetime,
 [DAY] 		int,
 [HOUR]  	numeric(6,2),
 [DAY_TIP]	int,
 [LINK_UP]	int,
 [PRIOR]	int,
 [LINK_WORK] int,	
 [LINK_WORK_TYPE] int,
 [DATE_BEG] DATETIME, 
 [DATE_END] DATETIME,
 [GRAPH_LINK] int,
 [num_stake] numeric(5,2)
 )		


DECLARE @LINK_OSN INT
SET @LINK_OSN= (Select TOP 1 LINK from TABEL_nastr2 where code = 'ОСН')

---Основное место
INSERT INTO @varKSG(LINK_EMPL, [DATE1],[DAY],[HOUR],[DAY_TIP],[LINK_UP],[PRIOR],[LINK_WORK], [LINK_WORK_TYPE], [DATE_BEG], [DATE_END], GRAPH_LINK, [num_stake])
SELECT	
		 E.LINK,
		 dbo.ConvertDMY2Date([DAY],@varKSMonth,@varKSYear) AS DATE1,
		 [DAY] = [DAY],
		 [HOUR] = [HOUR],
		 [DAY_TIP] = TD_LINK,
		 [LINK_UP] = 0,
		 [PRIOR] = PRIORITET,
		 [LINK_WORK] = NULL,
		 [LINK_WORK_TYPE] = @LINK_OSN,
		 [DATE_BEG] = DateAccept,
		 [DATE_END] = DateSack,
		 E.GRAPH_LINK,
		 E1.[num_stake]
FROM 
	dbo.KD_GRAPH_TABLE  GT
	inner join dbo.EMPL E on E.GRAPH_LINK = GT.LINK_GR
	inner join #empl E1 on E1.link = E.link
WHERE 
	[MONTH] = @varKSMonth AND [YEAR] = @varKSYear
	AND E.LINK NOT IN (Select link_empl from dbo.STO_TARIF_EMPL TE where TE.link_type = @LINK_OSN)

--Всевозможные совмещения
INSERT INTO @varKSG(LINK_EMPL, [DATE1],[DAY],[HOUR],[DAY_TIP],[LINK_UP],[PRIOR],[LINK_WORK], [LINK_WORK_TYPE], [DATE_BEG], [DATE_END], GRAPH_LINK, [num_stake])
SELECT	
		 E.link_empl,
		 dbo.ConvertDMY2Date([DAY],@varKSMonth,@varKSYear) AS DATE1,
		 [DAY] = [DAY],
		 [HOUR] = [HOUR],
		 [DAY_TIP] = TD_LINK,
		 [LINK_UP] = 0,
		 [PRIOR] = PRIORITET,
		 [LINK_WORK] = E.LINK, --сама работа
		 [LINK_WORK_TYPE] = E.LINK_TYPE, --Вид работы
		 [DATE_BEG] = DATE_BEGIN,
		 [DATE_END] = CASE WHEN ISNULL(E1.DATESACK, @varKSDateEnd) < ISNULL(DATE_END,@varKSDateEnd) THEN ISNULL(E1.DATESACK, @varKSDateEnd) ELSE ISNULL(DATE_END,@varKSDateEnd) END,
		 [GRAPH_LINK] = LINK_GRAPH,
		 E.[num_stake]
FROM 
	dbo.KD_GRAPH_TABLE  GT
	inner join dbo.STO_TARIF_EMPL E on E.LINK_GRAPH = GT.LINK_GR
	inner join #empl E1 on E1.link = E.link_empl
WHERE 
	[MONTH] = @varKSMonth AND [YEAR] = @varKSYear

---
DECLARE @varKSCurs CURSOR,
		@varKSCurType int,
		@varKSCurPrior int,
		@varKSCurHour numeric(6,2),
		@varKSCurDate1 datetime,				
		@varKSCurDate2 datetime,
		@varKSCurDoc	int,	
		@varKSCom int,
		@varKSBol int,
		@varKSOtp int,
		@link_empl int

SELECT @varKSCom = CONVERT(INT,VALUE) FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'TABEL_OPTIONS_COM') AND SID IS NULL
SELECT @varKSBol = CONVERT(INT,VALUE) FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'TABEL_OPTIONS_BOL') AND SID IS NULL
SELECT @varKSOtp = CONVERT(INT,VALUE) FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'TABEL_OPTIONS_OTP') AND SID IS NULL

SET @varKSCom = ISNULL(@varKSCom,0)
SET @varKSBol = ISNULL(@varKSBol,0)
SET @varKSOtp = ISNULL(@varKSOtp,0)

SET @varKSCurs = CURSOR FORWARD_ONLY
FOR SELECT * FROM #varKSS 
OPEN @varKSCurs
FETCH NEXT FROM @varKSCurs INTO @link_empl, @varKSCurType,@varKSCurPrior,@varKSCurHour,@varKSCurDate1,@varKSCurDate2,@varKSCurDoc
WHILE @@FETCH_STATUS = 0
BEGIN
	IF @varKSCurDoc = 2	
		IF @varKSOtp = 1
			UPDATE @varKSG
			SET DAY_TIP = @varKSCurType, [PRIOR] = @varKSCurPrior, [HOUR] = @varKSCurHour
			WHERE LINK_EMPL = @link_empl and DATE1 BETWEEN @varKSCurDate1 AND @varKSCurDate2 AND [PRIOR] < @varKSCurPrior AND DAY_TIP NOT IN (SELECT LINK FROM dbo.KD_TYP_DAYS WHERE WORK_D = 11)
		ELSE
			UPDATE @varKSG
			SET DAY_TIP = @varKSCurType, [PRIOR] = @varKSCurPrior, [HOUR] = @varKSCurHour
			WHERE LINK_EMPL = @link_empl and DATE1 BETWEEN @varKSCurDate1 AND @varKSCurDate2 AND [PRIOR] < @varKSCurPrior

	IF @varKSCurDoc = 1 
		IF @varKSBol = 1
			UPDATE @varKSG
			SET DAY_TIP = @varKSCurType, [PRIOR] = @varKSCurPrior, [HOUR] = @varKSCurHour
			WHERE LINK_EMPL = @link_empl and DATE1 BETWEEN @varKSCurDate1 AND @varKSCurDate2 AND [PRIOR] < @varKSCurPrior AND DAY_TIP NOT IN (SELECT LINK FROM dbo.KD_TYP_DAYS WHERE WORK_D = 11) 
		ELSE
			UPDATE @varKSG
			SET DAY_TIP = @varKSCurType, [PRIOR] = @varKSCurPrior, [HOUR] = @varKSCurHour
			WHERE LINK_EMPL = @link_empl and DATE1 BETWEEN @varKSCurDate1 AND @varKSCurDate2 AND [PRIOR] < @varKSCurPrior

	IF @varKSCurDoc = 3 
		IF @varKSCom = 1
			UPDATE @varKSG
			SET DAY_TIP = @varKSCurType, [PRIOR] = @varKSCurPrior, [HOUR] = @varKSCurHour
			WHERE LINK_EMPL = @link_empl and DATE1 BETWEEN @varKSCurDate1 AND @varKSCurDate2 AND [PRIOR] < @varKSCurPrior AND DAY_TIP NOT IN (SELECT LINK FROM dbo.KD_TYP_DAYS WHERE WORK_D = 11) 
		ELSE
			UPDATE @varKSG
			SET DAY_TIP = @varKSCurType, [PRIOR] = @varKSCurPrior, [HOUR] = @varKSCurHour
			WHERE LINK_EMPL = @link_empl and DATE1 BETWEEN @varKSCurDate1 AND @varKSCurDate2 AND [PRIOR] < @varKSCurPrior

	FETCH NEXT FROM @varKSCurs INTO @link_empl, @varKSCurType,@varKSCurPrior,@varKSCurHour,@varKSCurDate1,@varKSCurDate2,@varKSCurDoc

END
CLOSE @varKSCurs
DEALLOCATE @varKSCurs

--Проверка, чтобы за один и тот же день не было 2 табеля

SELECT @varKSYear AS Y, @varKSMonth AS M, @varKSLinkTab AS L
INTO #PAR

CREATE TABLE #TABOLD (LINK_EMPL INT, Y INT, M INT, D INT)

DECLARE @I INT, @SQL VARCHAR(8000)
SET @I = 1
WHILE @I <= 31
BEGIN
	SET @SQL = 
 + '
INSERT INTO #TABOLD (LINK_EMPL, Y, M, D)
SELECT DISTINCT T.LINK_EMPL, Y= YEAR(PERIOD), M = MONTH(PERIOD), D = ' + CONVERT(VARCHAR(3),@I) + '
FROM
	DBO.TABELS T INNER JOIN DBO.TABELS_W W ON T.LINK = W.LINK_UP
	INNER JOIN #empl E on E.link = T.LINK_EMPL
	INNER JOIN #PAR P ON 1=1
WHERE
	D' + CONVERT(VARCHAR(3),@I) + ' > 0
	AND
	YEAR(PERIOD) = P.Y AND MONTH(PERIOD) = P.M AND LINK_DOC <> P.L
'
	SET @I = @I + 1

	EXEC (@SQL)

END

DECLARE @END_DATE DATETIME
SET @END_DATE = (SELECT TOP 1 DATE FROM DBO.SDOC WHERE LINK = @varKSLinkTab)

DECLARE @ISMINUTES TINYINT
SET @ISMINUTES = DBO.SA_GET_OPTION_BY_CODE('TABEL_OPT10') --УЧЕТ ВРЕМЕНИ В ЧАСАХ И МИНУТАХ

SELECT DISTINCT 
	LINK_EMPL, G.LINK_WORK, G.LINK_WORK_TYPE, G.DATE1, G.[DAY], 
	Convert(NUMERIC(5,2), DBO.MINUTES_TO_NUM(DBO.NUM_TO_MINUTES(G.[HOUR],@ISMINUTES) * COALESCE(G.NUM_STAKE,0) ,@ISMINUTES)) AS HOURS,
	G.DAY_TIP,G.LINK_UP,D.SYMB AS SYMB,D.NAME AS NAME,
	D.DOP_TAB, G.DATE_BEG, G.DATE_END, G.GRAPH_LINK, E.ETS_RAZR
FROM 
	@varKSG G 
	inner join dbo.KD_TYP_DAYS D on G.DAY_TIP =  D.LINK 
	inner join #empl E on E.link = G.LINK_EMPL
WHERE 
	G.DATE1 BETWEEN DATE_BEG AND COALESCE(DATE_END,@varKSDateEnd)
	AND NOT EXISTS (SELECT LINK_EMPL FROM #TABOLD O WHERE O.LINK_EMPL = G.LINK_EMPL AND O.Y = YEAR(G.DATE1) AND O.M = MONTH(G.DATE1) AND O.D = DAY(G.DATE1))
	AND (G.DATE1 <= @END_DATE OR @END_DATE IS NULL)

ORDER BY 1


GO


GRANT EXECUTE ON dbo.[SA_TABEL_FILL_EMPL] TO PUBLIC

GO


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


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

GO

CREATE PROCEDURE BK_CREATE_PROV_CONV148N_INV_KAZNA
		@intDOC_LINK	INT,
		@intDEL_OLD		TINYINT = 0

AS
BEGIN
	DECLARE
		@intTO_MZ		INT,
		@intTO_OS		INT,
		@intTO_TMC		INT, 
		@intTO_SERV		INT,
		@intKIND_DOC		INT ,
		@intTYPE_NUMBER		INT ,

		@intOBJ_REF	INT,
		@intACC_LINK	INT,
		@intDEP_LINK	INT,
		
		@intAC108_DOC	INT,
		@intAC104_DOC	INT,
		@intKBK_DOC	INT,

		@intLINK_EMPL	INT,
		@intLINK_SUB	INT,
		@intLINK_KBK	INT,
		@strDOC_NUMBER	VARCHAR (25),
		@strINVOICE_NUMBER	VARCHAR (25),
		@dDOC_DATE	DATETIME,
		@intSELLER	INT,
		@intDOG_LINK	INT,
		@intDOG_TYPE	INT,
		@intLINK_OSNOV	INT,
		@intLINK_TO	INT,
		@intERROR	INT,

	-- Табличная часть
		@cTYPE_INV			VARCHAR (30),
		@intLINK_INV		INT,
		@strINV_CODE		VARCHAR (20),
		@strNEW_INV_CODE	VARCHAR (20),
		@intNEW_GRP_LINK	INT,
		@intNEW_GRP_CODE	VARCHAR (10),
		@intACC_101			INT,
		@intACC_104			INT,
		@nBALANCE			NUMERIC (20,2),
		@nAMORT				NUMERIC (20,2),

		@intSTEP1	INT,	-- 1=Баланс\2=амортизация
		@intSTEP2	INT,	-- 1=Списание со 101(104)\2=Счет казны 108(104)
		
		@cGRID_SOURCE	CHAR (1),

		@intDEP_LINK1	INT,

		@intNEW_NOMEN	INT,
		@intOLD_NOMEN	INT,

		--- Для создания номеклатуры ---
		@strNOM_CODE	VARCHAR (20),
		@strNOM_NAME	VARCHAR (254),
		@intGRP_INV	INT,
		@intUM		INT,
		@strSERIES	VARCHAR (30),
		@strGRP_CODE	VARCHAR (5),
		@bitIS_EXTRA	BIT,
		@intLINK_OKDP INT,
		@nCOEFF NUMERIC (18,9),
		@intPRICE_TYPE TINYINT,
		@intLINK_OKPD INT,
		@nCOEFF_OKPD NUMERIC (18,9),
		@intISUSED	TINYINT,

		@SUM		NUMERIC (28,4),
		@SUM_NALOG	NUMERIC (28,4),
		@SUMMA_ALL	NUMERIC (28,4),
		@LINK_EKR	INT,
		@cCODE_EKR	VARCHAR (3),
		@intROWCOUNT	INT,

	/* -- 20070317 -- */
		@cSOURCE	CHAR (1),
		@cSINTH	CHAR (3),
		@cANALIT CHAR (3),
		@cANALIT_108 CHAR (3),
		@intP_EKR	TINYINT,
		@p_KASSA	TINYINT,
		@intKBK_DEFAULT	INT,

		@intSGU_241	INT,
		@intSGU_180	INT,
		
	/* --- РАБОТА С G_PROV1 --- */
		@intLINK_G1	INT,
		@strNAME_OPER	VARCHAR (254),
		@intORDERS	INT,

	/* --- РАБОТА С G_PROV2 --- */
		@intLINK_G2	INT,
		@intECON_OPER	INT,
		@intSTORNO	INT,
		@strNAME_OPER2	VARCHAR (254),
		@strNAME_OPER21	VARCHAR (254),
		@intLINK_G2_TO	INT,
		@SUMMA_G2	NUMERIC (28,4),
			
		@D_SUMMA	NUMERIC (28,4),
		@K_SUMMA	NUMERIC (28,4),
		@QTY		NUMERIC (28,4),

	/* --- РАБОТА С G_PROV_AP --- */
		@intSGU		INT,
		@intACCOUNT	INT,
		@intAP_KBK	INT,
		@intEKR		INT,
		@intKAU		INT,
		@intDB_KR	TINYINT,
		@intAP_DEP	INT,
		@intAP_SUB	INT,
		@intAP_EMP	INT,
		@intAP_ACC	INT,
		@intAP_NOMEN	INT,
		@AP_INDATE	DATETIME,
		@intAP_INV	INT,
		@intAP_TMC	INT,
		@intAP1		INT,
		@intAP2		INT,
		@intAP3		INT,

	--- ТАБЛИЦА АНАЛИТИЧЕСКИХ ПРИЗНАКОВ ---
		@intSGU_DT	INT,
		@intACCOUNT_DT	INT,
		@intAP_KBK_DT	INT,
		@intEKR_DT		INT,
		@intKAU_DT		INT,
		@intDB_KR_DT	TINYINT,
		@intAP_DEP_DT	INT,
		@intAP_SUB_DT	INT,
		@intAP_EMP_DT	INT,
		@intAP_ACC_DT	INT,
		@intAP_NOMEN_DT	INT,
		@intAP_INDATE_DT	INT,
		@intAP_INV_DT	INT,
		@intAP_TMC_DT	INT,
		@intAP1_DT		INT,
		@intAP2_DT		INT,
		@intAP3_DT		INT,

		@intSGU_KT	INT,
		@intACCOUNT_KT	INT,
		@intAP_KBK_KT	INT,
		@intEKR_KT		INT,
		@intKAU_KT		INT,
		@intDB_KR_KT	TINYINT,
		@intAP_DEP_KT	INT,
		@intAP_SUB_KT	INT,
		@intAP_EMP_KT	INT,
		@intAP_ACC_KT	INT,
		@intAP_NOMEN_KT	INT,
		@intAP_INDATE_KT	INT,
		@intAP_INV_KT	INT,
		@intAP_TMC_KT	INT,
		@intAP1_KT		INT,
		@intAP2_KT		INT,
		@intAP3_KT		INT,

		@dDATE_REST		DATETIME

	--- !!!СОХРАНЯЕМ ПРОВОДКИ!!! --- 
	IF @intDEL_OLD = 1
	BEGIN
		DELETE FROM dbo.G_PROV1 WHERE LINK_UP = @intDOC_LINK
		SET @intERROR = @@ERROR
		IF @intERROR <> 0
			RETURN @intERROR
	END

	SELECT @intDEP_LINK = DEP_LINK,
		@dDOC_DATE = DATE,
		@intAC108_DOC	= LN_AC108,
		@intAC104_DOC	= LN_AC104,
		@intKBK_DOC = LN_KBK
	FROM dbo.BK_DOC_CONV148N_INV_KAZNA
	WHERE LINK = @intDOC_LINK

	SELECT @intSGU_241	= LINK FROM dbo.KOSGU WHERE CODE = '241'
	SELECT @intSGU_180	= LINK FROM dbo.KOSGU WHERE CODE = '180'

	SET @dDATE_REST = DATEADD (DAY, 1, @dDOC_DATE)

	DECLARE #DATA_CURSOR CURSOR LOCAL STATIC	
		FOR SELECT TYPE_INV,
			INV_LINK,
			INV_CODE,
			INV_CODE1,
			GRP_LINK1,
			GRP_CODE1,
			ACC101_LN,
			ACC104_LN,
			BALANCE,
			AMORT
		FROM dbo.BK_DOC_CONV148N_INV_KAZNA_TABLE 
		WHERE LINK_UP = @intDOC_LINK

	OPEN #DATA_CURSOR
	FETCH FROM #DATA_CURSOR
		INTO @cTYPE_INV, @intLINK_INV, @strINV_CODE, @strNEW_INV_CODE,
			@intNEW_GRP_LINK, @intNEW_GRP_CODE,
			@intACC_101, @intACC_104, @nBALANCE, @nAMORT

	WHILE @@FETCH_STATUS = 0
	BEGIN
		
		-- ЗАПИСЬ В G_PROV1 --
		SELECT	@strNAME_OPER = 'Перевод остатков имущества казны № ' + @strINV_CODE
		SET	@intORDERS = COALESCE ((SELECT MAX (ORDERS) FROM G_PROV1 WHERE LINK_UP = @intDOC_LINK), 0) + 1
		
		SET @intLINK_G1 = NULL
		EXEC @intERROR = dbo.X_UPDATE_G_PROV1 @intLINK_G1 OUTPUT, @intDOC_LINK, @intLINK_TO,
			@strNAME_OPER, @intORDERS
		IF @intERROR <> 0
			RETURN @intERROR

		IF @intLINK_G1 IS NULL
		BEGIN
			FETCH NEXT FROM #DATA_CURSOR
				INTO @cTYPE_INV, @intLINK_INV, @strINV_CODE, @strNEW_INV_CODE,
					@intNEW_GRP_LINK, @intNEW_GRP_CODE,
					@intACC_101, @intACC_104, @nBALANCE, @nAMORT
			CONTINUE
		END

		SET @intAP_NOMEN = CASE WHEN @cTYPE_INV IN ('DICTIONARY_SERV', 'BV_NOMENCLATURE') THEN @intLINK_INV ELSE NULL END
		SET @intAP_INV = CASE WHEN @cTYPE_INV = 'INVENTORY_CARD' THEN @intLINK_INV ELSE NULL END
		SET @intAP_TMC	= CASE WHEN @cTYPE_INV = 'DICTIONARY_TMC' THEN @intLINK_INV ELSE NULL END

		-- !!!ПЕРЕВОДИМ ОСТАТКИ!!! --
		SET @intSTEP1 = 0
		WHILE @intSTEP1 < 2
		BEGIN
			SELECT @intSTEP1 = @intSTEP1 + 1
			IF @intSTEP1 = 1		-- @intSTEP1 = 1 баланс. стоимость
				SELECT @intACCOUNT = @intACC_101
			ELSE	-- @intSTEP1 = 2 амортиация
				SELECT @intACCOUNT = @intACC_104

			DECLARE #CURSOR_REST CURSOR STATIC LOCAL
			FOR SELECT R.ACCOUNT, R.KBK, R.EKR, R.DEP, R.SUB,
						R.EMP, R.KAU, R.DEP_ACC, R.INDATE,
						R.AP1, R.AP2, R.AP3, R.D_QUANTITY, R.D_SUMMA, R.K_SUMMA,
						SA.cSINTH, SA.cANALIT 
				FROM dbo.ARestTableByDate (@dDATE_REST, @intACCOUNT) R
				INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = R.ACCOUNT
					AND SA.cSOURCE = '1')
				WHERE R.DEP_LINK = @intDEP_LINK
					AND	((@intAP_NOMEN IS NOT NULL AND R.NOMEN = @intLINK_INV)
						OR (@intAP_INV IS NOT NULL AND R.INV = @intLINK_INV)
						OR (@intAP_TMC IS NOT NULL AND R.TMC = @intLINK_INV))

			OPEN #CURSOR_REST 
			
			FETCH FROM #CURSOR_REST
				INTO @intACCOUNT, @intLINK_KBK, @LINK_EKR,
						@intAP_DEP, @intLINK_SUB, @intLINK_EMPL, @intKAU,
						@intACC_LINK, @AP_INDATE, @intAP1, @intAP2, @intAP3,
						@QTY, @D_SUMMA, @K_SUMMA,
						@cSINTH, @cANALIT 
			
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @intSTEP2 = 0
				WHILE @intSTEP2 < 2
				BEGIN

					SELECT @intSGU_DT = NULL, @intSGU_KT = NULL,
							@intEKR_DT = @LINK_EKR, @intEKR_KT = @LINK_EKR

					SET @intSTEP2 = @intSTEP2 + 1

					IF @intSTEP2 = 1	--- Отдельный КБК для учета имущества казны ---
						SELECT @intAP_KBK_DT = @intLINK_KBK, @intAP_KBK_KT = @intLINK_KBK
/*					ELSE
						SELECT @intAP_KBK_DT = ISNULL (@intKBK_DOC, @intLINK_KBK),
							@intAP_KBK_KT = ISNULL (@intKBK_DOC, @intLINK_KBK)
					
*/
					IF @intSTEP1 = 1		-- !!!Балансовая стоимсоть!!! 
						IF @intSTEP2 = 1	-- Списание балансовой стоимости --
						BEGIN
							SELECT @intACCOUNT_KT = @intACCOUNT,
									@intACCOUNT_DT = dbo.BK_GetDBKTAccount (@intACCOUNT, '401', '03', DEFAULT),
									@SUMMA_G2 = ISNULL (@D_SUMMA, 0), @QTY = ISNULL (@QTY, 0),
									@strNAME_OPER2 = 'Списание балансовой стоимости'

							EXEC dbo.BX_BPROV_GET_DEFAULT_SGU @intACCOUNT_KT, 1, @intSGU_KT OUTPUT
							SELECT @intSGU_DT = @intSGU_241

							IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS
										WHERE LINK = @intACCOUNT_DT
											AND P_KASSA = 1)
								SET @intEKR_DT = @intSGU_DT
						END
						ELSE	-- @intSTEP2 = 2 Счет казны --
						BEGIN
							SELECT @intAP_KBK_DT = ISNULL (@intKBK_DOC, @intLINK_KBK),
								@intAP_KBK_KT = @intLINK_KBK 

							IF ISNULL (@intAC108_DOC, 0) = 0
							BEGIN 
								SET @cANALIT_108 = CASE
											WHEN @cSINTH = '101'
													AND (@cANALIT IN ('01', '02', '03'))
												THEN '01'
											WHEN @cSINTH = '102' THEN '03'
											WHEN @cSINTH = '103' THEN '04'
											WHEN @cSINTH = '105' THEN '05'
											ELSE '02'
										END
					
								SET @intACCOUNT_DT = dbo.BK_GetDBKTAccount (@intACCOUNT, '108', @cANALIT_108, DEFAULT)
							END
							ELSE
								SET @intACCOUNT_DT = @intAC108_DOC

							SELECT @intACCOUNT_KT = dbo.BK_GetDBKTAccount (@intACCOUNT, '401', '03', DEFAULT),
									@SUMMA_G2 = ISNULL (@D_SUMMA, 0), @QTY = ISNULL (@QTY, 0),
									@strNAME_OPER2 = 'Стоимость имущества казны'

							exec dbo.BX_BPROV_GET_DEFAULT_SGU @intACCOUNT_DT, 0, @intSGU_DT output
							SELECT @intSGU_KT = @intSGU_180
							IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS
										WHERE LINK = @intACCOUNT_KT
											AND P_KASSA = 1)
								SET @intEKR_KT = @intSGU_KT
						END
					ELSE	-- @intSTEP1 = 2 !!!Амортизация!!! 
						IF @intSTEP2 = 1	-- Списание амортизации --
						BEGIN
							SELECT @intACCOUNT_DT = @intACCOUNT,
									@intACCOUNT_KT = dbo.BK_GetDBKTAccount (@intACCOUNT, '401', '03', DEFAULT),
									@SUMMA_G2 = ISNULL (@K_SUMMA, 0), @QTY = 0,
									@strNAME_OPER2 = 'Списание амортизации'

							exec dbo.BX_BPROV_GET_DEFAULT_SGU @intACCOUNT_DT, 0, @intSGU_DT output
							IF @intSGU_DT IS NULL 
								SELECT @intSGU_DT = (SELECT TOP 1 LINK_SGU
											FROM dbo.S_ACCOUNTS_SGU WHERE ACCOUNT = @intACCOUNT_DT)

							SELECT @intSGU_KT = @intSGU_241
							IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS
										WHERE LINK = @intACCOUNT_KT
											AND P_KASSA = 1)
								SET @intEKR_KT = @intSGU_KT
						END
						ELSE	-- @intSTEP2 = 2 Счет казны --
						BEGIN
							SELECT @intAP_KBK_DT = @intLINK_KBK,
								@intAP_KBK_KT = ISNULL (@intKBK_DOC, @intLINK_KBK)

							IF ISNULL (@intAC104_DOC, 0) = 0
							BEGIN
								SET @cANALIT_108 = CASE
											WHEN @cSINTH = '104'
													AND (@cANALIT IN ('01', '02', '03'))
												THEN '10'
											WHEN @cSINTH = '104' AND @cANALIT = '09' THEN '12'
											ELSE '11'
										END
								SET @intACCOUNT_KT = dbo.BK_GetDBKTAccount (@intACCOUNT, '104', @cANALIT_108, DEFAULT)
							END
							ELSE
								SET @intACCOUNT_KT = @intAC104_DOC

							SELECT @intACCOUNT_DT = dbo.BK_GetDBKTAccount (@intACCOUNT, '401', '03', DEFAULT),
									@SUMMA_G2 = ISNULL (@K_SUMMA, 0), @QTY = 0,
									@strNAME_OPER2 = 'Амортиация имущества казны'

							exec dbo.BX_BPROV_GET_DEFAULT_SGU @intACCOUNT_KT, 1, @intSGU_KT output
							IF @intSGU_KT IS NULL 
								SELECT @intSGU_KT = (SELECT TOP 1 LINK_SGU
											FROM dbo.S_ACCOUNTS_SGU WHERE ACCOUNT = @intACCOUNT_KT)

							SELECT @intSGU_DT = @intSGU_180
							IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS
										WHERE LINK = @intACCOUNT_DT
											AND P_KASSA = 1)
								SET @intEKR_DT = @intSGU_DT
						END
					
					SET @intLINK_G2 = NULL
					SET	@intORDERS = COALESCE ((SELECT MAX (ORDERS)
												FROM G_PROV2 WHERE LINK_UP = @intLINK_G1), 0) + 1
					EXEC @intERROR = dbo.X_UPDATE_G_PROV2 @intLINK_G2 OUTPUT, @intLINK_G1, NULL,
								@SUMMA_G2, @QTY, 0, @strNAME_OPER2, @intECON_OPER, @intORDERS
					IF @intERROR <> 0
						RETURN @intERROR

					IF @intLINK_G2 IS NULL 
						OR @intACCOUNT_DT IS NULL
						OR @intACCOUNT_KT IS NULL
					BEGIN
						FETCH NEXT FROM #CURSOR_REST
							INTO @intACCOUNT, @intLINK_KBK, @LINK_EKR,
									@intAP_DEP, @intLINK_SUB, @intLINK_EMPL, @intKAU,
									@intACC_LINK, @AP_INDATE, @intAP1, @intAP2, @intAP3,
									@QTY, @D_SUMMA, @K_SUMMA,
									@cSINTH, @cANALIT 
						CONTINUE
					END
					
					--- СОХРАНЯЕМ ДБ ---
					EXEC @intERROR = dbo.X_UPDATE_G_PROV_AP @intLINK_G2, 0, @intACCOUNT_DT,
								@intAP_KBK_DT, @intEKR_DT, @intAP_DEP,
								@intLINK_SUB, @intLINK_EMPL, @intAP_NOMEN, @intAP_INV,
								@intKAU, @intACC_LINK, 
								@intAP_TMC, @AP_INDATE, @intAP1, @intAP2, @intAP3, @intSGU_DT

					--- СОХРАНЯЕМ КТ ---
					EXEC @intERROR = dbo.X_UPDATE_G_PROV_AP @intLINK_G2, 1, @intACCOUNT_KT,
								@intAP_KBK_KT, @intEKR_KT, @intAP_DEP,
								@intLINK_SUB, @intLINK_EMPL, @intAP_NOMEN, @intAP_INV,
								@intKAU, @intACC_LINK, 
								@intAP_TMC, @AP_INDATE, @intAP1, @intAP2, @intAP3, @intSGU_KT

				END		-- @intSTEP2 < 2
				FETCH NEXT FROM #CURSOR_REST
					INTO @intACCOUNT, @intLINK_KBK, @LINK_EKR,
							@intAP_DEP, @intLINK_SUB, @intLINK_EMPL, @intKAU,
							@intACC_LINK, @AP_INDATE, @intAP1, @intAP2, @intAP3,
							@QTY, @D_SUMMA, @K_SUMMA,
							@cSINTH, @cANALIT 
			END	-- #CURSOR_REST

			CLOSE #CURSOR_REST
			DEALLOCATE #CURSOR_REST

			IF @cTYPE_INV = 'BV_NOMENCLATURE' 
				SELECT @intSTEP1 = 2
		END		-- @intSTEP1 < 2

		IF NOT EXISTS (SELECT * FROM dbo.G_PROV2 WHERE LINK_UP = @intLINK_G1)
			DELETE FROM dbo.G_PROV1 WHERE LINK = @intLINK_G1

		---!!!ПЕРЕНОС МАТ.ЦЕННОСТЕЙ НА НОВЫЕ ГРУППЫ!!!---
		SELECT @intNEW_NOMEN = NULL, @intOLD_NOMEN = NULL
		IF @cTYPE_INV = 'INVENTORY_CARD' 
		BEGIN
			SELECT @intOLD_NOMEN = T1.NOMENCLATURE,
					@intNEW_NOMEN = T2.NOMEN_148
			FROM dbo.INVENTORY T1
			LEFT JOIN dbo._148N_MOVE_INV_KAZNA T2 ON (T2.NOMEN_25 = T1.NOMENCLATURE)
			WHERE T1.LINK = @intLINK_INV
			
		--- Создание новой записи в номенклаторе ---
			IF @intNEW_NOMEN IS NULL
			BEGIN
				SELECT 
					@strNOM_NAME = N.[NAME],
					@intUM 	= N.UM,
					@strSERIES	= N.SERIES,
					@bitIS_EXTRA	=  N.IS_EXTRA,
					@intLINK_OKDP = O.LINK,
					@nCOEFF = N.COEFF,
					@intPRICE_TYPE = N.PRICE_TYPE,
					@intLINK_OKPD =	LINK_OKPD,
					@nCOEFF_OKPD =	COEFF_OKPD,
					@intISUSED	=	ISUSED
				FROM dbo.NOMENCLATURE N
				LEFT JOIN dbo.OKDP O ON (O.LINK = N.LINK_OKDP)
				WHERE N.LINK = @intOLD_NOMEN

				IF @intNEW_GRP_LINK IS NULL
					SELECT @intNEW_GRP_LINK FROM dbo.GROUP_INV WHERE CODE = @intNEW_GRP_CODE

				EXEC @intERROR = dbo.BV_GET_NOMEN_NEXT_CCODE @strNOM_CODE OUTPUT, @intNEW_GRP_CODE
				IF @intERROR <> 0
					RETURN @intERROR

				EXEC @intERROR = dbo.BV_SAVE_NOMENCLATURE 
						@varKSparLINK		=	@intNEW_NOMEN OUTPUT,
						@varKSparLINK_GRP	=	@intNEW_GRP_LINK,
						@varKSparCODE		=	@strNOM_CODE,
						@varKSparNAME		=	@strNOM_NAME,
						@varKSparSERIES		=	@strSERIES,
						@varKSparLINK_UM	=	@intUM,
						@lbIS_EXTRA			=	@bitIS_EXTRA,
						@varKSparLINK_OKDP	=	@intLINK_OKDP,
						@varKSparLINK_OKPD	=	@intLINK_OKPD,
						@nCOEFF			=	@nCOEFF,
						@nCOEFF_OKPD	=	@nCOEFF_OKPD,
						@intPRICE_TYPE		=	@intPRICE_TYPE,
						@intISUSED	= @intISUSED

/*				EXEC @intERROR = dbo.BV_SAVE_NOMENCLATURE @intNEW_NOMEN OUTPUT,
					@intNEW_GRP_LINK, @strNOM_CODE,
					@strNOM_NAME, @strSERIES, @intUM, @bitIS_EXTRA, @intLINK_OKDP,
						@nCOEFF, @intPRICE_TYPE 
*/
				IF @intERROR <> 0
					RETURN @intERROR

--SELECT @strNOM_NAME, @strNOM_CODE, @intNEW_NOMEN

			END	-- IF @intNEW_NOMEN IS NULL
			
			IF ISNULL (@strNEW_INV_CODE, '') = ''
				SELECT @strNEW_INV_CODE = @strINV_CODE

			UPDATE dbo.INVENTORY SET NOMENCLATURE = @intNEW_NOMEN,
					CODE = @strNEW_INV_CODE
			WHERE LINK = @intLINK_INV

			INSERT INTO dbo._148N_MOVE_INV_KAZNA (NOMEN_25, INV, NOMEN_148)
			VALUES (@intOLD_NOMEN, @intLINK_INV, @intNEW_NOMEN)
		END	-- IF @cTYPE_INV = 'INVENTORY_CARD' 

		IF @cTYPE_INV = 'BV_NOMENCLATURE' 
		BEGIN
		--- Перенос на новую группу ---
			SELECT @intNEW_GRP_LINK FROM dbo.GROUP_INV WHERE CODE = @intNEW_GRP_CODE
			UPDATE dbo.NOMENCLATURE SET GROUP_INV = @intNEW_GRP_LINK,
						CODE = @strNEW_INV_CODE
			WHERE LINK = @intLINK_INV

--			INSERT INTO dbo._148N_MOVE_INV_KAZNA (NOMEN_25, INV, NOMEN_148)
--			VALUES (@intOLD_NOMEN, @intLINK_INV, @intNEW_NOMEN)

		END	-- @cTYPE_INV = 'BV_NOMENCLATURE' 

--		SELECT @intOLD_NOMEN, @intNEW_NOMEN 

-- SELECT * FROM dbo.INVENTORY
-- SELECT * FROM dbo.NOMENCLATURE
-- SELECT * FROM _148N_MOVE_INV_KAZNA

/*

EXEC BK_CREATE_PROV_CONV148N_INV_KAZNA 28484, 1

		SELECT *
		FROM dbo.BK_DOC_CONV148N_INV_KAZNA_TABLE 
		WHERE LINK_UP = @intDOC_LINK
*/

		FETCH NEXT FROM #DATA_CURSOR
			INTO @cTYPE_INV, @intLINK_INV, @strINV_CODE, @strNEW_INV_CODE,
				@intNEW_GRP_LINK, @intNEW_GRP_CODE,
				@intACC_101, @intACC_104, @nBALANCE, @nAMORT
	END	-- #DATA_CURSOR

	CLOSE #DATA_CURSOR
	DEALLOCATE #DATA_CURSOR

	UPDATE dbo.G_PROV SET SUMMA = ISNULL(dbo.CalcDocSumma(LINK), 0)
	WHERE LINK = @intDOC_LINK
END

GO


GRANT EXECUTE ON dbo.[BK_CREATE_PROV_CONV148N_INV_KAZNA] TO PUBLIC

GO



GO
SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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




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

CREATE      PROCEDURE dbo.BB_GET_LINK_KBK_BY_CODE_2016
	@iLinkKBK	 int=null output,
	@iLinkEKR	 int=null output,
	@iLinkDCL	 int=null output,
	@cErrorTxt 	 varchar(100) output,
	@cCodeKBK 	 varchar(20) = '',
	@cTypeKBK 	 varchar(2) = '',
	@cCodeDCL 	 varchar(20) = '',
	@addVKR		 tinyint = 1 -- Добавить отсутсвущие ВКР
	
AS
declare @varKSiRet int,
	@iL_PPP	   int,
	@iL_Razd   int,
	@iL_C_St   int,
	@iL_Rash   int,
	@iLinkIVF  int,
	@iLinkD    int,
	@iLinkProg int,

	@varKSCode_PPP	 char(3),
	@varKSCode_Razd	 char(4),
	@varKSCode_CelSt char(10),
	@varKSCode_Rash	 char(3),
	@varKSCode_Ekr	 char(3),
	@cCodeIVF		 char(10),
	@cCodeD			 char(10),
	@cCodeP			 char(4),
	@iTypeKBK		 tinyint
	
			
SET @varKSiRet = 0
set @cErrorTxt = ''
set @varKSCode_Ekr = substring(@cCodeKBK,18,3)

if @cTypeKBK = ''
begin
	select @iLinkKBK = link from KL_KBK where replace(CODE,'.','') = @cCodeKBK
	if @iLinkKBK is null or @iLinkKBK = 0
		set @cErrorTxt = 'Не найден КБК в справочнике'

end
-- ВКР
IF @cTypeKBK = '10'
begin
select @varKSCode_PPP = left(@cCodeKBK,3),
		@varKSCode_Razd = substring(@cCodeKBK,4,4),
		@varKSCode_CelSt = substring(@cCodeKBK,8,10),
		@varKSCode_Rash = right(@cCodeKBK,3)

	IF isnull((select max(link) from bi_diction_vkr where Code_FKR_M = @varKSCode_PPP AND Code_FKR_D = @varKSCode_Razd AND Code_FKR_T = @varKSCode_CelSt AND Code_FKR_E = @varKSCode_Rash),0) > 0
		select @iLinkKBK = link from bi_diction_vkr where
			Code_FKR_M = @varKSCode_PPP
			AND Code_FKR_D = @varKSCode_Razd
			AND Code_FKR_T = @varKSCode_CelSt
			AND Code_FKR_E = @varKSCode_Rash
	ELSE 
		IF @addVKR = 1
		BEGIN
			select @iL_PPP = max(link) from kl_admin_bs where code = @varKSCode_PPP
			if @iL_PPP is null 
				set @cErrorTxt = 'Не найден администратор БС с кодом ' + @varKSCode_PPP

			select @iL_Razd = max(link) from kl_DIVISION where code = @varKSCode_Razd
			if @iL_Razd is null 
				set @cErrorTxt = 'Не найден раздел, подраздел БС с кодом ' + @varKSCode_Razd

			select @iL_C_St = max(link) from kl_Target_Item where code = @varKSCode_CelSt
			if @iL_C_St is null 
				set @cErrorTxt = 'Не найдена целевая статья  с кодом ' + @varKSCode_CelSt

			select @iL_Rash = max(link) from kl_Expend where code = @varKSCode_Rash
			if @iL_Rash is null 
				set @cErrorTxt = 'Не найден вид расхода с кодом ' + @varKSCode_Rash
	
			SET @iLinkKBK = 0
			exec @varKSiRet = dbo.BI_SAVE_VKR @iLinkKBK output, 'Сгенерированный ВКР', @iL_PPP, @iL_Razd, @iL_C_St, @iL_Rash
			if @varKSiRet <> 0 
				set @cErrorTxt = 'Ошибка при добавлении ВКР'
		END
		ELSE
			set @cErrorTxt = 'Запрещено добавление КБК в справочник.'
		
		if charindex('(', @cCodeDCL) > 0
		begin
			select @varKSCode_Ekr = substring(@cCodeDCL,charindex('(', @cCodeDCL) + 1,3)
			select @cCodeDCL = replace(@cCodeDCL,'(' + @varKSCode_Ekr + ')', '' )
		end
		else 
			set @varKSCode_Ekr = ''
			
		select @iLinkEKR = max(link) from dbo.KOSGU where CODE = @varKSCode_Ekr
		if @iLinkEKR is null 
			set @cErrorTxt = 'Не найден КОСГУ ' + @varKSCode_Ekr	
		--if @varKSCode_Ekr <> ''
		--begin
		--	select @iLinkEKR = max(link) from dbo.KOSGU where CODE = @varKSCode_Ekr
		--	if @iLinkEKR is null 
		--		set @cErrorTxt = 'Не найден КОСГУ ' + @varKSCode_Ekr
		--end
				

end

-- КИВФ
IF @cTypeKBK = '31' or @cTypeKBK = '32'
begin
	select @iTypeKBK = case @cTypeKBK when '31' then 3 else 4 end
	select @varKSCode_PPP = left(@cCodeKBK,3),
		@cCodeIVF = substring(@cCodeKBK,4,10),
		@cCodeP = substring(@cCodeKBK,14,4),
		@varKSCode_Ekr = right(@cCodeKBK,3)
	
	set @iLinkKBK = (select max(link) 
				from dbo.KL_KBK
				where CODE = rtrim(@varKSCode_PPP) + '.' + rtrim(@cCodeIVF) and TYPE = 4)
	IF @iLinkKBK is null
		IF @addVKR = 1
		BEGIN
			select @iL_PPP = max(link) from kl_admin_bs where code = @varKSCode_PPP
			if @iL_PPP is null 
				set @cErrorTxt = 'Не найден администратор БС с кодом ' + @varKSCode_PPP

			select @iLinkIVF = max(link) from dbo.KL_IVF where CODE = @cCodeIVF
			if @iLinkIVF is null 
				set @cErrorTxt = 'Не найден источник финансирования с кодом ' + @cCodeIVF
			
			select @iLinkProg = max(link) from dbo.KL_PROG where CODE = @cCodeP
			if @iLinkProg is null 
				set @cErrorTxt = 'Не найдена программа с кодом ' + @cCodeP
			
			select @iLinkEKR = max(link) from dbo.KOSGU where CODE = @varKSCode_Ekr
			if @iLinkEKR is null 
				set @cErrorTxt = 'Не найден КОСГУ ' + @varKSCode_Ekr
			
			
			SET @iLinkKBK = 0
			exec @varKSiRet = dbo.BI_SAVE_KBK @iLinkKBK output, @iTypeKBK, 'Сгенерированный ИВФ', @iL_PPP, null, @iLinkIVF, @iLinkProg, null, null, null, @iLinkEKR
			if @varKSiRet <> 0 
				SET @varKSiRet = -1
		END
		ELSE
			set @cErrorTxt = 'Запрещено добавление КБК в справочник.'

end


-- КД
IF @cTypeKBK = '20'
begin
	select @varKSCode_PPP = left(@cCodeKBK,3),
			@cCodeD = substring(@cCodeKBK,4,10),
			@cCodeP = substring(@cCodeKBK,14,4),
			@varKSCode_Ekr = right(@cCodeKBK,3)
	
	set @iLinkKBK = (select max(link) 
				from dbo.KL_KBK
				where CODE = rtrim(@varKSCode_PPP) + '.' + rtrim(@cCodeD) and TYPE = 2)
	IF @iLinkKBK is null
		IF @addVKR = 1
		BEGIN
			select @iL_PPP = max(link) from kl_admin_bs where code = @varKSCode_PPP
			if @iL_PPP is null 
				set @cErrorTxt = 'Не найден администратор БС с кодом ' + @varKSCode_PPP

			select @iLinkD = max(link) from dbo.KL_KD where CODE = @cCodeD
			if @iLinkD is null 
				set @cErrorTxt = 'Не найден вид дохода с кодом ' + @cCodeD

			select @iLinkProg = max(link) from dbo.KL_PROG where CODE = @cCodeP
			if @iLinkProg is null 
				set @cErrorTxt = 'Не найдена программа с кодом ' + @cCodeP
			
			select @iLinkEKR = max(link) from dbo.KOSGU where CODE = @varKSCode_Ekr
			if @iLinkEKR is null 
				set @cErrorTxt = 'Не найден КОСГУ ' + @varKSCode_Ekr
			
			
			SET @iLinkKBK = 0
			exec @varKSiRet = dbo.BI_SAVE_KBK @iLinkKBK output, 2, 'Сгенерированный КД', @iL_PPP, @iLinkD, null, @iLinkProg, null, null, null, @iLinkEKR
			
			if @varKSiRet <> 0 
				SET @varKSiRet = -1
		END
		ELSE
			set @cErrorTxt = 'Запрещено добавление КБК в справочник.'

end

if isnull(@cCodeDCL, '') <> ''
begin
	select @iLinkDCL = max(link) from dbo.DOP_CLASSIF where CODE = @cCodeDCL
	if @iLinkDCL is null 
		set @cErrorTxt = 'Не найдена доп.классификация ' + @cCodeDCL
end
			
if @cErrorTxt <> '' 
	SET @varKSiRet = -1


return @varKSiRet




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_SFIN_SAVE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_SFIN_SAVE]

GO

CREATE   PROCEDURE dbo.SA_SFIN_SAVE 
	@LINK	int	OUTPUT,
	@CODE	[varchar] (30),
	@NAME	[varchar] (120) ,
	@LINK_KBK int,
	@SOURCE	tinyint,
	@USER_ACC varchar(4),
	@LINK_KAU int,
	@LINK_DOP_KL int,
	@COMMENT varchar(100),
	@ENVD TINYINT = 0,
	@ACC_ESN varchar(6) = '',
	@LINK_LACC int = NULL,
	@USED TINYINT = 1,
	@LINK_CH_SFIN INT,
	@DATE_CHANGE DATETIME = NULL
AS
DECLARE @varKSERROR	tinyint,
	@varKStrancount	int, 
	@varKSRowCount int

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



IF @LINK_LACC = 0
	SET @LINK_LACC = NULL

IF @ACC_ESN IS NULL 
	SET @ACC_ESN = '' 

IF @CODE IS NULL OR @CODE = '' OR @NAME IS NULL OR @NAME = ''
BEGIN
	ROLLBACK
	RETURN 5
END

/*exec SA_SFIN_SAVE 37,'021.0101.0300000.006','Яранский райфо',1253,1,
						NULL,NULL,NULL,'перенесено из справочника КБК',0,'401.20',67771,NULL
						*/

IF EXISTS (SELECT * FROM dbo.SAL_SFIN WHERE LINK <> @LINK AND CODE = @CODE AND USED = @USED) BEGIN
	raiserror('Уже есть источник финансирования с таким кодом',11,1)	
	ROLLBACK
	RETURN 0
END

SET @SOURCE = COALESCE(@SOURCE,1)

IF @LINK is null OR @LINK = 0
BEGIN


	IF EXISTS (SELECT * FROM dbo.SAL_SFIN WHERE (RTRIM(LTRIM([name])) = @name OR RTRIM(LTRIM([code])) = @code) and  source = @SOURCE)
	BEGIN
		ROLLBACK
		RETURN 8
	END	

	INSERT INTO dbo.SAL_SFIN WITH (ROWLOCK) (CODE,[NAME],KBK,SOURCE,USER_ACC,DOP_KL,KAU,COMMENT,ENVD, ACC_ESN, LINK_LACC, USED, LINK_CH_SFIN,DATE_CHANGE)
		VALUES (@CODE,@NAME,@LINK_KBK,@SOURCE,@USER_ACC,@LINK_DOP_KL,@LINK_KAU,@COMMENT,@ENVD, @ACC_ESN, @LINK_LACC, @USED, @LINK_CH_SFIN,@DATE_CHANGE)

	SELECT @varKSERROR = @@ERROR, @LINK = @@IDENTITY
	IF @varKSERROR <> 0
	BEGIN

		ROLLBACK
		RETURN 7
	END
END

ELSE
BEGIN
	UPDATE dbo.SAL_SFIN SET CODE=@CODE, [NAME]=@NAME, KBK=@LINK_KBK, [SOURCE]=@SOURCE, USER_ACC=@USER_ACC, 
		DOP_KL=@LINK_DOP_KL, KAU=@LINK_KAU, COMMENT=@COMMENT, ENVD=@ENVD , ACC_ESN = @ACC_ESN, 
		LINK_LACC = @LINK_LACC, USED = @USED, LINK_CH_SFIN = @LINK_CH_SFIN, DATE_CHANGE = @DATE_CHANGE
	WHERE link=@LINK

	SELECT @varKSERROR = @@ERROR 
	IF @varKSERROR <> 0
	BEGIN

		ROLLBACK
		RETURN 7
	END
	IF @varKSRowCount = 0
	BEGIN

		ROLLBACK
		RETURN 2
	END
END

declare @ObjectLink int, @EventText varchar(254)
SELECT @ObjectLink = link FROM s_objects WHERE code='SALARY_SRC_FIN'
SET @EventText = 'Источники финансирования' +  RTRIM(@Name)
EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @EventText, @ObjectLink, 'SALARY_SRC_FIN', @LINK

IF @varKSERROR <> 0
	RETURN @varKSERROR

IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0







GO


GRANT EXECUTE ON dbo.[SA_SFIN_SAVE] TO PUBLIC

GO




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

GO
CREATE   PROCEDURE [dbo].[SA_EMPL_SFIN_EKR]
	@MODE TINYINT, -- 1 - зарплата, 2 - аванс, 3 - межрасч
	@YAR INT,
	@MON INT,	
	@LINK_SFIN INT = NULL, -- заданный источник или по всем
	@LINK_EKR INT = NULL, -- заданный ЭКР или по всем
	@DEP_LINK INT = NULL,
	@varKScBufferCode varchar(20) = null
AS

--Временная таблица для хранения отбора записей справочника
CREATE TABLE #DICT_RECORDS (LINK INT)
CREATE INDEX #TMP_IDX_DICT_RECORDS ON #DICT_RECORDS (LINK)

INSERT INTO #DICT_RECORDS (LINK)
SELECT LINK FROM dbo.Buffer B WHERE RTRIM(LTRIM(B.ID)) = RTRIM(LTRIM(@varKScBufferCode))

IF @DEP_LINK IS NULL
	EXEC DBO.XD_WHATS_ZB @DEP_LINK OUTPUT
	
DECLARE @DATE DATETIME	
SET @DATE = dbo.ConvertDMY2Date(1,@MON,@YAR)
SET @DATE = dbo.DateEndOfMonth(@DATE)

DECLARE @LINK_211EKR INT
SET @LINK_211EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '211')

IF @MODE = 2 -- аванс
BEGIN

	declare @VEDOM_OPTIONS_AVANCE_SUM   tinyint --- Учтем настройку "Аванс суммой"
	Set @VEDOM_OPTIONS_AVANCE_SUM  = dbo.SA_GET_OPTION_BY_CODE('VEDOM_OPTIONS_AVANCE_SUM')

	IF @VEDOM_OPTIONS_AVANCE_SUM = 1
		SELECT DISTINCT
			LINK_EMPL = D.EMPL_LINK, 
			LINK_SFIN = ISNULL(@LINK_SFIN,D.LINK_KBK),
			CODE_SFIN = F.CODE,
			LINK_EKR = ISNULL(@LINK_EKR,@LINK_211EKR),
			CODE_EKR = K.CODE
		FROM
			DBO.EMPL E
			INNER JOIN DBO.SA_EMPLS_INFO(@DATE, DEFAULT) D ON E.LINK = D.EMPL_LINK
			INNER JOIN DBO.KOSGU K ON ISNULL(@LINK_EKR,@LINK_211EKR) = K.LINK 	
			INNER JOIN DBO.SAL_SFIN F ON ISNULL(@LINK_SFIN,D.LINK_KBK) = F.LINK
		WHERE
			E.DEP_LINK = @DEP_LINK
			AND @MODE = 2
			AND @VEDOM_OPTIONS_AVANCE_SUM = 1
			AND (@varKScBufferCode IS NULL OR EXISTS (SELECT * FROM #DICT_RECORDS R WHERE R.LINK = E.LINK))
		ORDER BY
			D.EMPL_LINK,
			F.CODE,
			K.CODE	
	ELSE
		SELECT DISTINCT--Аванс процентом: Список источников и ЭКР из постоянных начислений
			LINK_EMPL = D.LINK_EMPL, 
			LINK_SFIN = ISNULL(@LINK_SFIN,D.LINK_KBK),
			CODE_SFIN = F.CODE,
			LINK_EKR = ISNULL(@LINK_EKR,P.LINK_EKR),
			CODE_EKR = K.CODE
		FROM
			dbo.sa_all_pays_all(DEFAULT,@DATE,@varKScBufferCode,@DEP_LINK,DEFAULT) D
			INNER JOIN dbo.PAYS P ON D.LINK_PAYS = P.LINK
			INNER JOIN DBO.KOSGU K ON ISNULL(@LINK_EKR,P.LINK_EKR) = K.LINK 	
			INNER JOIN DBO.SAL_SFIN F ON ISNULL(@LINK_SFIN,D.LINK_KBK) = F.LINK
		WHERE
			@MODE = 2
			AND @VEDOM_OPTIONS_AVANCE_SUM = 0
		ORDER BY
			D.LINK_EMPL,
			F.CODE,
			K.CODE		
END	

IF @MODE = 1 -- зарплата
	
	SELECT DISTINCT 
		LINK_EMPL = J.LINK_EMPL, 
		LINK_SFIN = J.LINK_VKR, 
		CODE_SFIN = F.CODE,
		LINK_EKR = K.LINK,
		CODE_EKR = K.CODE
	FROM 
		dbo.CALCULATE_JURNAL J
		INNER JOIN dbo.PAYS P ON P.LINK = J.LINK_PAYS
		INNER JOIN DBO.SAL_SFIN F ON J.LINK_VKR = F.LINK
		CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = 'R211') R211
		CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = '211') T211		
		INNER JOIN DBO.KOSGU K ON (CASE WHEN R211.LINK = J.LINK_EKR THEN T211.LINK ELSE J.LINK_EKR END) = K.LINK 
	WHERE
		LINK_DEP = @DEP_LINK
		AND (@varKScBufferCode IS NULL OR EXISTS (SELECT * FROM #DICT_RECORDS R WHERE R.LINK = J.LINK_EMPL))
		AND YEAR(J.PERIOD_BEGIN) = @YAR
		AND MONTH(J.PERIOD_BEGIN) <= @MON
		AND (@LINK_SFIN IS NULL OR J.LINK_VKR = @LINK_SFIN)
		AND (@LINK_EKR IS NULL OR K.LINK = @LINK_EKR)
		AND J.LINK_EMPL IS NOT NULL
		AND @MODE IN (1,3)
		AND P.[OBJECT] IN (1,2)	


IF @MODE = 3 -- межрасчётная выплата
		
	SELECT DISTINCT 
		LINK_EMPL = J.LINK_EMPL, 
		LINK_SFIN = J.LINK_VKR, 
		CODE_SFIN = F.CODE,
		LINK_EKR = K.LINK,
		CODE_EKR = K.CODE
	FROM 
		dbo.CALCULATE_JURNAL J
		INNER JOIN dbo.PAYS P ON P.LINK = J.LINK_PAYS
		INNER JOIN DBO.SAL_SFIN F ON J.LINK_VKR = F.LINK
		CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = 'R211') R211
		CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = '211') T211		
		INNER JOIN DBO.KOSGU K ON (CASE WHEN R211.LINK = J.LINK_EKR THEN T211.LINK ELSE J.LINK_EKR END) = K.LINK
	WHERE
		LINK_DEP = @DEP_LINK
		AND (@varKScBufferCode IS NULL OR EXISTS (SELECT * FROM #DICT_RECORDS R WHERE R.LINK = J.LINK_EMPL))
		AND YEAR(J.PERIOD_BEGIN) = @YAR
		AND MONTH(J.PERIOD_BEGIN) <= @MON
		AND (@LINK_SFIN IS NULL OR J.LINK_VKR = @LINK_SFIN)
		AND (@LINK_EKR IS NULL OR K.LINK = @LINK_EKR)
		AND J.LINK_EMPL IS NOT NULL
		AND @MODE IN (1,3)
		AND P.[OBJECT] IN (1,2)	
	UNION 
		SELECT DISTINCT
			LINK_EMPL = D.EMPL_LINK, 
			LINK_SFIN = ISNULL(@LINK_SFIN,D.LINK_KBK),
			CODE_SFIN = F.CODE,
			LINK_EKR = ISNULL(@LINK_EKR,@LINK_211EKR),
			CODE_EKR = K.CODE
		FROM
			DBO.EMPL E
			INNER JOIN DBO.SA_EMPLS_INFO(@DATE, DEFAULT) D ON E.LINK = D.EMPL_LINK
			INNER JOIN DBO.SAL_SFIN F ON ISNULL(@LINK_SFIN,D.LINK_KBK) = F.LINK
			INNER JOIN DBO.KOSGU K ON ISNULL(@LINK_EKR,@LINK_211EKR) = K.LINK 				
		WHERE
			E.DEP_LINK = @DEP_LINK
			AND (@varKScBufferCode IS NULL OR EXISTS (SELECT * FROM #DICT_RECORDS R WHERE R.LINK = E.LINK))		

--Завершение
DROP TABLE #DICT_RECORDS

GO


GRANT EXECUTE ON dbo.[SA_EMPL_SFIN_EKR] TO PUBLIC

GO


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

GO

/*
© Кейсистемс (Keysystems), 2005
Выбор сумм по договору по кварталам с группировкой по КБК
*/

CREATE    PROCEDURE DBO.FS_SUMM_BY_QURT
	@varKSDog_link int
AS
BEGIN

CREATE TABLE #Dog_Sum
([KBK] varchar(30),
 [Sum1]	numeric(19,2),
 [Sum2]	numeric(19,2),
 [Sum3]	numeric(19,2),
 [Sum4]	numeric(19,2)) 

INSERT INTO #Dog_Sum
Select KBK = ltrim(rtrim(vkr_code)) + '.' + ekr_code, Sum1 = p1+p2+p3, Sum2 = p4+p5+p6, Sum3 = p7+p8+p9,  Sum4 = p10+p11+p12 from finans_contract_table where link_up = @varKSDog_link

Select KBK, Sum1 = Sum(Sum1), Sum2 =  Sum(Sum2),  Sum3 =Sum(Sum3),  Sum4 = Sum(Sum4) from #Dog_Sum group by KBK
DROP TABLE #Dog_Sum
RETURN 1
END


GO


GRANT EXECUTE ON dbo.[FS_SUMM_BY_QURT] TO PUBLIC

GO



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

GO

CREATE  PROCEDURE [dbo].[SA_CREATE_RKO_BY_VEDOM]
			@LINK_RKO INT OUTPUT,
			@LINK_VEDOM INT
AS 
/*
Формирование РКО по ведомости на выплату штатным и внештатным сотрудникам
*/

---
Set @LINK_RKO = 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')
							AND
							LINK_vedom = @LINK_VEDOM),0)

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

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

---
DECLARE 
	@NUM_RKO 		VARCHAR(25),
	@NUM_VEDOM		VARCHAR(20),
	@DATE_VEDOM  		datetime,
	@DATE_BUH_DOC		datetime,
	@RUK			VARCHAR(254),
	@KAS			VARCHAR(254),
	@BUH			VARCHAR(254),
	@DEP_LINK		INT,
	@EMP_LINK		INT,
	@Osnovanie 		VARCHAR(254),
	@AddText 		VARCHAR(254),
	@LINK_PAY 		INT,
	@TYP_PAYMENT 		TINYINT,
	@MONTH_BASE 		INT,
	@YEAR_BASE 		INT,
	@KD_FULL_CODE_ACC VARCHAR(13)

DECLARE @varKStrancount INT, @varKSERROR as INT

-- данные из ведомости
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,
	@DEP_LINK=LINK_DEP,
	@EMP_LINK=REF_EMPL,
	@MONTH_BASE = MONTH_BASE,
	@YEAR_BASE = YEAR_BASE,
	@TYP_PAYMENT = TYP_PAYMENT,
	@AddText = 'Ведомость №' + RTRIM(LTRIM(COALESCE(NUMBER,''))) + ' от ' + COALESCE(convert(VARCHAR(10),[DATE], 104),''),
	@LINK_PAY = REF_PAY
FROM 	
	(
	SELECT [DATE], MONTH_BASE, YEAR_BASE, NUMBER, LINK_DEP, REF_EMPL, TYP_PAYMENT, REF_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 FROM dbo.DOCUMENTS_DED_PR_DGH V2 WHERE V2.LINK = @LINK_VEDOM
	) V

---
Declare @KD_CODE_ACC VARCHAR(6), @PAYS_CODE VARCHAR(30)
Select TOP 1 @KD_CODE_ACC = CODE_ACC, @PAYS_CODE = CODE from dbo.Pays where Link = @LINK_PAY

IF REPLACE(LTRIM(RTRIM(ISNULL(@KD_CODE_ACC,''))),'.','') = '' BEGIN
	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформирован РКО',
		'Не указан счет кредита в настройках вида удержания с кодом '+ ISNULL(LTRIM(RTRIM(@PAYS_CODE)),''),
		'Укажите в настройках удержания '+ISNULL(LTRIM(RTRIM(@PAYS_CODE)),'')+' счет кредита.',
		'SALARY'
	RETURN 0
END	

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

-- Определяем руководителя кассира буха
SELECT @RUK=Face_Name FROM DICTIONARY_OTV_FACE 
WHERE dep_link=@DEP_LINK and [name] = 'Руководитель'

SELECT @BUH=Face_Name FROM DICTIONARY_OTV_FACE 
WHERE dep_link=@DEP_LINK and [name]='Главный бухгалтер'

SELECT @KAS=Face_Name FROM DICTIONARY_OTV_FACE 
WHERE dep_link=@DEP_LINK and [name]= 'Кассир'

DECLARE @empl_pasport VARCHAR(254)
exec dbo.X_DOCUMENT_RKO_PASSPORT @EMP_LINK, @empl_pasport OUTPUT
set @empl_pasport = RTRIM(LTRIM(COALESCE(@empl_pasport,'')))


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	@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 'Не сформированы РКО по документу ' + @AddText,
		'Программа формирует дату проводки, равную дате ведомости. Но эта дата не попадает в период редактирования!',
		'Отключите в общих настройках по зарплате опцию "В бух. документе автоматически ставить дату" проводки или измените период редактирования.',
		'SALARY'
	RETURN 0
END

DECLARE 
	@Cur 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(30), 
	@Fin_Source CHAR(1),
	@LINK_EKR	INT,
	@ACC_CODE VARCHAR(30)

DECLARE @CUR_F CURSOR

--Формируем расходники для каждого КБК отдельно
SET @CUR_F = CURSOR FORWARD_ONLY
FOR 
	SELECT F.KBK 
	FROM dbo.CALCULATE_JURNAL JC INNER JOIN dbo.SAL_SFIN F ON F.LINK = JC.LINK_VKR
	WHERE JC.LINK_DOC = @LINK_VEDOM
	GROUP BY F.KBK
	HAVING SUM(JC.SUMMA) <> 0
	ORDER BY F.KBK
OPEN @CUR_F
FETCH NEXT FROM @CUR_F INTO @LINK_KBK
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
		--------------------

		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((SELECT ' по КБК ' + KBK.[CODE] FROM dbo.KL_KBK KBK WHERE KBK.LINK = @LINK_KBK),''))) 
			 + ' Ведомость №' + RTRIM(LTRIM(COALESCE(@NUM_VEDOM,''))) + ' от ' + COALESCE(convert(VARCHAR(10),@DATE_VEDOM, 104),'')

		IF COALESCE(@ACC_302,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	

		Set @ORDER = 0

		-- определим максимальный номер RКО
		exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'DOCUMENTS_RKO', @NUM_RKO output, @DEP_LINK

		-- Сохраняем РКО 
		SET @LINK_RKO = NULL
		exec dbo.X_SAVE_DOCUMENTS_RKO @LINK_RKO OUT, @NUM_RKO, @DATE_VEDOM, @DATE_PROV, 0, '', @DEP_LINK,
					NULL, @EMP_LINK, 1, NULL, NULL, @Osnovanie, NULL, @RUK, @BUH,
					@KAS, @empl_pasport, NULL, 0,''

		INSERT INTO dbo.sdoc_vedom_rko (LINK_VEDOM, LINK_RKO, COMMENT) VALUES(@LINK_VEDOM, @LINK_RKO, @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,
			COALESCE(CAST (F.SOURCE as CHAR(1)),''),
			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 ISNULL(F.KBK,0) = ISNULL(@LINK_KBK,0)
		GROUP BY 
			JC.LINK_EKR, JC.LINK_PAYS, F.KBK, F.KAU, F.DOP_KL, F.USER_ACC, F.CODE, F.SOURCE
		HAVING 
			SUM(JC.SUMMA) <> 0
		ORDER BY
			F.SOURCE
		
		--------------------
		OPEN @Cur
		FETCH NEXT FROM @Cur INTO @LINK_EKR, @LINK_KAU, @LINK_DOP_KL, @USER_ACC, @CODE_SFIN, @Fin_Source, @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_RKO, NULL, @AddText, 1
		
				Set @ORDER = @ORDER + 1
				
				IF RTRIM(LTRIM(COALESCE(@USER_ACC,''))) <> ''
					Set @Account1 = (SELECT TOP 1 link FROM dbo.S_ACCOUNTS WHERE cSource = @Fin_Source and cSinth = RTRIM(LTRIM(@ACC_302)) 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(@ACC_302)) 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(@ACC_302)) + '.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 = @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 'Не сформирован РКО ' + @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 'Не сформирован РКО ' + @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),
							'Вероятно в настройках удержания ' + COALESCE(LTRIM(RTRIM(@PAYS_CODE)),'') + ' указан некорректный счет кредита или в общих настройках по зарплате указан неправильно счет для начисления на оплату труда.',
							'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, @DEP_LINK, 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, @DEP_LINK, NULL, NULL, NULL, NULL, @LINK_KAU, NULL, NULL, NULL, NULL, @LINK_DOP_KL, NULL, @SGU
				END
				END
		
			END
			FETCH NEXT FROM @Cur INTO @LINK_EKR, @LINK_KAU, @LINK_DOP_KL, @USER_ACC, @CODE_SFIN, @Fin_Source, @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_RKO 
		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_RKO

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


GO


GRANT EXECUTE ON dbo.[SA_CREATE_RKO_BY_VEDOM] TO PUBLIC

GO

GO

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

GO
CREATE   PROCEDURE [dbo].SD_EMPL_INCOM_VKR
	@VARKSNMODE	SMALLINT	= 0, 
	@VARKSNMONTH INT		= 0,
	@VARKSNYEAR	INT		= 0,
	@DEP_LINK INT = NULL,
	@DO_EKR TINYINT = 0 -- вразрезе ЭКР
AS

IF @DEP_LINK IS NULL
	EXEC DBO.XD_WHATS_ZB @DEP_LINK OUTPUT
	
DECLARE @LINK_211EKR INT, @LINK_R211EKR INT, @LINK_212EKR INT, @SHOW_212 TINYINT, @LINK_213EKR INT
		  
SET @LINK_211EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '211')
SET @LINK_R211EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = 'R211')
SET @LINK_212EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '212')
SET @LINK_213EKR = (SELECT TOP 1 LINK FROM dbo.KOSGU WHERE CODE = '213')
SET @SHOW_212 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_3')

DECLARE @ESN_213 INT --Начислять страховые взносы на доходы с 213 ЭКР                                                    
SET @ESN_213 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_5')

SELECT DISTINCT
	LINK= E.PERS_LINK,
	LINK_EMPL= E.LINK,
	TAB_NUM= E.TAB,
	[NAME_EMPL]= RTRIM(P.FM) + ' ' + SUBSTRING(RTRIM(P.IM),1,1) + '.' + SUBSTRING(RTRIM(P.OT),1,1) + '.', 
	[STATUS] = 1,
	NUM_STAKE = 1,	
	JC.LINK_VKR, 
	NAME_VKR = KBK.CODE,
	LINK_EKR = EKR.LINK,
	CODE_EKR = EKR.CODE
FROM
	DBO.PERSON P with (nolock)
	INNER JOIN DBO.EMPL E with (nolock) ON E.PERS_LINK = P.LINK AND E.DEP_LINK = COALESCE(@DEP_LINK,E.DEP_LINK)
	--Заполняем сотрудником с последним приказом о приеме
	INNER JOIN (
		/*выбор последних линков сотрудников для статусов основной и внешний совместитель
		берется последний табельный, если увольнялся, затем заново принимался*/
		SELECT E.DEP_LINK, E.PERS_LINK, E.LINK, E.TAB, NUM = ROW_NUMBER () OVER (PARTITION BY E.DEP_LINK, E.PERS_LINK ORDER BY DATE_BEGIN DESC)
			FROM dbo.EMPL E INNER JOIN dbo.ITEM_MOVE IM ON E.LINK = IM.EMPL_LINK
				WHERE IM.ACTIVE = 1 AND IM.NEW_FACE=1 AND (IM.[STATUS]=1 OR IM.[STATUS]=3) AND DATE_BEGIN <= dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@VARKSNMONTH,@VARKSNYEAR))
		/*выбор линков сотрудников для статусов внутренний совместитель*/
		UNION ALL
		SELECT E.DEP_LINK, E.PERS_LINK, E.LINK, E.TAB, NUM = 1
			FROM dbo.EMPL E INNER JOIN dbo.ITEM_MOVE IM ON E.LINK = IM.EMPL_LINK
				WHERE IM.ACTIVE = 1 AND IM.NEW_FACE=1 AND IM.[STATUS]=2 AND DATE_BEGIN <= dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@VARKSNMONTH,@VARKSNYEAR))
		) T ON T.DEP_LINK = E.DEP_LINK AND E.LINK = T.LINK AND T.NUM = 1	
	INNER JOIN dbo.CALCULATE_JURNAL JC ON JC.LINK_EMPL = E.LINK
	INNER JOIN dbo.PAYS PS ON JC.LINK_PAYS = PS.LINK
	INNER JOIN DBO.SAL_SFIN KBK ON JC.LINK_VKR = KBK.LINK
	INNER JOIN DBO.KOSGU EKR ON 
		@SHOW_212 = 1 AND (EKR.LINK = JC.LINK_EKR OR (JC.LINK_EKR = @LINK_212EKR AND EKR.LINK = @LINK_211EKR)) --Источники с 212 ЭКР дублируем с 211 ЭКР --Временно до конца года
		OR 
		@SHOW_212 = 0 AND EKR.LINK = (CASE WHEN JC.LINK_EKR <> @LINK_212EKR THEN JC.LINK_EKR ELSE @LINK_211EKR END)	
		OR 
		@DO_EKR = 1 AND EKR.LINK = JC.LINK_EKR
WHERE
	E.DEP_LINK = @DEP_LINK
	AND
	PS.[OBJECT] IN (1,2)
	AND
	YEAR(JC.PERIOD_BEGIN) = @VARKSNYEAR
	AND
	JC.SUMMA<>0
	AND
	(
		(MONTH(JC.PERIOD_BEGIN) <= @VARKSNMONTH AND @VARKSNMODE <> 0)
		OR
		(MONTH(JC.PERIOD_BEGIN) = @VARKSNMONTH AND @VARKSNMODE = 0)
	)
	AND
	(@ESN_213 = 1 OR @ESN_213 = 0 AND EKR.LINK <> @LINK_213EKR)
ORDER BY
	4,6,8

GO


GRANT EXECUTE ON dbo.[SD_EMPL_INCOM_VKR] TO PUBLIC

GO

GO

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

GO



CREATE PROCEDURE dbo.SA_REP_VACATION_OR_TRAVEL_REESTR ( @Type varchar(20), @DATE1 datetime, @DATE2 datetime, @DEP_LINK INT = NULL , @OPTION INT = 1) 
AS

DECLARE @SQL Nvarchar(4000)

IF @DEP_LINK IS NULL
	EXEC dbo.xd_whats_zb @DEP_LINK OUTPUT

SET @SQL =
N'
SELECT  
	TYPE = @Type,
	REF_TYP = D.type_link, 
	name_typ = D.type_name, 
	tab_numer = D.tab_num,
	NAME_EMPL = D.FIO, 
	D.number,
	D.[date],
	date1 = D.date_begin,
	date2 = D.date_end,
	isnull(''№''+rtrim(C.NUMBER)+'' от ''+convert(varchar(10),C.[DATE],104),'''') as [Calc],
	C.SUMMA,
	C.DAYS,
	C.HOURS 
FROM ' 
	+ RTRIM(@Type) + ' D '
	+ (case when @Type <> 'TRAVEL' then '
	LEFT JOIN (SELECT C0.REF_ARHE, C0.NUMBER, C0.[DATE], SUM(T.SUMMA) AS SUMMA, SUM(T.DAYS) AS DAYS, SUM(T.HOURS) AS HOURS
			FROM DOCUMENTS_ADD_FUR C0 INNER join SDOC_AVAC_TABLE1 T ON T.LINK_UP = C0.LINK
				GROUP BY C0.REF_ARHE, C0.NUMBER, C0.[DATE]) C ON C.REF_ARHE = D.link '
	else '
	LEFT JOIN (SELECT C0.REF_ARHE, C0.NUMBER, C0.[DATE], SUM(T.SUMMA) AS SUMMA, SUM(T.DAYS) AS DAYS, SUM(T.HOURS) AS HOURS
			FROM DOCUMENTS_CALC_TRAVEL C0 INNER join SDOC_AVAC_TABLE1 T ON T.LINK_UP = C0.LINK
				GROUP BY C0.REF_ARHE, C0.NUMBER, C0.[DATE]) C ON C.REF_ARHE = D.link '
	end) + '
WHERE
	D.dep_link = @DEP_LINK
	AND '
		+ 
		CASE @OPTION 
		WHEN 1 THEN
			' D.[date] BETWEEN dbo.DateBeginOfDay(@DATE1) AND dbo.DateEndOfDay(@DATE2) '
		WHEN 2 THEN
			' D.[date_begin] BETWEEN dbo.DateBeginOfDay(@DATE1) AND dbo.DateEndOfDay(@DATE2) '
		WHEN 3 THEN
			' D.[date_begin] <= dbo.DateEndOfDay(@DATE2) AND D.[date_end] >= dbo.DateBeginOfDay(@DATE1) '
		END	
	+ ' AND
	active = 1
ORDER BY
	D.type_link, D.tab_num, D.[date]  
'
print @SQL
EXEC SP_EXECUTESQL @SQL, N'@Type varchar(20), @DEP_LINK INT, @DATE1 datetime, @DATE2 datetime', 
		@Type=@Type, @DEP_LINK = @DEP_LINK, @DATE1 = @DATE1, @DATE2 = @DATE2

GO


GRANT EXECUTE ON dbo.[SA_REP_VACATION_OR_TRAVEL_REESTR] TO PUBLIC

GO

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

GO

CREATE PROCEDURE [dbo].[SD_U_NDFL_FILL]
	@varKSlinkEmpl	 int,  
	@varKSRef_Pay  int, 	 
	@varKSDate datetime, 	 
	@varKSLinkVKR int,
	@varKSLinkEKR int,	
	@varKSfl int = 0

AS 
SET NOCOUNT ON
DECLARE @varKSMonth int, 
	  @varKSYear int, 
	  @varKSLINK_FACE int, 
	  @varKSPred_Mesto_Rab numeric(15,2), 
	  @varKSFlagD int,
	  @Status int	-->>NEW

IF @varKSfl>0
	SET @varKSfl = 1

DECLARE @NDFL_OPT8 TINYINT --Разрешить отрицательные суммы налога
SET @NDFL_OPT8 = dbo.sa_get_option_by_code('NDFL_OPT8')

SET @varKSMonth= month(@varKSDate)
SET @varKSYear = year(@varKSDate)

declare @DEP_LINK int
SELECT @DEP_LINK = DEP_LINK, @varKSLINK_FACE = PERS_LINK FROM DBO.EMPL WHERE LINK = @varKSlinkEmpl

DECLARE @Link211EKR int
Set @Link211EKR = ISNULL((SELECT TOP 1 LINK FROM KOSGU WHERE CODE = '211'),0)

if @varKSfl = 1
	Select [Организация] = [NAME] from dbo.DEPARTMENTS where link = @DEP_LINK

Select @Status= [STATUS] from dbo.ITEM_MOVE where ACTIVE = 1 and EMPL_LINK = @varKSlinkEmpl	-->>NEW

SET @varKSFlagD = 0

DECLARE @DIS_DATE DATETIME
SET @DIS_DATE = COALESCE((SELECT TOP 1 IDF.DIS_DATE FROM DBO.ITEM_DIS_FACE IDF with (nolock) WHERE IDF.EMPL_LINK = @varKSlinkEmpl AND IDF.ACTIVE=1),'29990101')

SET @varKSPred_Mesto_Rab = 0
IF YEAR(dbo.kd_DateBeginWork(@varKSlinkEmpl,@varKSDate)) = @varKSYear
BEGIN

	SET @varKSPred_Mesto_Rab =(SELECT ISNULL(SUM(SUMMA_TYP_INCOMS),0) FROM dbo.SD_EMPL_PREV_DOHOD WHERE LINK_EMPL = @varKSlinkEmpl)
			- (SELECT ISNULL(SUM(SUMMA_DED),0) FROM dbo.SD_EMPL_PREV_DED WHERE LINK_EMPL = @varKSlinkEmpl and 
					LINK_DED IN (SELECT distinct REF_DEDUCT FROM DICTIONARY_TYP_INCOMS where REF_DEDUCT is not null) )
	IF @varKSPred_Mesto_Rab IS null or @varKSPred_Mesto_Rab < 0
		SET @varKSPred_Mesto_Rab = 0
	SET @varKSFlagD = 1
END


IF @varKSfl = 1 
	SELECT Case @Status when 1 then 'Основной сотрудник' when 2 then 'Внутренний совместитель' else 'Внешний совместитель' end + 
	': '+rtrim(TAB)+ ' ' +rtrim(dbo.sd_GetEmplName(LINK))+  ', месяц ' + rtrim(convert(varchar(100),@varKSMonth))+ 
			 ', год ' +rtrim( convert(varchar(100),@varKSYear )) as 'Исходные данные'  FROM dbo.EMPL WHERE LINK = @varKSlinkEmpl   
IF  @varKSfl = 1 
	SELECT 'Совокупный доход: '+ rtrim(isnull(convert(varchar(100),(select sum(summa_TYP_INCOMS) from dbo.SD_EMPL_PREV_DOHOD where link_empl =@varKSlinkEmpl)),'0')) + ' , предоставленные вычеты: '+
	 rtrim( isnull( convert(varchar(100),(select sum(summa_ded) from dbo.SD_EMPL_PREV_DED where link_empl =@varKSlinkEmpl and LINK_DED NOT IN (SELECT distinct REF_DEDUCT FROM DICTIONARY_TYP_INCOMS where REF_DEDUCT is not null) )),'0'))
	+ ' , предоставлены скидки: '+
	 rtrim( isnull( convert(varchar(100),(select sum(summa_ded) from dbo.SD_EMPL_PREV_DED where link_empl =@varKSlinkEmpl and LINK_DED IN (SELECT distinct REF_DEDUCT FROM DICTIONARY_TYP_INCOMS where REF_DEDUCT is not null) )),'0'))  as 'Данные с предыдущего места работы'


/*Доходы*/
Declare @isPrevPreiod tinyint
--Суммы начислений включать в базу расчета в том месяце, в котором он был начислен.                   
Set @isPrevPreiod = dbo.sa_get_option_by_code('NDFL_OPT6')
Set @isPrevPreiod = 1 - ISNULL(@isPrevPreiod,0)

Declare @SJC table (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)

Insert into @SJC (link_empl, link_pays, link_vkr, link_ekr, typ_per, typ_oper, summa, period_begin, date1)
Select 
	JC.LINK_EMPL, P.LINK, link_vkr, S.LINK, 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_PREMIUM' and d.code <> 'DOCUMENTS_ADD_PERCENT'
					then JC.DATE_BEGIN else JC.period_begin 
				end) 
			end),
	JC.DATE_BEGIN
from 
	dbo.CALCULATE_JURNAL JC 
	INNER JOIN dbo.EMPL E ON JC.LINK_EMPL = E.LINK
	INNER JOIN dbo.PAYS P ON JC.LINK_PAYS = P.LINK
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = 'R211') R211
	CROSS APPLY (SELECT LINK FROM dbo.KOSGU T WHERE T.CODE = '211') T211
	INNER JOIN dbo.KOSGU S ON S.LINK = (CASE WHEN R211.LINK = ISNULL(JC.LINK_EKR,P.LINK_EKR) THEN T211.LINK ELSE ISNULL(JC.LINK_EKR,P.LINK_EKR) END)	
	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
	P.OBJECT = 1
	AND
	P.LINK in (Select TAX_LINK from dbo.group_tax(@varKSRef_Pay)) 
	AND (
			@isPrevPreiod = 0 and @varKSMonth >= month(JC.PERIOD_BEGIN) and @varKSYear = year(JC.PERIOD_BEGIN)
		or 
			@isPrevPreiod = 1 
			and (@varKSMonth >= month(JC.DATE_BEGIN) or @varKSMonth >= month(JC.PERIOD_BEGIN) )
			and (@varKSYear = year(JC.DATE_BEGIN) or @varKSYear = year(JC.PERIOD_BEGIN) )
		)
	AND  
		(	-->>NEW
		@Status <> 1 AND JC.LINK_EMPL = @varKSlinkEmpl /*Если не основной сотрудник, то доход по своему табельному номеру*/
		or
		@Status = 1 AND E.PERS_LINK = @varKSLINK_FACE /*Если основной сотрудник, то доход по всем табельным номерам*/
		)	
	AND JC.LINK_DEP = @DEP_LINK 
	

DECLARE @varKSVal TABLE 
([MONTH] 		[int],
 [EMPL_SUMMA] 		[numeric](19, 2),
 [SUMMA] 		[numeric](19, 2),
 [EMPL_SUMMA_VKR]	[numeric](19, 2),
 [SUMMA_VKR]		[numeric](19, 2),
 [SUMMA_M]		[numeric](19, 2),
 [SUMMA_M_211]  [numeric](19, 2), --для расчёта коэффициента при предоставлении вычета только по 211 ЭКР
 [SUMMA_M_VKR]		[numeric](19, 2)
 --[SUMMA_M_VKR1]		[numeric](19, 2)
)

INSERT INTO @varKSVal([MONTH],[SUMMA],[EMPL_SUMMA], [SUMMA_VKR], [EMPL_SUMMA_VKR],[SUMMA_M],[SUMMA_M_211],[SUMMA_M_VKR])--,[SUMMA_M_VKR1])
SELECT T.NUM AS [MONTH],  
		[SUMMA] = SUM(SJ.SUMMA), 
		[EMPL_SUMMA] = SUM(CASE WHEN SJ.LINK_EMPL = @varKSlinkEmpl THEN SJ.SUMMA ELSE 0 END),
		[SUMMA_VKR] = SUM(CASE WHEN SJ.LINK_VKR = @varKSLinkVKR   AND SJ.LINK_EKR = @varKSLinkEKR THEN SJ.SUMMA ELSE 0 END), 
		[EMPL_SUMMA_VKR] = SUM(CASE WHEN SJ.LINK_VKR = @varKSLinkVKR AND SJ.LINK_EMPL = @varKSlinkEmpl AND SJ.LINK_EKR = @varKSLinkEKR THEN SJ.SUMMA ELSE 0 END), 
		[SUMMA_M] = SUM(CASE WHEN Month(sj.period_begin) = T.NUM AND SJ.LINK_EMPL = @varKSlinkEmpl THEN SJ.SUMMA ELSE 0 END), 
		[SUMMA_M_211] = SUM(CASE WHEN Month(sj.period_begin) = T.NUM AND SJ.LINK_EMPL = @varKSlinkEmpl AND SJ.LINK_EKR = @Link211EKR THEN SJ.SUMMA ELSE 0 END), 
		[SUMMA_M_VKR] = SUM(CASE WHEN Month(sj.period_begin) =T.NUM AND SJ.LINK_VKR = @varKSLinkVKR AND SJ.LINK_EMPL = @varKSlinkEmpl AND SJ.LINK_EKR = @varKSLinkEKR THEN SJ.SUMMA ELSE 0 END)
--		[SUMMA_M_VKR1] = SUM(CASE WHEN Month(sj.period_begin) =T.NUM AND SJ.LINK_VKR = @varKSLinkVKR AND SJ.LINK_EMPL = @varKSlinkEmpl THEN SJ.SUMMA ELSE 0 END)
FROM dbo.MONTHS T, @SJC SJ
WHERE SJ.TYP_OPER = 1 AND T.NUM <= @varKSMonth
		AND T.NUM >= Month(sj.period_begin)
		AND  @varKSYear = Year(sj.period_begin)
GROUP BY  T.NUM

if @varKSfl = 1 
	select [month] as [Месяц], [summa] as [Сумма ФЛ с нач года ],summa_vkr as [Сумма ФЛ с нач года по ВКР], summa_m as [Сумма сотр за месяц], 
	summa_m_vkr as [Сумма сотр за месяц по ВКР]  from @varKSVal

/*Доходы для вычетов*/
DECLARE @varKSVal2 TABLE 
([MONTH] 		[int],
 [SUMMA] 		[numeric](19, 2),
 [EMPL_SUMMA] 		[numeric](19, 2),
 [SUMMA_VKR]		[numeric](19, 2),
 [EMPL_SUMMA_VKR]	[numeric](19, 2),
 [SUMMA_M]		[numeric](19, 2),
 [SUMMA_M_VKR]		[numeric](19, 2))


INSERT INTO @varKSVal2([MONTH],[SUMMA],[EMPL_SUMMA], [SUMMA_VKR], [EMPL_SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR])
SELECT T.NUM AS [MONTH],
		[SUMMA] = SUM(SJ.SUMMA),
		[EMPL_SUMMA] = SUM(CASE WHEN SJ.LINK_EMPL = @varKSlinkEmpl THEN SJ.SUMMA ELSE 0 END),
		[SUMMA_VKR] = SUM(CASE WHEN SJ.LINK_VKR = @varKSLinkVKR AND SJ.LINK_EKR = @varKSLinkEKR THEN SJ.SUMMA ELSE 0 END),
		[EMPL_SUMMA_VKR] = SUM(CASE WHEN SJ.LINK_VKR = @varKSLinkVKR AND (SJ.LINK_EMPL = @varKSlinkEmpl) AND SJ.LINK_EKR = @varKSLinkEKR THEN SJ.SUMMA ELSE 0 END), 
		[SUMMA_M] = SUM(CASE WHEN (CASE WHEN SJ.TYP_PER=1 THEN Month(sj.period_begin) ELSE MONTH(sj.DATE1) END)=T.num AND SJ.LINK_EMPL = @varKSlinkEmpl then sj.summa else 0 end),
		[SUMMA_M_VKR] = SUM(CASE WHEN ((CASE WHEN SJ.TYP_PER=1 THEN Month(sj.period_begin) ELSE MONTH(sj.DATE1) END)=T.num)
							AND sj.link_vkr = @varKSLinkVKR AND SJ.LINK_EMPL = @varKSlinkEmpl AND SJ.LINK_EKR = @varKSLinkEKR THEN SJ.SUMMA ELSE 0 END)
FROM dbo.MONTHS T, @SJC SJ
WHERE SJ.TYP_OPER = 1 
		AND T.NUM <= @varKSMonth AND
		T.NUM >=(CASE WHEN SJ.TYP_PER=1 THEN Month(sj.period_begin) ELSE MONTH(SJ.DATE1) END)
		AND @varKSYear =(case WHEN SJ.TYP_PER=1 THEN Year(sj.period_begin) ELSE YEAR(sj.DATE1) END)
GROUP BY  T.NUM

insert into @varKSVal2 ([MONTH],[SUMMA],[EMPL_SUMMA], [SUMMA_VKR], [EMPL_SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR])
select T.NUM, 0, 0, 0, 0, 0, 0  from dbo.MONTHS T where T.NUM < (Select min([month]) from @varKSVal2)

if @varKSfl = 1 
	select [month] as [Месяц], [summa] as [Сумма ФЛ с нач года], @varKSPred_Mesto_Rab as [Сумма ФЛ с предыдущего места работы], summa_vkr as [Сумма ФЛ с нач года по ВКР ], summa_m as [Сумма сотр за месяц], 
	summa_m_vkr as [Сумма сотр за месяц по ВКР]  from @varKSVal2 order by [month]

/*Какие бывают скидки*/
if @varKSfl=1 
   select code as [Код вычета], name as [Наименование вычета], SUMMA as [Сумма] from dbo.Salary_deductions(@varKSDate) WHERE TYPE = 5

/*
Если это не внешний совместитель, то Скидки и вычеты предоставляем только по основному табельному номеру
Если это внешний совместитель, предоставляем скидки
*/

/*Какие скидки у физ.лица*/
DECLARE @varKSTemp1 TABLE 
([NUM] 			[int],
 [REF_PAY]		[int],	
 [MP]		 	[numeric](19, 2),
 [MP_M]			[numeric](19, 2),
 [MP_M_VKR]		[numeric](19, 2),
 [PREDEL]		[numeric](19, 2))

--Расчет скидок
INSERT INTO @varKSTemp1 ([NUM],[REF_PAY],[MP],[MP_M],[MP_M_VKR],[PREDEL])
SELECT m.num,T1.REF_PAY,
	/*Годовая сумма дохода со скидкой по физ.лицу*/
	[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 = @varKSLinkVKR AND SJ.LINK_EKR = @varKSLinkEKR then (case when Month(sj.period_begin)<=m.num then SJ.summa else 0 end) else 0 end),
	[PREDEL] = T1.SUMMA -(case when @varKSFlagD = 1 then isnull((select sum(summa_ded) from dbo.SD_EMPL_PREV_DED where LINK_DED = T1.REF_PAY and  link_empl=@varKSlinkEmpl),0)  else 0 end) 
FROM 
	dbo.MONTHS M, @SJC SJ, dbo.Salary_deductions(@varKSDate) T1
WHERE  
	Year(sj.period_begin) = @varKSYear and m.num<=@varKSMonth AND T1.TYPE = 6 --Тип вычета "Скидка на материальную помощь"
	AND T1.REF_PAY = (select ref_deduct  from dbo.DICTIONARY_TYP_INCOMS where link = (select LINK_INC from dbo.PAYS where LINK = SJ.LINK_PAYS)) 
	AND @Status in (1 /*Основной*/, 3 /*Внешний совместитель*/) AND SJ.LINK_EMPL = @varKSlinkEmpl
GROUP BY m.num, T1.REF_PAY, T1.SUMMA

IF @varKSfl=1 
	select [num] as [Месяц], [Вычет] = (select name from diction where link = ref_pay), [mp] as [Сумма ФЛ с нач года], mp_m as [Сумма ФЛ за месяц], 
	mp_m_vkr as [Сумма ФЛ за месяц по ВКР], predel as [Предел]  from @varKSTemp1

DECLARE @varKSTemp2 TABLE 
([NUM] 			[int],
 [REF_PAY]		[int],	
 [MP]		 	[numeric](19, 2),
 [MP_M]			[numeric](19, 2),
 [MP_M_VKR]		[numeric](19, 2), [PREDEL]		[numeric](19, 2),
 [SALDO]		[numeric](19, 2),
 [KOEF] 		[numeric](19, 10))

INSERT INTO @varKSTemp2 ([NUM],[REF_PAY],[MP],[MP_M],[MP_M_VKR],[PREDEL],[SALDO],[KOEF])
SELECT T1.NUM,T1.REF_PAY,T1.MP,T1.MP_M,T1.MP_M_VKR,T1.PREDEL, 
	[SALDO] = (CASE WHEN PREDEL < 0 THEN 0 ELSE PREDEL END) - ISNULL((select sum(mp_m) from @varKSTemp1 T2 where T2.num < T1.num and T2.REF_PAY = T1.REF_PAY),0),
	[KOEF] =  (CASE WHEN MP_M = 0 THEN 0 ELSE MP_M_VKR/MP_M END)
FROM @varKSTemp1 T1

DECLARE @varKSTemp3 TABLE 
([NUM] 			[int],
 [REF_PAY]		[int],	
 [MP_M]			[numeric](19, 2),
 [MP_M_VKR]		[numeric](19, 2),
 [KOEF] 		[numeric](19, 10),
 [DED]			[numeric](19, 2)
  )

INSERT INTO @varKSTemp3 ([NUM],[REF_PAY],[MP_M],[MP_M_VKR],[KOEF],[DED])
SELECT [NUM],[REF_PAY],[MP_M],[MP_M_VKR],[KOEF], 
	   [DED] = 	case when SALDO < 0 then 
				- case when (CASE WHEN PREDEL < 0 THEN 0 ELSE PREDEL END) - ISNULL(MP,0) > 0	then
					(CASE WHEN PREDEL < 0 THEN 0 ELSE PREDEL END) - ISNULL(MP,0) 
					else 0
				end
			else
				(CASE WHEN MP_M > SALDO THEN SALDO ELSE MP_M END)
			end
FROM @varKSTemp2 

/*Очитстка от мусора: были рассчитаны вычеты и скидки с КБК, которые теперь в этом году больше не используются.
Врезультате эти суммы вычетов не очищаются при расчете и вылазят в 2НДФЛ*/
delete
from 
	dbo.SAL_DED_MONTH
where
	YEAR(dbo.SAL_DED_MONTH.DATE_DED) = YEAR(@varKSDate)
	and
	not exists (
		Select j.LINK 
		from dbo.calculate_jurnal j
		where 
			j.link_pays in (Select TAX_LINK from dbo.group_tax(@varKSRef_Pay)) 
			and YEAR(j.PERIOD_BEGIN) = YEAR(@varKSDate)
			and j.link_empl = dbo.SAL_DED_MONTH.link_empl and j.LINK_VKR = dbo.SAL_DED_MONTH.LINK_VKR
	)

/*Удалить все вычеты и скидки по сотруднику, чтобы затем вновь рассчитать их*/
DELETE FROM dbo.SAL_DED_MONTH
WHERE 
	LINK_EMPL = @varKSlinkEmpl 
	AND LINK_VKR = @varKSLinkVKR 
	AND ISNULL(LINK_EKR,@varKSLinkEKR) = @varKSLinkEKR 
	AND YEAR(DATE_DED) = YEAR(@varKSDate) 
	AND MONTH(DATE_DED) <= MONTH(@varKSDate) 

/*Заново рассчитать годовые скидки*/
INSERT INTO dbo.SAL_DED_MONTH (LINK_EMPL,REF_DED,SUMMA,DATE_DED,LINK_VKR,LINK_EKR,TYPE)
SELECT [LINK_EMPL] = @varKSlinkEmpl,
		 [REF_DED]   = T.REF_PAY,
		 [SUMMA] 	 = ISNULL(T.DED,0) * ISNULL(T.KOEF,1),
		 [DATE_DED]  = dbo.ConvertDMY2Date(1,t.num,year(@varKSDate)),
		 [LINK_VKR]	 = @varKSLinkVKR,
		 [LINK_EKR]	 = @varKSLinkEKR,
		 [TYPE] = 2
FROM @varKSTemp3 T WHERE T.MP_M_VKR <> 0 AND T.DED <> 0 

/* Скидки */

DECLARE @varKSTotTab TABLE
([MONTH] 		[int],
 [EMPL_SUMMA]		[numeric](19, 2), --
 [EMPL_SUMMA_VKR]	[numeric](19, 2), --
 [SUMMA_VKR]		[numeric](19, 2),
 [SUMMA_M]		[numeric](19, 2),
 [SUMMA_M_211]  [numeric](19, 2), --для расчёта коэффициента при предоставлении вычета только по 211 ЭКР
 [SUMMA_M_VKR]		[numeric](19, 2), --для каждого ЭКР, ВКР
 [DED_M_ALL] 		[numeric](19, 2),
 --[DED_M_ALL_211] 	[numeric](19, 2), --для расчёта коэффициента при предоставлении вычета только по 211 ЭКР
 [DED]			[numeric](19, 2),
 [DED_M]		[numeric](19, 2),
 [DED0]			[numeric](19, 2)
 ) 

/* Вычеты делятся между КБК пропорционально с помощью коэффициентов пропорциональности */
INSERT INTO @varKSTotTab([MONTH], [EMPL_SUMMA], [EMPL_SUMMA_VKR], [SUMMA_VKR],[SUMMA_M],[SUMMA_M_211],[SUMMA_M_VKR],[DED_M_ALL],[DED],[DED_M],DED0)
SELECT 	
		M.[NUM], 
		ISNULL(T1.EMPL_SUMMA,0), 
		ISNULL(T1.[EMPL_SUMMA_VKR],0), 
		ISNULL(T1.[SUMMA_VKR],0), 
		ISNULL(T1.[SUMMA_M],0),
		ISNULL(T1.[SUMMA_M_211],0),	 
		ISNULL(T1.[SUMMA_M_VKR],0),
	 	[DED_M_ALL] = ISNULL((SELECT SUM(T2.DED) FROM @varKSTemp3 T2 WHERE T2.NUM=M.[NUM]),0),
		[DED] 		= ISNULL((SELECT SUM(T2.DED * T2.KOEF) FROM @varKSTemp3 T2 WHERE T2.NUM <= M.[NUM]),0),
		[DED_M] 	= ISNULL((SELECT SUM(T2.DED * T2.KOEF) FROM @varKSTemp3 T2 WHERE T2.NUM = M.[NUM]),0),
		[DED0] 		= ISNULL((SELECT SUM(T2.DED) FROM @varKSTemp3 T2 WHERE T2.NUM <= M.[NUM]),0)
FROM  dbo.months M LEFT JOIN @varKSVal T1 on M.num = T1.[MONTH] 
WHERE M.NUM <= @varKSMonth
GROUP BY M.[NUM], T1.[EMPL_SUMMA], T1.[EMPL_SUMMA_VKR], T1.SUMMA_VKR, T1.SUMMA_M_VKR, T1.SUMMA_M, T1.SUMMA_M_211

IF @varKSfl=1 
select [month] as [Месяц],summa_vkr as [Сумма ФЛ с нач года по ВКР], summa_m as [Сумма сотр за месяц], 
	summa_m_vkr as [Сумма за месяц по ВКР], ded_m_all as [Скидки всего], ded as [Скидки всего по ВКР], ded_m as [Скидки за месяц по ВКР]  from @varKSTotTab

DECLARE @varKSTT TABLE
([REF_PAY] 	[int],
 [PREDEL]	[numeric](19, 2),
 [SUMMA]		[numeric](19, 2),
 [MONTHEND]	[int])

--- Вычеты и скидки: Определение достижения предела
INSERT INTO @varKSTT ([REF_PAY],[PREDEL],[SUMMA],[MONTHEND])
SELECT TD.REF_PAY,TD.PREDEL,TD.SUMMA, 
		[MonthEnd] =  (SELECT TOP 1 T1.[MONTH] FROM  @varKSVal2 T1 
 							WHERE (SUMMA+ISNULL(@varKSPred_Mesto_Rab,0) - ISNULL((select sum(ded) from @varKSTemp3 where num<=T1.[MONTH]),0))
							<(CASE WHEN TD.PREDEL = 0 THEN 999999999999 ELSE TD.PREDEL END)
							ORDER BY T1.[MONTH] DESC)
FROM 
	dbo.Salary_deductions(@varKSDate ) as TD where TYPE = 1

DECLARE @varKSTotal TABLE
( link int not null IDENTITY(1,1),
 [REF_PAY] 	[int],
 [MONTH_BEGIN]	[int],
 [MONTH_END]	[int],		
 [SUMMA]	[numeric](19, 2),
[SUMMA_V] numeric(18,2), [SUMMA_D] numeric(18,2), [Ostatok_V] numeric(18,2)-- Для определения факт вычетов
)

--Предоставление стандартных вычетов
--'Всегда,При наличии любого дохода за месяц,При наличии только положительного дохода за месяц'
declare @NDFL_OPT5 tinyint
SET @NDFL_OPT5 =  ISNULL((SELECT top 1 CONVERT(INT,VALUE) FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'NDFL_OPT5')),1)

INSERT INTO @varKSTotal ([REF_PAY],[MONTH_BEGIN],[MONTH_END],[SUMMA],[SUMMA_V],[SUMMA_D])
SELECT 		
	[REF_PAY] 		= TT.REF_PAY, 
	[MONTH_BEGIN]	= M.[NUM],--SDE.MONTH_BEGIN,
	[MONTH_END] 	= M.[NUM],--(CASE WHEN TT.MonthEnd> SDE.MONTH_END THEN SDE.MONTH_END ELSE TT.MonthEnd END),
	[SUMMA] 		= TT.SUMMA,
	[SUMMA_V]		= TT.SUMMA,	-- Для определения факт вычетов
	[SUMMA_D]		= ISNULL(D.[summa_m],0)	-- Для определения факт вычетов
				- ISNULL((select sum(ded) from @varKSTemp3 where num = M.[NUM]),0)
FROM 
	@varKSTT TT
	INNER JOIN (SELECT link_ded, month_begin,month_end FROM DBO.salary_ded_empl(@varKSlinkEmpl,@varKSMonth, @varKSYear)T1 WHERE t1.month_begin<=t1.month_end) SDE
		ON SDE.LINK_DED =TT.REF_PAY
	INNER JOIN dbo.Months M ON TT.MonthEnd >= M.[NUM] AND M.[NUM] between SDE.MONTH_BEGIN and SDE.MONTH_END
	LEFT JOIN @varKSVal2 D ON M.NUM = D.[month] -- Для определения факт вычетов
WHERE 
	@Status in (1 /*Основной*/, 3 /*Внешний совместитель*/)	-->>NEW
	AND 
		(@NDFL_OPT5 = 1 or @NDFL_OPT5 = 2 and D.SUMMA_M <> 0 or @NDFL_OPT5 = 3 and D.SUMMA_M > 0)
	AND --Вычет дается, если сотрудник в этом месяце не уволен или есть положительный доход.
		(D.SUMMA_M <> 0 OR dbo.DateEndOfMonth(@DIS_DATE) >= dbo.DateEndOfMonth( dbo.ConvertDMY2Date(1,M.[NUM],@varKSYear)))
ORDER BY
	M.NUM

---Вычеты от взносов в пенсионый фонд
INSERT INTO @varKSTotal ([REF_PAY],[MONTH_BEGIN],[MONTH_END],[SUMMA],[SUMMA_V],[SUMMA_D])
select 
	TA.LINK_DED, MONTH(cj.PERIOD_BEGIN), MONTH(cj.PERIOD_BEGIN), SUM(SUMMA),SUM(SUMMA), (SELECT MAX(A.SUMMA_D) FROM @varKSTotal A WHERE A.MONTH_BEGIN = MONTH(cj.PERIOD_BEGIN))
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 
	year(period_begin) = @varKSYear
	and
	E.LINK = @varKSlinkEmpl	
	and
	@Status in (1 /*Основной*/, 3 /*Внешний совместитель*/) and MONTH(cj.PERIOD_BEGIN) <= Month(@varKSDate) 
	and
	ISNULL(TA.LINK_DED,0) > 0
GROUP BY 
	TA.LINK_DED, MONTH(cj.PERIOD_BEGIN)

/*
Раздение на части сумм вычетов, на которые человек имеет право: фактически предоставленные и остаток непредоставленных вычетов
*/
declare @VychOpt1 int -- ограничивать месячный вычет месячным доходом
declare	@VychOpt2 int  -- месячный вычет давать с нарастающим итогом (компенсировать не предоставленный вычет, если в определенном месяце сотрудник не получал дохода)

if @NDFL_OPT5 > 1 begin
	Set @VychOpt1 = ISNULL((SELECT top 1 CONVERT(INT,VALUE) FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'NDFL_OPT1')),0)
	Set @VychOpt2 = ISNULL((SELECT top 1 CONVERT(INT,VALUE) FROM S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'NDFL_OPT2')),0)
end
else
	Select @VychOpt1 = 0, @VychOpt2 = 0

IF @VychOpt1 = 1 --Если ограничивать месячный вычет месячным доходом
BEGIN

	DECLARE @Cur1 CURSOR, @MES tinyint, @REF_V int, @SUMMA_V numeric(18,2), @SUMMA_D numeric(18,2), @Ostatok_V numeric(18,2), @Ostatok numeric(18,2), @Ostatok_m numeric(18,2), @link int
	Declare @SumVPred numeric(18,2) --Сумма уже предоставленных вычетов в отчетном месяце
	SET @Cur1 = CURSOR FORWARD_ONLY

	FOR select link, MONTH_BEGIN, REF_PAY, SUMMA_V, SUMMA_D, Ostatok_V from @varKSTotal order by link
	
	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @link, @MES, @REF_V, @SUMMA_V, @SUMMA_D, @Ostatok_V
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN
			Set @Ostatok = ISNULL((Select Sum(Ostatok_V)  from @varKSTotal 
				where ((@VychOpt2 = 1 and MONTH_BEGIN <= @MES) -- ограниченный месячным доходом вычет давать с нарастающим итогом (компенсировать не предоставленный вычет)
					or (@VychOpt2 = 0 and MONTH_BEGIN = @MES)) -- ограниченный месячным доходом вычет давать без нарастающего итога
					and link < @link and REF_PAY = @REF_V) ,0)
				
			Set @Ostatok_m = ISNULL((Select Sum(Ostatok_V)  from @varKSTotal where Ostatok_V > 0 and MONTH_BEGIN = @MES and link < @link),0)
			Set @SUMMA_V = ISNULL((Select Sum(SUMMA_V)  from @varKSTotal where MONTH_BEGIN = @MES and link <= @link),0)
			Set @SumVPred = ISNULL((Select Sum(SUMMA_V)  from @varKSTotal where MONTH_BEGIN = @MES and link < @link),0)
	
			update @varKSTotal
			Set 	SUMMA_V = (case when ISNULL(@SUMMA_V,0) + @Ostatok > ISNULL(SUMMA_D,0) 
					then ISNULL(SUMMA_D,0) - @SumVPred
					else (case when @Ostatok_m = 0 then ISNULL(@SUMMA_V,0) + @Ostatok - @SumVPred else 0 end) 
				end),
				Ostatok_V = (case when ISNULL(@SUMMA_V,0) + @Ostatok > ISNULL(SUMMA_D,0)
							then ISNULL(@SUMMA_V,0) - ISNULL(SUMMA_D,0)
							else  - @Ostatok
						end)
			where link = @link

		END
	
		FETCH NEXT FROM @Cur1 INTO @link, @MES, @REF_V, @SUMMA_V, @SUMMA_D, @Ostatok_V
	END
	
	CLOSE @Cur1
	DEALLOCATE @Cur1

	IF @varKSfl=1 
	select [Вычет] = (select  rtrim(sname) + ' ' + LEFT(rtrim(name),100) from dbo.DICTIONARY_TYP_DEDUCTION where link = REF_PAY),
		month_begin as [Месяц начала], month_end as [Месяц окончания], summa as [Сумма вычета по НК], summa_v as [Сумма вычета факт], Ostatok_V as [Изменение остатка вычетов] from @varKSTotal order by month_begin,  REF_PAY
	
	update @varKSTotal 
	Set summa = summa_v
END
/**/

/* ^^^^^^ Имущественные вычеты - Начало расчета ^^^^^^^^*/

declare @VychOpt9 int -- имущественный вычет предоставлять с даты регистрации уведомсления
Set @VychOpt9 = ISNULL((SELECT top 1 CONVERT(INT,VALUE) FROM dbo.S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = 'NDFL_OPT9')),0)

declare @SprOtherDed table(LINK_DICTION int, MONTH1 TINYINT, Summa numeric(18,2))

insert into @SprOtherDed
Select LINK_DICTION, MONTH1, SUM(SUM_DED) 
from 
	EMPL E 
	inner join TAX_DEDUCTIONS TD on E.PERS_LINK = TD.LINK_PERSON AND E.DEP_LINK = TD.LINK_DEP
where 
	E.LINK = @varKSlinkEmpl 
	and [YEAR] = @varKSYear 
	AND @Status in (1 /*Основной*/, 3 /*Внешний совместитель*/) 
	and MONTH1 <= Month(@varKSDate) --DATE_REF <= dbo.DateEndOfMonth(@varKSDate)
	AND E.DEP_LINK = @DEP_LINK
Group by 
	LINK_DICTION, MONTH1

IF @varKSfl=1 
	select [Код]= rtrim(SNAME), [Имущественный вычет] = rtrim(name), [Сумма вычета] = ISNULL(OD.summa,0) from @SprOtherDed OD inner join dbo.DICTIONARY_TYP_DEDUCTION  D on D.link = OD.LINK_DICTION

declare @TMP Table ([REF_PAY] int, [MONTH_BEGIN] int, [MONTH_END] int, [SUMMA] numeric(18,2))
Insert into @TMP
Select [REF_PAY], M.NUM, M.NUM, SUM([SUMMA]) 
from dbo.Months M, @varKSTotal T1 
 where M.[NUM] between [MONTH_BEGIN] and [MONTH_END] and [REF_PAY] not in (select LINK_DICTION from @SprOtherDed) 
group by [REF_PAY], M.NUM

DECLARE @REF_PAY int, @MONTH_BEGIN int, @SUMMA numeric(18,2), @Saldo numeric(18,2), @STD_VYCH NUMERIC(18,2), @MONTH1 TINYINT

DECLARE @Cur CURSOR
SET @Cur = CURSOR FORWARD_ONLY
FOR 
	Select M.NUM, LINK_DICTION, [SUMMA], MONTH1 = (CASE WHEN @VychOpt9 = 1 THEN OD.MONTH1 ELSE 1 END) 
	from @SprOtherDed OD, dbo.Months M 
	WHERE M.NUM BETWEEN (CASE WHEN @VychOpt9 = 1 THEN OD.MONTH1 ELSE 1 END) AND @varKSMonth

OPEN @Cur
FETCH NEXT FROM @Cur INTO @MONTH_BEGIN, @REF_PAY, @SUMMA, @MONTH1
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN
		Set @Saldo = ISNULL(@SUMMA,0) - ISNULL((Select Sum(Summa) from @tmp T where T.REF_PAY = @REF_PAY),0)

		SET @STD_VYCH = ISNULL((SELECT SUM(SUMMA) FROM @varKSTotal WHERE [MONTH_BEGIN] < @MONTH1),0)

		INSERT INTO @TMP ([REF_PAY],[MONTH_BEGIN],[MONTH_END],[SUMMA])
		Select --
			@REF_PAY, @MONTH_BEGIN, @MONTH_BEGIN, 
			(Case When @Saldo > (ISNULL(DS.EMPL_SUMMA,0) - ISNULL(DS.DED0,0) 
								- (ISNULL(DS2.EMPL_SUMMA,0) - ISNULL(DS2.DED0,0) - @STD_VYCH)
								- ISNULL((Select SUM(summa) from @TMP where MONTH_BEGIN <=  @MONTH_BEGIN ),0))
				then (ISNULL(DS.EMPL_SUMMA,0) - ISNULL(DS.DED0,0) 
						- (ISNULL(DS2.EMPL_SUMMA,0) - ISNULL(DS2.DED0,0) - @STD_VYCH)
						- ISNULL((Select SUM(summa) from @TMP where MONTH_BEGIN <=  @MONTH_BEGIN ),0))
			else
				@Saldo
			end)
		from
			@varKSTotTab DS
			LEFT JOIN @varKSTotTab DS2 ON DS2.[Month] = @MONTH1-1 
		where
			DS.[Month] = @MONTH_BEGIN
			and
			(ISNULL(DS.EMPL_SUMMA,0) - ISNULL(DS.DED0,0)
				- (ISNULL(DS2.EMPL_SUMMA,0) - ISNULL(DS2.DED0,0) - @STD_VYCH) 
				- ISNULL((Select SUM(summa) from @TMP where MONTH_BEGIN <=  @MONTH_BEGIN ),0)) > 0
			and 
			@Saldo > 0

	END
	FETCH NEXT FROM @Cur INTO @MONTH_BEGIN, @REF_PAY, @SUMMA, @MONTH1
END

CLOSE @Cur
DEALLOCATE @Cur

INSERT INTO @varKSTotal ( [REF_PAY], [MONTH_BEGIN], [MONTH_END], [SUMMA])
Select * from @TMP where [REF_PAY] in (select LINK_DICTION from @SprOtherDed)

/* vvvvvv Имущественные вычеты - Конец расчета vvvvvvv */


IF @varKSfl=1 
select [Вычет] = (select  rtrim(sname) + ' ' + LEFT(rtrim(name),50) from dbo.DICTIONARY_TYP_DEDUCTION where link = REF_PAY),
	month_begin as [Месяц начала], month_end as [Месяц окончания], summa as [Сумма вычета]  from @varKSTotal T1  order by month_begin, REF_PAY


DECLARE @varKSTotal1 TABLE
([KOL]			[int],
 [REF_PAY] 		[int],
 [MONTH_BEGIN]		[int],
 [MONTH_END]		[int],		
 [SUMMA]		[numeric](19, 2))

INSERT INTO @varKSTotal1 ([KOL],[REF_PAY],[MONTH_BEGIN],[MONTH_END],[SUMMA])
SELECT COUNT(*) AS [KOL],REF_PAY,MONTH_BEGIN,MONTH_END,SUMMA
FROM @varKSTotal 
GROUP BY REF_PAY,MONTH_BEGIN,MONTH_END,SUMMA

DECLARE @varKSvych TABLE
([MONTH] 	[int],
 [REF_PAY] 	[int],
 [DEDUCT]	[numeric] (19, 2),
 [COMMENT]  [varchar] (254),
 [KOEF_VKR] [numeric] (18,10),
 [kol] [numeric] (18,2),
 [SPR_SUM]  NUMERIC(18,2)	
)

DECLARE @NDFL_OPT7 int
SET @NDFL_OPT7 = dbo.sa_get_option_by_code('NDFL_OPT7')

DECLARE @Koef table (Mon int, koef NUMERIC(18,10), doh tinyint, koef2 NUMERIC(18,10))
insert into @Koef (Mon, Koef, doh, koef2)
Select 	T2.[Month], 
	CASE WHEN @NDFL_OPT7 = 1 --Вычеты применять только к доходу по 211 ЭКР
	THEN 
		CASE WHEN @varKSLinkEKR = @Link211EKR 
		THEN --Начислять пропорционально КБК
			--CONVERT(NUMERIC(18,10), case when (t2.summa_m_211- t2.ded_m_all) <> 0 then ((v.summa_m_vkr-T2.ded_m)/(t2.summa_m_211- t2.ded_m_all)) else 0 end )
			CONVERT(NUMERIC(18,10), case when t2.summa_m_211 <> 0 then (v.summa_m_vkr/t2.summa_m_211) else 0 end )
		ELSE 
			0 
		END
	ELSE --Начислять пропорционально КБК и ЭКР
		--CONVERT(NUMERIC(18,10), case when (t2.summa_m- t2.ded_m_all) <> 0 then ((t2.summa_m_vkr-T2.ded_m)/(t2.summa_m- t2.ded_m_all)) else 0 end )
		CONVERT(NUMERIC(18,10), case when t2.summa_m <> 0 then (t2.summa_m_vkr/t2.summa_m) else 0 end )
	END,
	(Case when t2.summa_m <> 0 then 1 else 0 end),
	CONVERT(NUMERIC(18,10), case when t2.summa_m <> 0 then (t2.summa_m_vkr/t2.summa_m) else 0 end )	
from 
	@varKSTotTab T2 
	inner join @varKSVal V on T2.[month] = V.[month]

--СПРАВОЧНИК ВИДОВ ИМУЩЕСТВЕННЫХ ВЫЧЕТОВ
DECLARE @DICT_TAX_DEDUCTIONS TABLE (LINK INT)
INSERT INTO @DICT_TAX_DEDUCTIONS (LINK)
SELECT LINK FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE NUMBER = 4

/*Расстановка коэффициентов на вычеты. Если нет дохода, то вычета по коэф. будующего месяца, в котором доход есть*/
INSERT INTO @varKSvych ([MONTH],[REF_PAY],[DEDUCT],[COMMENT],[KOEF_VKR],[KOL], [SPR_SUM])
SELECT [MONTH] = T1.MONTH_BEGIN, T1.REF_PAY,
	[DEDUCT] = 
			CASE WHEN NOT EXISTS (SELECT * FROM @DICT_TAX_DEDUCTIONS D WHERE D.LINK = T1.REF_PAY) THEN	
				CONVERT(NUMERIC(18,10), T1.KOL*T1.SUMMA * 
				case when D.summa_m = 0 then ISNULL((Select top 1 K.Koef from @Koef K where K.Mon >= T1.MONTH_BEGIN and doh <> 0 order by Mon),0)
					else ISNULL((Select top 1 K.Koef from @Koef K where K.Mon = T1.MONTH_BEGIN and K.Koef <> 0 order by Mon),0) end)
			ELSE
				CONVERT(NUMERIC(18,10), T1.KOL*T1.SUMMA * 
				case when D.summa_m = 0 then ISNULL((Select top 1 K.Koef2 from @Koef K where K.Mon >= T1.MONTH_BEGIN and doh <> 0 order by Mon),0)
					else ISNULL((Select top 1 K.Koef2 from @Koef K where K.Mon = T1.MONTH_BEGIN and K.Koef2 <> 0 order by Mon),0) end)
			END,		

	[COMMENT] = 
			CASE WHEN NOT EXISTS (SELECT * FROM @DICT_TAX_DEDUCTIONS D WHERE D.LINK = T1.REF_PAY) THEN	
				'('+RTRIM(LTRIM(STR(T1.KOL)))+'*'+RTRIM(LTRIM(CONVERT(VARCHAR(100),T1.SUMMA)))+ 
				'*'+ rtrim(ltrim(convert(varchar(100), CONVERT(NUMERIC(18,2), case when D.summa_m = 0 then ISNULL((Select top 1 K.Koef from @Koef K where K.Mon >= T1.MONTH_BEGIN and K.Koef <> 0 order by Mon),0)
					else ISNULL((Select top 1 K.Koef from @Koef K where K.Mon = T1.MONTH_BEGIN and doh <> 0 order by Mon),0) end)) )) +')'
			ELSE
				'('+RTRIM(LTRIM(STR(T1.KOL)))+'*'+RTRIM(LTRIM(CONVERT(VARCHAR(100),T1.SUMMA)))+ 
				'*'+ rtrim(ltrim(convert(varchar(100), CONVERT(NUMERIC(18,2), case when D.summa_m = 0 then ISNULL((Select top 1 K.Koef2 from @Koef K where K.Mon >= T1.MONTH_BEGIN and K.Koef2 <> 0 order by Mon),0)
					else ISNULL((Select top 1 K.Koef2 from @Koef K where K.Mon = T1.MONTH_BEGIN and doh <> 0 order by Mon),0) end)) )) +')'
			END,

	[KOEF_VKR] =
			CASE WHEN NOT EXISTS (SELECT * FROM @DICT_TAX_DEDUCTIONS D WHERE D.LINK = T1.REF_PAY) THEN
				 CONVERT(NUMERIC(18,10), case when D.summa_m = 0 then ISNULL((Select top 1 K.Koef from @Koef K where K.Mon >= T1.MONTH_BEGIN and K.Koef <> 0 order by Mon),0)
					else ISNULL((Select top 1 K.Koef from @Koef K where K.Mon = T1.MONTH_BEGIN and doh <> 0 order by Mon),0) end )
			ELSE
				 CONVERT(NUMERIC(18,10), case when D.summa_m = 0 then ISNULL((Select top 1 K.Koef2 from @Koef K where K.Mon >= T1.MONTH_BEGIN and K.Koef2 <> 0 order by Mon),0)
					else ISNULL((Select top 1 K.Koef2 from @Koef K where K.Mon = T1.MONTH_BEGIN and doh <> 0 order by Mon),0) end )				
			END,		
	T1.KOL,
	T1.KOL*T1.SUMMA
FROM @varKSTotal1 t1 left join @varKSTotTab D on T1.MONTH_BEGIN = D.[Month]--, @varKSTotTab T2 WHERE T2.[MONTH] BETWEEN T1.MONTH_BEGIN AND T1.MONTH_END 
ORDER BY 1

INSERT INTO dbo.SAL_DED_MONTH (LINK_EMPL,REF_DED,SUMMA,DATE_DED,LINK_VKR,LINK_EKR,TYPE, KOEF_VKR, KOL )
SELECT 	[LINK_EMPL] = @varKSlinkEmpl,
			[REF_DED] 	= T.REF_PAY,
			[SUMMA] 	= T.DEDUCT,
			[DATE_DED] 	= dbo.ConvertDMY2Date(1,t.[month],year(@varKSDate)),
			[LINK_VKR]	= @varKSLinkVKR,
			[LINK_EKR]	= @varKSLinkEKR,
			[TYPE] 		= 1, --convert(NUMERIC(3,0),B.VALUE)
			[KOEF_VKR],
			[KOL]
FROM @varKSvych T WHERE T.DEDUCT <> 0 

--========================================================================================
--Блок проверки и коррестировки ошибки, связанной с погрешностья округления разбитых по источникам вычетов
SELECT S.REF_DED, MONTH(DATE_DED) AS MN, V.SPR_SUM - SUM(SUMMA) AS SUMMA
INTO #CORRECT
FROM dbo.SAL_DED_MONTH S INNER JOIN @varKSvych V ON V.[MONTH] = MONTH(S.DATE_DED) AND S.REF_DED = V.REF_PAY
WHERE YEAR(DATE_DED) = year(@varKSDate) AND LINK_EMPL = @varKSlinkEmpl
GROUP BY S.REF_DED, MONTH(DATE_DED), V.SPR_SUM
HAVING ABS(V.SPR_SUM - SUM(SUMMA)) BETWEEN 0.01 AND 0.02

IF EXISTS(SELECT * FROM #CORRECT) BEGIN

	UPDATE V
	SET V.DEDUCT = ISNULL(V.DEDUCT,0) + ISNULL(C.SUMMA,0)
	FROM @varKSvych V INNER JOIN #CORRECT C ON V.[MONTH] = C.MN AND C.REF_DED = V.REF_PAY

	DELETE FROM dbo.SAL_DED_MONTH 
	WHERE YEAR(DATE_DED) = year(@varKSDate) AND LINK_EMPL = @varKSlinkEmpl AND [LINK_VKR] = @varKSLinkVKR AND [LINK_EKR] = @varKSLinkEKR
		AND REF_DED IN (SELECT REF_PAY FROM @varKSvych)

	INSERT INTO dbo.SAL_DED_MONTH (LINK_EMPL,REF_DED,SUMMA,DATE_DED,LINK_VKR,LINK_EKR,TYPE, KOEF_VKR, KOL )
	SELECT 	[LINK_EMPL] = @varKSlinkEmpl,
				[REF_DED] 	= T.REF_PAY,
				[SUMMA] 	= T.DEDUCT,
				[DATE_DED] 	= dbo.ConvertDMY2Date(1,t.[month],year(@varKSDate)),
				[LINK_VKR]	= @varKSLinkVKR,
				[LINK_EKR]	= @varKSLinkEKR,
				[TYPE] 		= 1, --convert(NUMERIC(3,0),B.VALUE)
				[KOEF_VKR],
				[KOL]
	FROM @varKSvych T WHERE T.DEDUCT <> 0 

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

DECLARE @varKSTota TABLE
([MONTH] 		[int],
 [PERS_SUMMA_VKR]	[numeric](19, 2),
 [SUMMA_VKR]	[numeric](19, 2),
 [SUMMA_M]		[numeric](19, 2),
 [SUMMA_M_VKR]	[numeric](19, 2),
 [DED_M_ALL] 	[numeric](19, 2),
 [DED]			[numeric](19, 2),
 [DED_M]			[numeric](19, 2),
 [VYCH]			[numeric](19, 2),
 [VYCH_M]		[numeric](19, 2),
 [DOHOD_ALL]	[numeric](19, 2),
 [VICHET_ALL]	[numeric](19, 2)
 ) 

INSERT INTO @varKSTota([MONTH], [PERS_SUMMA_VKR], [SUMMA_VKR],[SUMMA_M],[SUMMA_M_VKR],[DED_M_ALL],[DED],[DED_M],[VYCH],[VYCH_M],[DOHOD_ALL],[VICHET_ALL])
SELECT T1.[MONTH],T1. [SUMMA_VKR], T1.[EMPL_SUMMA_VKR],T1.[SUMMA_M],T1.[SUMMA_M_VKR],T1.[DED_M_ALL],T1.[DED],T1.[DED_M],
		[VYCH]	=ISNULL((SELECT SUM(V.DEDUCT) FROM @varKSvych v WHERE V.[MONTH]<= T1.[MONTH]),0),
		[VYCH_M] =ISNULL((SELECT SUM(V.DEDUCT) FROM @varKSvych v WHERE V.[MONTH] = T1.[MONTH]),0),
		[DOHOD_ALL] = T1.[EMPL_SUMMA],
		[VICHET_ALL] = ISNULL((SELECT SUM(V.SPR_SUM) FROM @varKSvych v WHERE V.[MONTH]<= T1.[MONTH]),0)
FROM @varKSTotTab T1

IF @varKSfl=1 
	select [month] as [Месяц],pers_summa_vkr as [Сумма ФЛ с нач года по ВКР], summa_vkr as [Сумма сотр с нач года по ВКР], summa_m as [Сумма сотр за месяц], 
	summa_m_vkr as [Сумма сотр за месяц по ВКР], ded_m_all as [Скидки всего], ded as [Скидки всего по ВКР], ded_m as [Скидки за месяц по ВКР], 
	vych as [Вычеты всего], vych_m  as [Вычеты за месяц] from @varKSTota

----
declare @varKSSumDed numeric(15,2), @varKSRange  numeric(15,2), @varKSResid int, @varKSStrCom varchar(1000)

SET @varKSSumDed = ISNULL(
	(SELECT sum(summa) 
	FROM
		dbo.PAYS P INNER JOIN dbo.CALCULATE_JURNAL SJ ON P.LINK = SJ.LINK_PAYS
	WHERE
		SJ.LINK_PAYS = @varKSRef_Pay
		AND YEAR(SJ.PERIOD_BEGIN) = @varKSYear
		AND MONTH(SJ.PERIOD_BEGIN) <=@varKSMonth 
		AND SJ.LINK_EMPL = @varKSlinkEmpl 
		AND SJ.LINK_VKR = @varKSLinkVKR
		AND SJ.LINK_DEP = @DEP_LINK 
		AND ISNULL(SJ.LINK_EKR,P.LINK_EKR) = @varKSLinkEKR)
	,0)	
	
SET @varKSSumDed = @varKSSumDed + ISNULL( (SELECT SUM(SR.NDFL) FROM dbo.SAL_REMAIN SR WHERE SR.LINK_EMPL = @varKSlinkEmpl AND SR.YEAR_SAL = @varKSYear AND SR.LINK_VKR = @varKSLinkVKR AND SR.LINK_EKR = @varKSLinkEKR), 0)

set @varKSRange =  dbo.SalaryGetNDFLRange (@varKSlinkEmpl,@varKSDate)
set @varKSResid = dbo.GetEmplResident(@varKSlinkEmpl)

IF @varKSfl=1 
	select [Удержано с нач года] = @varKSSumDed, [Ставка налога] = @varKSRange, [Статус] = (case when @varKSResid = 1  then 'Резидент' else 'Не резидент' end)


set @varKSStrCom = ''
DECLARE @varKSCurs CURSOR,
		  @varKSCurCOMMENT varchar(255)

SET @varKSCurs = CURSOR FORWARD_ONLY
FOR SELECT COMMENT FROM @varKSvych WHERE DEDUCT <> 0 and [month]=@varKSMonth
OPEN @varKSCurs
FETCH NEXT FROM @varKSCurs INTO @varKSCurCOMMENT
WHILE @@FETCH_STATUS = 0
BEGIN
	SET @varKSStrCom = @varKSStrCom + ' ' + isnull(@varKSCurCOMMENT,'0')+ ' +'
	FETCH NEXT FROM @varKSCurs INTO @varKSCurCOMMENT
END 
CLOSE @varKSCurs
DEALLOCATE @varKSCurs
IF LEN(@varKSStrCom) > 2
	SET @varKSStrCom = LEFT(@varKSStrCom,LEN(@varKSStrCom)-2) 


IF @varKSfl=1 
BEGIN	
	PRINT 'Расчет налога с общего дохода по КБК'
	
	SELECT T.*,
	[sum_ded]=  isnull(@varKSSumDed,0),
	[summa] = 	case when DOHOD_ALL > VICHET_ALL THEN
					convert(numeric(18,2),(summa_vkr -ded - (case when @varKSResid = 1 then vych else 0 end))*@varKSRange/100)
				ELSE
					0
				END,
	[comment] = @varKSStrCom
	FROM @varKSTota T
	WHERE [MONTH] = @varKSMonth
	
END

/*Вычеты, скидки и налог пропорционально доли больничных за счет ФСС/зарплате в общем доходе работника*/
IF @varKSfl<>1 
SELECT 
	[MONTH],
	PERS_SUMMA_VKR= convert(numeric(18,2), [PERS_SUMMA_VKR]),
	SUMMA_VKR= convert(numeric(18,2), [SUMMA_VKR]),
	SUMMA_M= convert(numeric(18,2), [SUMMA_M]),
	SUMMA_M_VKR= convert(numeric(18,2), [SUMMA_M_VKR]),
	DED_M_ALL= convert(numeric(18,2), [DED_M_ALL]),
	DED= convert(numeric(18,2),[DED]),
	DED_M= convert(numeric(18,2),[DED_M]),
	VYCH= convert(numeric(18,2), [VYCH]),
	VYCH_M= convert(numeric(18,2), [VYCH_M]),
	[sum_ded]=  convert(numeric(18,0), isnull(@varKSSumDed,0)), 
	[summa] = 	case when convert(numeric(18,0),(summa_vkr -ded - (case when @varKSResid = 1 then vych else 0 end))*@varKSRange/100) > 0
			then 
				case when DOHOD_ALL > VICHET_ALL THEN
					convert(numeric(18,0),(summa_vkr -ded - (case when @varKSResid = 1 then vych else 0 end))*@varKSRange/100)
				ELSE
					0
				END					
			else 
				CASE WHEN @NDFL_OPT8 = 0 
				THEN 
					0
				ELSE
					convert(numeric(18,0),(summa_vkr -ded - (case when @varKSResid = 1 then vych else 0 end))*@varKSRange/100)
				END
			end,
	[comment] = Case when len(rtrim(ltrim(@varKSStrCom))) > 0 then '{' + RTRIM(LTRIM(@varKSStrCom)) + '}' else '' end,
	[RANGE] = @varKSRange/100
FROM @varKSTota T
WHERE [MONTH] = @varKSMonth

GO


GRANT EXECUTE ON dbo.[SD_U_NDFL_FILL] TO PUBLIC

GO

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

GO

CREATE  PROCEDURE [dbo].SD_REP_F417
	@varKScYear VARCHAR(254),
	@varKSnLinkEmpl INT,
	@nCheck1 int = 0 ,/* Объединять начисления */
	@nMode int = 0/* 0-По сотрудникам, 1-По ГПХ */
AS 
BEGIN

	DECLARE @varKSnYear INT
	SELECT @varKSnYear = CAST(@varKScYear AS INT)
	DECLARE @varKSnLinkPers INT
	
	declare @DEP_LINK int
	exec dbo.xd_whats_zb @DEP_LINK output	

	DECLARE @varKSstart_date DATETIME, 
			@varKSEND_DATE DATETIME

	SELECT @varKSstart_date = dbo.ConvertDMY2Date(1,1,@varKSnYear)
	SELECT @varKSEND_DATE  = dbo.DateEndOfYear(@varKSstart_date)

	DECLARE 
		@varKSCODE_FKR_D VARCHAR(10), @varKSNAME_FKR_D VARCHAR(254),
		@varKSCODE_FKR_T VARCHAR(10), @varKSNAME_FKR_T VARCHAR(254),
		@varKSCODE_FKR_E VARCHAR(10), @varKSNAME_FKR_E VARCHAR(254),
		@varKSDate datetime
		
	IF @nMode = 0 
	BEGIN
		SELECT @varKSnLinkPers = PERS_LINK FROM dbo.EMPL WHERE LINK = @varKSnLinkEmpl

		SELECT TOP 1
			@varKSCODE_FKR_D = CODE_FKR_D, @varKSNAME_FKR_D = NAME_FKR_D,
			@varKSCODE_FKR_T = CODE_FKR_T, @varKSNAME_FKR_T = NAME_FKR_T,
			@varKSCODE_FKR_E = CODE_FKR_E, @varKSNAME_FKR_E = NAME_FKR_E,
			@varKSDate = dpe.date_begin
		FROM 
			dbo.BI_DICTION_VKR VKR 
			INNER JOIN dbo.SAL_SFIN F ON F.KBK = VKR.LINK		
			INNER JOIN dbo.DICTIONARY_PAYS_EMPL_FN(@varKSEND_DATE,@varKSnLinkEmpl,0,DEFAULT,@DEP_LINK,1) DPE ON DPE.LINK_KBK = F.LINK
		WHERE 
			DPE.DATE_BEGIN <= @varKSEND_DATE  
		ORDER BY 
			DPE.DATE_BEGIN DESC


		CREATE TABLE #PART1(SUBDIV VARCHAR(254),FIO VARCHAR(254),TAB_NUM VARCHAR(15),
							BIRTH DATETIME, KATEG VARCHAR(254), OBR VARCHAR(254), 
							ZV_STEP VARCHAR(254), EXPIR VARCHAR(40), 
							OSN_OKL NUMERIC(20,2), CHILDREN INT, IZHD INT, INV VARCHAR(20), PENS_DATE datetime)

		INSERT INTO #PART1
		SELECT TOP 1
			[SUBDIV]  = EP.SUBDIV_NAME,
			[FIO] 	  = RTRIM(P.FM) + ' ' + RTRIM(P.IM) + ' ' + RTRIM(P.OT),
			[tab_num] = EP.TAB,
			[BIRTH]   = P.BIRTHDATE,
			[KATEG]   = '',
			[OBR] 	  = (SELECT NAME FROM EDUCTYPE WHERE LINK =  PE.EDUC_LINK),
			[ZV_STEP] = RTRIM(ISNULL((SELECT NAME FROM dbo.ACAD_STATUS WHERE LINK = P.ACAD_STATUS_LINK),'')) + ' ' 
						+ RTRIM(ISNULL((SELECT NAME FROM dbo.ACAD_DEGREE WHERE LINK = P.ACAD_DEGREE_LINK),'')),
			[EXPIR]   = '',
			[OSN_OKL] = (SELECT OKLAD FROM dbo.SALARY_OKLAD(@varKSEND_DATE,@varKSnLinkEmpl, DEFAULT, @DEP_LINK)),
			[CHILDREN] = (SELECT COUNT(*) FROM dbo.KU_PERS_FAMILY F WHERE 
										F.PERS_LINK = EP.PERS_LINK AND YEAR(F.[BIRTHDATE]) <= @varKSnYear
										AND FAMILY_NAME IN ('Сын','Дочь')),
			[IZHD] = (SELECT COUNT(*) FROM dbo.PERS_FAMILY F WHERE 
										F.PERS_LINK = EP.PERS_LINK  AND IZHD = 1 AND @varKSnYear BETWEEN YEAR(F.[IZHD_BEG]) AND ISNULL(YEAR(F.[IZHD_END]),@varKSnYear)),
			[INV] = (SELECT TOP 1 LTRIM(RTRIM(PV.GROUP_NAME)) FROM dbo.KU_PERS_INVALID PV
					 WHERE PV.PERS_LINK = P.LINK AND @varKSEND_DATE BETWEEN DATE_BEGIN AND ISNULL(DATE_END,@varKSEND_DATE)),
			[PENS_DATE] = (SELECT TOP 1 K.DATE_PENS FROM dbo.KJ_PERS_PENSION K WHERE K.PERS_LINK = P.LINK)
		FROM 
			dbo.SD_EMPL_FN(@varKSnLinkEmpl, @varKSEND_DATE, DEFAULT, @DEP_LINK) EP  
			INNER JOIN dbo.PERSON P ON (EP.PERS_LINK = P.LINK)
			LEFT OUTER JOIN dbo.KU_PERS_EDUCATION PE ON (P.LINK = PE.PERS_LINK
					 and (SATISFY = (case when exists (select * from  KU_PERS_EDUCATION where pers_link = P.LINK and SATISFY = 1)
				then  1
				else 0
				end)
				and pe.educ_code = (case when SATISFY = 0 
				then 	 (select max(educ_code) from  KU_PERS_EDUCATION where pers_link = P.LINK)
				else (select max(educ_code) from  KU_PERS_EDUCATION where pers_link = P.LINK and SATISFY = 1)
				end		)))
	
					

		--Вычисление категории
		DECLARE @varKSKATEG VARCHAR(4000), @varKSTMP_STR VARCHAR(254)
		SET @varKSKATEG = ''
		DECLARE #KAT_CURSOR CURSOR LOCAL FAST_FORWARD FOR

		SELECT TOP 1 ISNULL(QUALIFY, '') 
		FROM dbo.KU_PERS_EDUCATION PE
		WHERE PERS_LINK = @varKSnLinkPers AND YEAR(DATE_END) <= @varKSnYear
		ORDER BY SATISFY DESC
		
		OPEN #KAT_CURSOR
		FETCH #KAT_CURSOR INTO @varKSTMP_STR
		WHILE @@FETCH_STATUS = 0 BEGIN
			SET @varKSKATEG = @varKSKATEG + ' ' + RTRIM(@varKSTMP_STR)
			FETCH #KAT_CURSOR INTO @varKSTMP_STR
		END
		CLOSE #KAT_CURSOR
		DEALLOCATE #KAT_CURSOR

		UPDATE #PART1 SET KATEG = LTRIM(RTRIM(@varKSKATEG))

		--	
		declare @varKSdays int, @varKSmonths int, @varKSyears int, @varKScDate varchar(10)
		SELECT @varKSyears = years, @varKSmonths = months, @varKSdays = days from dbo.ku_EmplExpirTable(@varKSnLinkEmpl,@varKSEND_DATE, DEFAULT) ET WHERE ET.EXPIR_CODE = 'GEN'  

		UPDATE #PART1 SET EXPIR = 
			RTRIM(LTRIM(CAST (@varKSyears AS VARCHAR(4) ))) + ' лет '
			+ RTRIM(LTRIM(CAST (@varKSmonths AS VARCHAR(2) ))) + ' месяцев '
			+ RTRIM(LTRIM(CAST (@varKSdays AS VARCHAR(2) ))) + ' дней '

		CREATE TABLE #DPE (LINK_EMPL INT, LINK_PAYS INT, ORDER_DATE DATETIME, DATE_BEGIN DATETIME, DATE_END DATETIME, VALUE NUMERIC(18,4))

		INSERT INTO #DPE (LINK_EMPL, LINK_PAYS, ORDER_DATE, DATE_BEGIN, DATE_END, VALUE)
		SELECT LINK_EMPL, LINK_PAYS, ORDER_DATE, DATE_BEGIN, DATE_END, VALUE 
		FROM dbo.DICTIONARY_PAYS_EMPL_FN(DEFAULT,@varKSnLinkEmpl,0,DEFAULT,DEFAULT,DEFAULT)

		CREATE TABLE #PAYS_EMPL(
			LINK_PAY INT, cp varchar(10), NP VARCHAR(254), 
			date_begin datetime, date_end datetime,
			s numeric(20,2), parent_id int
		)


		-- На начало года по стортуднику
		INSERT INTO #PAYS_EMPL
		SELECT 
			ISNULL(P1.LINK,P.LINK), ISNULL(P1.CODE,P.CODE), ISNULL(P1.NAME,P.NAME), ISNULL(DPE.ORDER_DATE,DPE.DATE_BEGIN), NULL, VALUE, 0
		FROM 
			#DPE DPE
			INNER JOIN dbo.PAYS P ON P.LINK = DPE.LINK_PAYS
			LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1 
		WHERE 
			LINK_EMPL = @varKSnLinkEmpl
			AND @varKSstart_date - 1 BETWEEN DPE.DATE_BEGIN AND ISNULL(DATE_END, '30000101')
			AND VALUE > 0
		
		-- Изменения в выбранном году
		INSERT INTO #PAYS_EMPL
		SELECT 
			ISNULL(P1.LINK,P.LINK), ISNULL(P1.CODE,P.CODE), ISNULL(P1.NAME,P.NAME), 
			ISNULL(DPE.ORDER_DATE,DPE.DATE_BEGIN), 
			DATE_END, VALUE, 0
		FROM 
			#DPE DPE
			INNER JOIN dbo.PAYS P ON P.LINK = DPE.LINK_PAYS
			LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1
		WHERE 
			LINK_EMPL = @varKSnLinkEmpl
			AND YEAR(ISNULL(DPE.ORDER_DATE,DPE.DATE_BEGIN)) = @varKSnYear
			AND ISNULL(DATE_END, '30000101') >= @varKSstart_date
			AND VALUE > 0
			AND NOT EXISTS (SELECT * FROM #PAYS_EMPL PE WHERE PE.LINK_PAY = ISNULL(P1.LINK,P.LINK) AND PE.date_begin = ISNULL(DPE.ORDER_DATE,DPE.DATE_BEGIN))

		-- Прочие действующие сейчас начисления
		INSERT INTO #PAYS_EMPL
		SELECT 
			ISNULL(P1.LINK,P.LINK), ISNULL(P1.CODE,P.CODE), ISNULL(P1.NAME,P.NAME), NULL, NULL, VALUE, 0
		FROM 
			#DPE DPE
			INNER JOIN dbo.PAYS P ON P.LINK = DPE.LINK_PAYS
			LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1
		WHERE 
			LINK_EMPL = @varKSnLinkEmpl
			AND DATE_BEGIN = (Select max(DATE_BEGIN) from dbo.DICTIONARY_PAYS_EMPL_FN(@varKSEND_DATE,@varKSnLinkEmpl,0,DEFAULT,@DEP_LINK,1) DPE1 where DPE1.LINK_EMPL = DPE.LINK_EMPL and DPE1.LINK_PAYS = DPE.LINK_PAYS and DPE1.DATE_BEGIN <= @varKSEND_DATE AND ISNULL(DPE1.DATE_END, '30000101') >= @varKSstart_date) 
			AND ISNULL(DATE_END, '30000101') >= @varKSstart_date
			AND VALUE > 0
			AND NOT EXISTS (SELECT * FROM #PAYS_EMPL PE WHERE PE.LINK_PAY = ISNULL(P1.LINK,P.LINK))

		UPDATE #PAYS_EMPL
		SET DATE_BEGIN = NULL
		WHERE DATE_BEGIN < @varKSstart_date

		UPDATE R
		SET CP = CP + '*', NP = NP + '*'
		FROM
			#PAYS_EMPL R
			INNER JOIN dbo.PAYS P on P.LINK_MPAY = R.LINK_PAY

		CREATE TABLE #TMP2 ( ID INT IDENTITY, ORDER_DATE datetime, ORDER_NUM VARCHAR(30), 
			SUBDIV VARCHAR(254), POST VARCHAR(254), CONDITION VARCHAR(40), 
			KATEG VARCHAR(254), AVANSE NUMERIC(20, 2), REAL_REC BIT
		)
		
		--INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG,
		--	REAL_REC)
		--SELECT TOP 1 DATE, NUMBER, SUBDIVISION_PD, POST_PD, '', '', 1
		--FROM DICTIONARY_PURP_DISP_FACES 
		--WHERE EMPL_LINK = @varKSnLinkEmpl AND YEAR(DATE_PD) < @varKSnYear
		--ORDER BY DATE_PD DESC

		CREATE TABLE #STAFF_INFO(LINK_UP INT, SUBDIV_NAME VARCHAR(254), POST_NAME VARCHAR(254), DATE_BEGIN DATETIME, DATE_END DATETIME)
		INSERT INTO #STAFF_INFO(LINK_UP, SUBDIV_NAME, POST_NAME, DATE_BEGIN, DATE_END)
		SELECT 
			S.LINK_UP, 
			(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)),
			DP.NAME,
			S.DATE_BEGIN, 
			S.DATE_END
		FROM 
			DBO.STAFF_HEAD SH
			INNER JOIN dbo.staff s ON s.link_up=sh.link
			LEFT OUTER JOIN dbo.POST DP ON DP.LINK = s.post_link
			
		--Приказы о приёме и переводе
		---------------------------
		-- Прием
		INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG, REAL_REC)
		SELECT 
			o.[DATE], o.NUMBER, 'ПРИНЯТ(А) ' + CONVERT(VARCHAR(10),im.DATE_BEGIN,104), S.POST_NAME, '', '', 1 /*#3584 Шорков И.А. добавление даты приема*/
		FROM 
			ITEM_MOVE im 
			INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE = 1
			LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
			
		WHERE 
			im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) <= @varKSnYear	 /* #3584 Шорков И.А. приказ о приеме работника может быть не только за выбранный год */
		ORDER BY 
			IM.DATE_BEGIN DESC
		---
		INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG,REAL_REC)
		SELECT NULL, NULL, NULL, NULL, '', '', 1
		WHERE EXISTS (
			SELECT * FROM #DPE DPE WHERE LINK_EMPL = @varKSnLinkEmpl
					AND @varKSstart_date-1 BETWEEN DPE.DATE_BEGIN AND ISNULL(DATE_END, '30000101')
					AND VALUE > 0	
			)		

		---		

		--Перевод
		INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG, REAL_REC)
		SELECT 
			o.[DATE], o.NUMBER, 
			case when ORD.obj_code = 'MOVES' then 'ПЕРЕВЕДЕН(А) ' + CONVERT(VARCHAR(10),im.DATE_BEGIN,104)
				 else ORD.type_txt + ' ' + CONVERT(VARCHAR(10),im.DATE_BEGIN,104) end	, 
			S.POST_NAME, '', '', 1 /*#3584 Шорков И.А. добавление даты приема*/
		FROM 
			ITEM_MOVE im 
			INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE not in(2,1)
			inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
			LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
			
		WHERE 
			im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear	 /* #3584 Шорков И.А. приказ о приеме работника может быть не только за выбранный год */
		
		union 
	 		SELECT DISTINCT DATE_BEGIN, null, '','','','',1
			FROM #PAYS_EMPL
			WHERE 
			DATE_BEGIN NOT IN (SELECT ISNULL(O.[DATE],'18000101') FROM ITEM_MOVE im 
								INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE not in(2,1)
								inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
								LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
									WHERE 
								im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear)
			AND ( DATE_BEGIN >= ISNULL((SELECT MIN(O.[DATE]) FROM ITEM_MOVE im 
								INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE not in(2,1)
								inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
								LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
									WHERE 
								im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear), '18000101')
			OR ISNULL(DATE_END,'18000101') < ISNULL((SELECT MIN(O.[DATE]) FROM ITEM_MOVE im 
								INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE not in(2,1)
								inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
								LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
									WHERE 
								im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear), '18000101')		
			)								



		/*ORDER BY 
			DATE_BEGIN ASC*/

		-----------------------------
			
		-- Приказы об увольнении
		DECLARE @DICTIONARY_PUV INT
		SET @DICTIONARY_PUV = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS WHERE CODE = 'DICTIONARY_PUV')

		INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG, REAL_REC)
		SELECT 
			o.[DATE], o.NUMBER, 'УВОЛЕН(А) ' + CONVERT(VARCHAR(10),DIS_DATE,104), LEFT(D.NAME,254), '', '', 1
		FROM 
			dbo.ITEM_DIS_FACE DF
			INNER JOIN dbo.ORDERS O ON DF.ORDER_LINK=o.LINK and DF.active=1
			INNER JOIN dbo.DICTION D ON D.LINK = DF.REASON
		WHERE 
			DF.EMPL_LINK = @varKSnLinkEmpl AND YEAR(DF.DIS_DATE) = @varKSnYear	
		ORDER BY 
			DF.DIS_DATE DESC		
			
		DECLARE @varKSDATE_MIN DATETIME, @varKSADVANCE NUMERIC(20, 2)

		SELECT @varKSADVANCE = OKL.OKLAD * ISNULL(AVANCE, 0) / 100.0 
		FROM EMPL E,dbo.salary_oklad(@varKSEND_DATE, @varKSnLinkEmpl, DEFAULT, @DEP_LINK) OKL  
		WHERE OKL.LINK_EMPL = @varKSnLinkEmpl AND E.LINK = OKL.LINK_EMPL 

		SET @varKSDATE_MIN = ISNULL((SELECT MIN(ORDER_DATE) FROM #TMP2), '18000101')


		/*INSERT INTO #TMP2(ORDER_DATE, REAL_REC)
		SELECT DISTINCT DATE_BEGIN, 1
		FROM #PAYS_EMPL
		WHERE 
			DATE_BEGIN NOT IN (SELECT ISNULL(ORDER_DATE,'18000101') FROM #TMP2)
			AND DATE_BEGIN >= @varKSDATE_MIN
		*/
		
		
		DECLARE #TMP_CUR CURSOR LOCAL FAST_FORWARD FOR 
			SELECT ID, ORDER_DATE
			FROM #TMP2
			ORDER BY ORDER_DATE DESC
		DECLARE @varKSID INT, @varKSORDER_DATE DATETIME
		
		OPEN #TMP_CUR
		FETCH #TMP_CUR INTO @varKSID, @varKSORDER_DATE
		WHILE @@FETCH_STATUS = 0 BEGIN
			
			UPDATE #PAYS_EMPL
			SET PARENT_ID = @varKSID 
			WHERE 
				PARENT_ID = 0 
				AND DATE_BEGIN >= @varKSORDER_DATE
			FETCH #TMP_CUR INTO @varKSID, @varKSORDER_DATE
		END
		CLOSE #TMP_CUR
		DEALLOCATE #TMP_CUR
		
		UPDATE #PAYS_EMPL
		SET PARENT_ID = @varKSID 
		WHERE 
			PARENT_ID = 0 


		UPDATE #TMP2 SET AVANSE = @varKSADVANCE WHERE ORDER_DATE = @varKSDATE_MIN
		DECLARE @varKSPAYS_EMPL VARCHAR(100), @varKSTMP2 VARCHAR(120)
		EXEC X_GET_TABLE_NAME @varKSPAYS_EMPL OUTPUT
		SET @varKSTMP2 = @varKSPAYS_EMPL + '_1'

		EXEC M_CROSS_TABLE 
			'PARENT_ID',
			'CP, NP',
			'VARCHAR(10)#VARCHAR(254)',
			'S',
			'NUMERIC(20,2)',
			'SUM(S) AS S',
			'#PAYS_EMPL',
			@varKSPAYS_EMPL


		INSERT INTO #TMP2(REAL_REC) VALUES(0)
		INSERT INTO #TMP2(REAL_REC) VALUES(0)
		INSERT INTO #TMP2(REAL_REC) VALUES(0)
		INSERT INTO #TMP2(REAL_REC) VALUES(0)
		INSERT INTO #TMP2(REAL_REC) VALUES(0)
		INSERT INTO #TMP2(REAL_REC) VALUES(0)

		CREATE TABLE #TMP_3 ( ID INT IDENTITY,
			ORD_DATE DATETIME,	ORD_NUM VARCHAR(30),
			VAC_TYPE VARCHAR(254),
			PERIOD_B DATETIME,	PERIOD_E DATETIME,
			VAC_BEG DATETIME,	VAC_END DATETIME,
			DAYS VARCHAR(254),
			REAL_REC BIT
			)

		INSERT INTO #TMP_3
		(
			ORD_DATE, ORD_NUM, 
			VAC_TYPE,
			PERIOD_B, PERIOD_E,
			VAC_BEG, VAC_END,
			DAYS, REAL_REC
		)
		SELECT 
			DATE, NUMBER,
			TYPE_NAME,
			PERIOD_BEGIN, PERIOD_END,
			case when compens = 0 then DATE_BEGIN ELSE '' END , case when compens = 0 then DATE_END  ELSE '' END,
			dbo.W_DAYS(7, DATE_BEGIN,DATE_END),
			1
		FROM VACATION
		WHERE
			EMPL_LINK = @varKSnLinkEmpl
			AND YEAR([DATE_BEGIN]) = @varKSnYear

	
		CREATE TABLE #TMP_DED (
			ID INT IDENTITY, 
			DOC_NAME VARCHAR(254), DOC_NUM VARCHAR(50), DOC_DST VARCHAR(254), DOC_ADR VARCHAR(254), 
			link_tax int, NAME_TAX VARCHAR(254), DATE1 DATETIME, DATE2 DATETIME, 
			SUMMA_PROC NUMERIC(20,2), SUMMA NUMERIC(20, 2), REAL_REC BIT )

		INSERT INTO #TMP_DED (DOC_NAME, DOC_NUM, DOC_DST, DOC_ADR, link_tax, NAME_TAX, DATE1, DATE2, SUMMA_PROC, SUMMA, REAL_REC)
		SELECT 
			DOC_NAME, 
			DOC_NUM = '№ ' + DOC_NUM + ' от ' + CONVERT(VARCHAR(10),DOC_DATE,104),
			DOC_DST = D.NAME,
			DOC_ADR = 
				LEFT(
					(
					LEFT(ISNULL(dbo.GetAddressByKladr(D.KLADR_LINK), ''), 254) + 
					CASE WHEN LEN(ISNULL(HOUSE, '')) = 0 THEN '' ELSE ', д. ' + LTRIM(RTRIM(HOUSE)) END 
					--+ CASE WHEN LEN(ISNULL(CORP_REAL, '')) = 0 THEN '' ELSE ', корп. ' + LTRIM(RTRIM(CORP_REAL)) END 
					+ CASE WHEN LEN(ISNULL(FLAT, '')) = 0 THEN '' ELSE ', оф. ' + LTRIM(RTRIM(FLAT)) END
					--Расчётный счёт		
					+ ISNULL(
						CASE WHEN DA.CODE IS NOT NULL THEN DA.CODE
							ELSE (SELECT TOP 1 DA1.CODE FROM dbo.DEPARTMENT_ACCOUNTS DA1 WHERE DA1.[TYPE] = 1 AND DA1.LINK_UP = ET.LINK_DEST)
						END, '')
				),254),	
			
			link_tax, NAME_TAX, DATE1, DATE2, SUMMA, SUMMA, 1
		FROM 
			dbo.SD_EMPL_TAX ET
			LEFT JOIN dbo.DEPARTMENTS D ON D.LINK = ET.LINK_DEST
			LEFT JOIN dbo.DEPARTMENT_ACCOUNTS DA ON DA.LINK = D.MAIN_LINK
		WHERE 
			ET.LINK_EMPL = @varKSnLinkEmpl
			AND (DATE2 IS NULL OR DATE2 >= @varKSstart_date)
			AND (DATE1 <= @varKSEND_DATE)


		DECLARE @varKSTMP_INT INT, 
			@varKSCOUNT_2 INT, @varKSCOUNT_3 INT, @varKSCOUNT_4 INT, @varKSCOUNT_MAX INT, @varKSDELTA INT
		SET @varKSCOUNT_2 = (SELECT COUNT(*) FROM #TMP_3)
		SET @varKSCOUNT_MAX = @varKSCOUNT_2
		SET @varKSCOUNT_3 = (SELECT COUNT(*) FROM #TMP_DED)
		IF @varKSCOUNT_MAX < @varKSCOUNT_3 SET @varKSCOUNT_MAX = @varKSCOUNT_3
		IF @varKSCOUNT_MAX =0 SET @varKSCOUNT_MAX = 1
		SET @varKSDELTA = @varKSCOUNT_MAX - @varKSCOUNT_2
		SET @varKSTMP_INT = 1
		WHILE @varKSTMP_INT <= @varKSDELTA BEGIN
			INSERT INTO #TMP_3(REAL_REC) VALUES(0)
			SET @varKSTMP_INT=@varKSTMP_INT+1
		END

		SET @varKSDELTA=@varKSCOUNT_MAX-@varKSCOUNT_3
		SET @varKSTMP_INT=1
		WHILE @varKSTMP_INT<=@varKSDELTA BEGIN
			INSERT INTO #TMP_DED (REAL_REC) VALUES(0)
			SET @varKSTMP_INT=@varKSTMP_INT+1
		END


		INSERT INTO #TMP_3(REAL_REC) VALUES(0)
		INSERT INTO #TMP_3(REAL_REC) VALUES(0)
		INSERT INTO #TMP_3(REAL_REC) VALUES(0)
		INSERT INTO #TMP_DED (REAL_REC) VALUES(0)
		INSERT INTO #TMP_DED (REAL_REC) VALUES(0)
		INSERT INTO #TMP_DED (REAL_REC) VALUES(0)
		

		CREATE TABLE #PART2 (mode int, NAME_STR VARCHAR(254), 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)
		)


		insert into #PART2 
		SELECT 1, 'отработано дней', '',
			M1 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 1 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M2 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 2 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M3 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 3 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M4 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 4 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M5 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 5 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M6 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 6 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M7 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 7 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M8 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 8 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M9 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 9 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M10 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 10 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M11 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 11 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END ),
			M12 = SUM( CASE WHEN MONTH(T.PERIOD_BEGIN) = 12 THEN DBO.SA_GET_EMPL_WD (T.LINK_EMPL, 0, DEFAULT, T.PERIOD_BEGIN, T.PERIOD_END, DEFAULT, DEFAULT) ELSE 0 END )
		FROM	
			(
			SELECT DISTINCT LINK_EMPL, J.PERIOD_BEGIN, J.PERIOD_END
			from 
				dbo.WAY_CALC W
				INNER JOIN dbo.PAYS P ON P.WAY_CALC = W.CODE
				INNER JOIN dbo.CALCULATE_JURNAL J ON P.LINK = J.LINK_PAYS
			where 
				W.[TYPE] = 1 AND W.[OKLAD] = 1
				AND P.[OBJECT] = 1
				AND J.LINK_EMPL = @varKSnLinkEmpl and YEAR(J.PERIOD_BEGIN) = @varKSnYear
			) T	


		insert into #PART2 
		select 2, 'всего начислено', '',
			sum(case when month_begin = 1 then summa else 0 end),
			sum(case when month_begin = 2 then summa else 0 end),
			sum(case when month_begin = 3 then summa else 0 end),
			sum(case when month_begin = 4 then summa else 0 end),
			sum(case when month_begin = 5 then summa else 0 end),
			sum(case when month_begin = 6 then summa else 0 end),
			sum(case when month_begin = 7 then summa else 0 end),
			sum(case when month_begin = 8 then summa else 0 end),
			sum(case when month_begin = 9 then summa else 0 end),
			sum(case when month_begin = 10 then summa else 0 end),
			sum(case when month_begin = 11 then summa else 0 end),
			sum(case when month_begin = 12 then summa else 0 end)
		from s_j_c where link_empl = @varKSnLinkEmpl and year_begin = @varKSnYear
			and typ_oper = 1


		
		insert into #PART2 
		select 4, 'всего удержано', '',
			sum(case when month_begin = 1 then summa else 0 end),
			sum(case when month_begin = 2 then summa else 0 end),
			sum(case when month_begin = 3 then summa else 0 end),
			sum(case when month_begin = 4 then summa else 0 end),
			sum(case when month_begin = 5 then summa else 0 end),
			sum(case when month_begin = 6 then summa else 0 end),
			sum(case when month_begin = 7 then summa else 0 end),
			sum(case when month_begin = 8 then summa else 0 end),
			sum(case when month_begin = 9 then summa else 0 end),
			sum(case when month_begin = 10 then summa else 0 end),
			sum(case when month_begin = 11 then summa else 0 end),
			sum(case when month_begin = 12 then summa else 0 end)
		from s_j_c where link_empl = @varKSnLinkEmpl and year_begin = @varKSnYear
			and typ_oper = 2 
			and link_doc not in (
				select link from documents_ded_pr 
				where year_base = @varKSnYear

					and flag_jc = 1
					and TYP_PAYMENT = 1
			)



	-----Начисленные суммы
		CREATE TABLE #SJ (typ_oper TINYINT , month_begin TINYINT, LINK_PAYS INT, NAME_PAYS VARCHAR(254), CODE_PAYS  varchar(10), SUMMA NUMERIC(18,2))
		INSERT INTO #SJ (typ_oper, month_begin, LINK_PAYS, NAME_PAYS, CODE_PAYS, SUMMA)
		SELECT P.[OBJECT], MONTH(J.PERIOD_BEGIN), ISNULL(P1.LINK,P.LINK), ISNULL(P1.NAME,P.NAME), ISNULL(P1.CODE,P.CODE), SUMMA
		from 
			dbo.CALCULATE_JURNAL J
			INNER JOIN dbo.PAYS P ON P.LINK = J.LINK_PAYS
			LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1
		where 
			link_empl = @varKSnLinkEmpl 
			and YEAR(J.PERIOD_BEGIN) = @varKSnYear
			and P.[OBJECT] in(1, 2)
			and link_doc not in (
				select link from documents_ded_pr 
				where year_base = @varKSnYear
					and flag_jc = 1
					and TYP_PAYMENT = 1
			)
		--
		UPDATE R
		SET NAME_PAYS = NAME_PAYS + '*', CODE_PAYS = CODE_PAYS + '*'
		FROM
			#SJ R
			INNER JOIN dbo.PAYS P on P.LINK_MPAY = R.LINK_PAYS
		--	
		insert into #PART2 
		select 
			case when typ_oper = 1 then 3 else 5 end, 
			name_pays, code_pays,
			sum(case when month_begin = 1 then summa else 0 end),
			sum(case when month_begin = 2 then summa else 0 end),
			sum(case when month_begin = 3 then summa else 0 end),
			sum(case when month_begin = 4 then summa else 0 end),
			sum(case when month_begin = 5 then summa else 0 end),
			sum(case when month_begin = 6 then summa else 0 end),
			sum(case when month_begin = 7 then summa else 0 end),
			sum(case when month_begin = 8 then summa else 0 end),
			sum(case when month_begin = 9 then summa else 0 end),
			sum(case when month_begin = 10 then summa else 0 end),
			sum(case when month_begin = 11 then summa else 0 end),
			sum(case when month_begin = 12 then summa else 0 end)
		from #SJ
		group by 
			case when typ_oper = 1 then 3 else 5 end, 
			name_pays, code_pays


		insert into #PART2 
		select 6, 'сумма к выдаче', '',
			sum(case when month_base = 1 then d1.summa else 0.00 end),
			sum(case when month_base = 2 then d1.summa else 0.00 end),
			sum(case when month_base = 3 then d1.summa else 0.00 end),
			sum(case when month_base = 4 then d1.summa else 0.00 end),
			sum(case when month_base = 5 then d1.summa else 0.00 end),
			sum(case when month_base = 6 then d1.summa else 0.00 end),
			sum(case when month_base = 7 then d1.summa else 0.00 end),
			sum(case when month_base = 8 then d1.summa else 0.00 end),
			sum(case when month_base = 9 then d1.summa else 0.00 end),
			sum(case when month_base = 10 then d1.summa else 0.00 end),
			sum(case when month_base = 11 then d1.summa else 0.00 end),
			sum(case when month_base = 12 then d1.summa else 0.00 end)
		from documents_ded_pr d inner join DOCUMENTS_DED_PR_TABLE d1
			on (d.link = d1.link and d1.REF_Empl = @varKSnLinkEmpl 
				and year_base = @varKSnYear
				and flag_jc = 1
				and TYP_PAYMENT = 1)




		SELECT *,
			@varKSCODE_FKR_D AS CODE_FKR_D, @varKSNAME_FKR_D AS NAME_FKR_D,
			@varKSCODE_FKR_T AS CODE_FKR_T, @varKSNAME_FKR_T AS NAME_FKR_T,
			@varKSCODE_FKR_E AS CODE_FKR_E, @varKSNAME_FKR_E AS NAME_FKR_E
		FROM #PART1

		EXEC ('
			SELECT * 
			INTO ' + @varKSTMP2 + ' 
			FROM #TMP2 T2 LEFT OUTER JOIN ' + @varKSPAYS_EMPL + ' PE
			ON T2.ID = PE.PARENT_ID
		')	
	 
		DECLARE @varKSCNT_PAYS INT, @varKSFIELD_NAME VARCHAR(254), @varKSSQL_STR VARCHAR(8000), @varKSI INT
		SELECT @varKSCNT_PAYS = COUNT(DISTINCT CP) FROM #PAYS_EMPL
		SET @varKSI=1
		WHILE @varKSI <= @varKSCNT_PAYS BEGIN
			SET @varKSFIELD_NAME = 'CP_' + RTRIM(LTRIM(STR(@varKSI))) 
			SET @varKSSQL_STR= ' UPDATE ' + @varKSTMP2 + '  SET '+@varKSFIELD_NAME+ ' = (SELECT TOP 1 '+@varKSFIELD_NAME + ' FROM ' + @varKSPAYS_EMPL + ' 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 ' + @varKSTMP2 + '  SET '+@varKSFIELD_NAME+ ' = (SELECT TOP 1 '+@varKSFIELD_NAME + ' FROM ' + @varKSPAYS_EMPL + ' WHERE '+
				@varKSFIELD_NAME+ '  IS NOT NULL ) ' 
			EXEC (@varKSSQL_STR)
			SET @varKSFIELD_NAME= 'S_'  +  RTRIM(LTRIM(STR(@varKSI)))  + '_'  +  RTRIM(LTRIM(STR(@varKSI))) 
			SET @varKSSQL_STR= ' UPDATE '+@varKSTMP2 + '  SET '+@varKSFIELD_NAME+ ' = 0  WHERE ' +
				@varKSFIELD_NAME+ '  IS  NULL ' 

			SET @varKSI=@varKSI+1
		END

		IF @varKSCNT_PAYS >= 1 AND @varKSCNT_PAYS < 9  BEGIN
			SET @varKSDELTA = 9 - @varKSCNT_PAYS
			SET @varKSI = 1
			WHILE @varKSI <= @varKSDELTA BEGIN
				SET @varKSSQL_STR= 'ALTER TABLE '  + @varKSTMP2 + 
				'  ADD CP_' + LTRIM(STR(@varKSCNT_PAYS + @varKSI)) + '  VARCHAR(10), 
				NP_' + LTRIM(STR(@varKSCNT_PAYS + @varKSI)) + '_' + LTRIM(STR(@varKSCNT_PAYS + @varKSI)) + ' VARCHAR(254), 
				S_' + LTRIM(STR(@varKSCNT_PAYS + @varKSI)) + '_' + LTRIM(STR(@varKSCNT_PAYS + @varKSI)) + '  NUMERIC(20,2) '
				EXEC (@varKSSQL_STR)
				SET @varKSI=@varKSI+1
			END
		END

		IF @varKSCNT_PAYS = 0 BEGIN
			SET @varKSSQL_STR= 
				'ALTER TABLE '  + @varKSTMP2 + 
				'  ADD CP_0  VARCHAR(10), 
				NP_0_0 VARCHAR(254), 
				S_0_0  NUMERIC(20,2) '
				EXEC (@varKSSQL_STR)
		END


		EXEC( 'SELECT *, ITOGOZP = NULL 
		FROM ' + @varKSTMP2 + ' ORDER  by ID, REAL_REC DESC, ORDER_DATE ASC')
	/*
		EXEC( 'SELECT *, ITOGOZP = (SELECT SUM(S) FROM #PAYS_EMPL WHERE ORDER_DATE BETWEEN DATE_BEGIN AND COALESCE(DATE_END,''29990101'')) 
		FROM ' + @varKSTMP2 + ' ORDER BY REAL_REC DESC, ORDER_DATE ASC')
	*/
		SELECT * 
		FROM #TMP_3 INNER JOIN #TMP_DED ON #TMP_3.ID = #TMP_DED.ID
		ORDER BY #TMP_3.REAL_REC DESC, ORD_DATE

		select * from #part2
		order by mode, code


		EXEC ('DROP TABLE ' + @varKSPAYS_EMPL )
		EXEC ('DROP TABLE ' + @varKSTMP2 )
	END 
	ELSE BEGIN
	----------------------------------------------------------------------------
	------ПО ДОГОВОРНИКАМ			---------------------------------------------
	----------------------------------------------------------------------------

		SET @varKSnLinkPers = @varKSnLinkEmpl
			
		select @varKSCODE_FKR_D = CODE_FKR_D, @varKSNAME_FKR_D = NAME_FKR_D,
			@varKSCODE_FKR_T = CODE_FKR_T, @varKSNAME_FKR_T = NAME_FKR_T,
			@varKSCODE_FKR_E = CODE_FKR_E, @varKSNAME_FKR_E = NAME_FKR_E,
			@varKSDate = G.period
		from 	
			DOCUMENTS_DGH G INNER JOIN DOCUMENTS_DGH_T1 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
			inner join BI_DICTION_VKR VKR ON F.KBK = VKR.LINK
		WHERE 
			FLAG_jc = 1
			and G.PERIOD <= @varKSEND_DATE
			AND G.PERIOD >= @varKSstart_date
			AND g.link_dep = @DEP_LINK
			AND (P.link = @varKSnLinkPers OR @varKSnLinkPers = 0)	
		ORDER BY 
			G.PERIOD DESC


		CREATE TABLE #PART1_P(SUBDIV VARCHAR(254),FIO VARCHAR(254),TAB_NUM VARCHAR(15),
							BIRTH DATETIME, KATEG VARCHAR(254), OBR VARCHAR(254), 
							ZV_STEP VARCHAR(254), EXPIR VARCHAR(40), 
							OSN_OKL NUMERIC(20,2), CHILDREN INT, IZHD INT, INV VARCHAR(20), PENS_DATE datetime)

		INSERT INTO #PART1_p
		SELECT TOP 1
			[SUBDIV]  = '',
			[FIO] 	  = RTRIM(P.FM) + ' ' + RTRIM(P.IM) + ' ' + RTRIM(P.OT),
			[tab_num] = '',
			[BIRTH]   = P.BIRTHDATE,
			[KATEG]   = '',
			[OBR] 	  = (SELECT NAME FROM EDUCTYPE WHERE LINK =  PE.EDUC_LINK),
			[ZV_STEP] = RTRIM(ISNULL((SELECT NAME FROM dbo.ACAD_STATUS WHERE LINK = P.ACAD_STATUS_LINK),'')) + ' ' 
						+ RTRIM(ISNULL((SELECT NAME FROM dbo.ACAD_DEGREE WHERE LINK = P.ACAD_DEGREE_LINK),'')),
			[EXPIR]   = '',
			[OSN_OKL] = null,
			[CHILDREN] = (SELECT COUNT(*) FROM dbo.KU_PERS_FAMILY F WHERE 
										F.PERS_LINK = s.PERS_LINK AND YEAR(F.[BIRTHDATE]) <= @varKSnYear
										AND FAMILY_NAME IN ('Сын','Дочь')),
			[IZHD] = (SELECT COUNT(*) FROM dbo.PERS_FAMILY F WHERE 
										F.PERS_LINK = s.PERS_LINK  AND IZHD = 1 AND @varKSnYear BETWEEN YEAR(F.[IZHD_BEG]) AND ISNULL(YEAR(F.[IZHD_END]),@varKSnYear)),
			[INV] = (SELECT TOP 1 LTRIM(RTRIM(PV.GROUP_NAME)) FROM dbo.KU_PERS_INVALID PV
					 WHERE PV.PERS_LINK = P.LINK AND @varKSEND_DATE BETWEEN DATE_BEGIN AND ISNULL(DATE_END,@varKSEND_DATE)),
			[PENS_DATE] = (SELECT TOP 1 K.DATE_PENS FROM dbo.KJ_PERS_PENSION K WHERE K.PERS_LINK = P.LINK)
		FROM 
	 		salary_reestr_dgh s  
	 		inner join PERSON P on s.PERS_LINK = P.link
			LEFT OUTER JOIN dbo.KU_PERS_EDUCATION PE ON (P.LINK = PE.PERS_LINK
					 and (SATISFY = (case when exists (select * from  KU_PERS_EDUCATION where pers_link = P.LINK and SATISFY = 1)
				then  1
				else 0
				end)
				and pe.educ_code = (case when SATISFY = 0 
				then 	 (select max(educ_code) from  KU_PERS_EDUCATION where pers_link = P.LINK)
				else (select max(educ_code) from  KU_PERS_EDUCATION where pers_link = P.LINK and SATISFY = 1)
				end		)))
		where 	(P.link = @varKSnLinkPers OR @varKSnLinkPers = 0)	
				AND s.DATE1 <= @varKSEND_DATE
				AND s.DATE1 >= @varKSstart_date	
				AND s.DEP_LINK = @DEP_LINK
		ORDER BY 
				s.DATE1 DESC		
					

		--Вычисление категории
		DECLARE @varKSKATEG_P VARCHAR(4000), @varKSTMP_STR_P VARCHAR(254)
		SET @varKSKATEG_P = ''
		DECLARE #KAT_CURSOR CURSOR LOCAL FAST_FORWARD FOR

		SELECT TOP 1 ISNULL(QUALIFY, '') 
		FROM dbo.KU_PERS_EDUCATION PE
		WHERE PERS_LINK = @varKSnLinkPers AND YEAR(DATE_END) <= @varKSnYear
		ORDER BY SATISFY DESC
		
		OPEN #KAT_CURSOR
		FETCH #KAT_CURSOR INTO @varKSTMP_STR
		WHILE @@FETCH_STATUS = 0 BEGIN
			SET @varKSKATEG_P = @varKSKATEG_P + ' ' + RTRIM(@varKSTMP_STR_P)
			FETCH #KAT_CURSOR INTO @varKSTMP_STR
		END
		CLOSE #KAT_CURSOR
		DEALLOCATE #KAT_CURSOR

		UPDATE #PART1_P SET KATEG = LTRIM(RTRIM(@varKSKATEG_P))

		--	
		declare @varKSdays_P int, @varKSmonths_P int, @varKSyears_P int, @varKScDate_P varchar(10)
		SELECT @varKSyears_P = years, @varKSmonths_P = months, @varKSdays_P = days from dbo.ku_EmplExpirTable(@varKSnLinkEmpl,@varKSEND_DATE, DEFAULT) ET WHERE ET.EXPIR_CODE = 'GEN'  

		UPDATE #PART1_P SET EXPIR = ''
		/*	RTRIM(LTRIM(CAST (@varKSyears_P AS VARCHAR(4) ))) + ' лет '
			+ RTRIM(LTRIM(CAST (@varKSmonths_P AS VARCHAR(2) ))) + ' месяцев '
			+ RTRIM(LTRIM(CAST (@varKSdays_P AS VARCHAR(2) ))) + ' дней '
		*/	
		CREATE TABLE #DPP (PERS_LINK INT, LINK_PAYS INT, ORDER_DATE DATETIME, ORD_LINK int ,  DATE_BEGIN DATETIME, DATE_END DATETIME, VALUE NUMERIC(18,4))

		INSERT INTO #DPP (PERS_LINK, LINK_PAYS, ORDER_DATE,ORD_LINK, DATE_BEGIN, DATE_END, VALUE)
		SELECT GT.PERS_LINK, GT.LINK_PAY, S.[DATE], S.link, G.PERIOD, dbo.DateEndOfMonth(G.PERIOD), GT.SUMMA 
		FROM DOCUMENTS_DGH G INNER JOIN DOCUMENTS_DGH_T1 GT ON G.LINK = GT.LINK 
							 left  join salary_reestr_dgh s on GT.LINK_DOG =  s.link
		WHERE 
			gt.pers_Link = @varKSnLinkPers
			and G.FLAG_JC = 1
			AND G.LINK_DEP = @DEP_LINK
		
		CREATE TABLE #PAYS_PERS(
			LINK_PAY INT, ord_link int ,cp varchar(10), NP VARCHAR(254), 
			date_begin datetime, date_end datetime,
			s numeric(20,2), parent_id int
		)

		-- На начало года по договорнику
		/*INSERT INTO #PAYS_PERS
		SELECT 
			ISNULL(P1.LINK,P.LINK), ISNULL(P1.CODE,P.CODE), ISNULL(P1.NAME,P.NAME), ISNULL(DPP.ORDER_DATE,DPP.DATE_BEGIN), NULL, VALUE, 0
		FROM 
			#DPP DPP
			INNER JOIN dbo.PAYS P ON P.LINK = DPP.LINK_PAYS
			LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1 
		WHERE 
			PERS_LINK = @varKSnLinkPers
			AND @varKSstart_date - 1 BETWEEN DPP.DATE_BEGIN AND ISNULL(DATE_END, '30000101')
			AND VALUE > 0
		*/

		-- Изменения в выбранном году
		INSERT INTO #PAYS_PERS
		SELECT 
			ISNULL(P1.LINK,P.LINK), ord_link ,ISNULL(P1.CODE,P.CODE), ISNULL(P1.NAME,P.NAME), 
			ISNULL(DPP.ORDER_DATE,DPP.DATE_BEGIN), 
			DATE_END, VALUE, 0
		FROM 
			#DPP DPP
			INNER JOIN dbo.PAYS P ON P.LINK = DPP.LINK_PAYS
			LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1
		WHERE 
			PERS_LINK = @varKSnLinkPers
			AND YEAR(ISNULL(DPP.ORDER_DATE,DPP.DATE_BEGIN)) = @varKSnYear
			AND ISNULL(DATE_END, '30000101') >= @varKSstart_date
			AND VALUE > 0
			AND NOT EXISTS (SELECT * FROM #PAYS_PERS PP WHERE PP.LINK_PAY = ISNULL(P1.LINK,P.LINK) AND PP.date_begin = ISNULL(DPP.ORDER_DATE,DPP.DATE_BEGIN))

		-- Прочие действующие сейчас начисления
		INSERT INTO #PAYS_PERS
		SELECT 
			ISNULL(P1.LINK,P.LINK),ord_link, ISNULL(P1.CODE,P.CODE), ISNULL(P1.NAME,P.NAME), NULL, NULL, VALUE, 0
		FROM 
			#DPP DPP
			INNER JOIN dbo.PAYS P ON P.LINK = DPP.LINK_PAYS
			LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1
		WHERE 
			PERS_LINK = @varKSnLinkPers
			AND DATE_BEGIN = (Select max(g1.period) from DOCUMENTS_DGH G1 INNER JOIN DOCUMENTS_DGH_T1 GT1 ON G1.LINK = GT1.LINK  where GT1.PERS_LINK = DPP.PERS_LINK and Gt1.LINK_PAY = DPP.LINK_PAYS and G1.PERIOD <= @varKSEND_DATE AND ISNULL(dbo.DateEndOfMonth(g1.PERIOD), '30000101') >= @varKSstart_date) 
			AND ISNULL(DATE_END, '30000101') >= @varKSstart_date
			AND VALUE > 0
			AND NOT EXISTS (SELECT * FROM #PAYS_PERS PP WHERE PP.LINK_PAY = ISNULL(P1.LINK,P.LINK))

		UPDATE #PAYS_PERS
		SET DATE_BEGIN = NULL
		WHERE DATE_BEGIN < @varKSstart_date
		
		UPDATE R
		SET CP = CP + '*', NP = NP + '*'
		FROM
			#PAYS_PERS R
			INNER JOIN dbo.PAYS P on P.LINK_MPAY = R.LINK_PAY

		CREATE TABLE #TMP2_P ( ID INT IDENTITY, ORDER_DATE datetime, ORDER_NUM VARCHAR(30),
			SUBDIV VARCHAR(254), POST VARCHAR(254), CONDITION VARCHAR(40), 
			KATEG VARCHAR(254), AVANSE NUMERIC(20, 2), REAL_REC BIT, link_dgh int
		)
		
		--INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG,
		--	REAL_REC)
		--SELECT TOP 1 DATE, NUMBER, SUBDIVISION_PD, POST_PD, '', '', 1
		--FROM DICTIONARY_PURP_DISP_FACES 
		--WHERE EMPL_LINK = @varKSnLinkEmpl AND YEAR(DATE_PD) < @varKSnYear
		--ORDER BY DATE_PD DESC

		CREATE TABLE #STAFF_INFO_P(LINK_UP INT, DEP_NAME VARCHAR(254), POST_NAME VARCHAR(254), DATE_BEGIN DATETIME, DATE_END DATETIME)
		INSERT INTO #STAFF_INFO_P(LINK_UP, DEP_NAME, POST_NAME, DATE_BEGIN, DATE_END)
		SELECT 
			S.LINK, 
			(SELECT TOP 1 [name] FROM dictionary_department_hist WHERE link_UP = s.dep_link and (s.date1 between date_begin and date_end or s.date1< date_begin and s.date2 > date_end or s.date2 between date_begin and date_end)),
			'Наемный рабочий',
			S.DATE1, 
			S.DATE2
		FROM 
			DBO.salary_reestr_dgh S
			
		--Приказы о приёме и переводе
		---------------------------
		-- Прием
		INSERT INTO #TMP2_P (ORDER_DATE, ORDER_NUM ,  SUBDIV, POST, CONDITION, KATEG, REAL_REC, link_dgh)
		SELECT 
			sr.[DATE], sr.NUMBER, case when sr.date2 is not null then 'ПРИНЯТ(А) c' + CONVERT(VARCHAR(10),sr.DATE1,104) + ' по ' + CONVERT(VARCHAR(10),sr.DATE2,104) 
																else 'ПРИНЯТ(А) ' + CONVERT(VARCHAR(10),sr.DATE1,104) end 	
			, '', '', '', 1 , Sr.link /*#3584 Шорков И.А. добавление даты приема*/
		FROM 
			#STAFF_INFO_P S 
			inner join DBO.salary_reestr_dgh Sr ON S.link_up=sr.link and sr.date1 between s.date_begin and s.date_end
		WHERE 
			sr.PERS_LINK = @varKSnLinkPers AND (YEAR(sr.DATE1) <= @varKSnYear and YEAR(sr.DATE2) >= @varKSnYear) 	 /* #3584 Шорков И.А. приказ о приеме работника может быть не только за выбранный год */
		ORDER BY 
			sr.DATE1 
		---
		INSERT INTO #TMP2_P (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG,REAL_REC, link_dgh)
		SELECT NULL, NULL, NULL, NULL, '', '', 1 , null
		WHERE EXISTS (
			SELECT * FROM #DPP DPP WHERE PERS_LINK = @varKSnLinkPers
					AND @varKSstart_date-1 BETWEEN DPP.DATE_BEGIN AND ISNULL(DATE_END, '30000101')
					AND VALUE > 0	
			)		
	
		---		
		/*--Перевод
		INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG, REAL_REC)
		SELECT 
			o.[DATE], o.NUMBER, 
			case when ORD.obj_code = 'MOVES' then 'ПЕРЕВЕДЕН(А) ' + CONVERT(VARCHAR(10),im.DATE_BEGIN,104)
				 else ORD.type_txt + ' ' + CONVERT(VARCHAR(10),im.DATE_BEGIN,104) end	, 
			S.POST_NAME, '', '', 1 /*#3584 Шорков И.А. добавление даты приема*/
		FROM 
			ITEM_MOVE im 
			INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE not in(2,1)
			inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
			LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
			
		WHERE 
			im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear	 /* #3584 Шорков И.А. приказ о приеме работника может быть не только за выбранный год */
		
		union 
	 		SELECT DISTINCT DATE_BEGIN, null, '','','','',1
			FROM #PAYS_EMPL
			WHERE 
			DATE_BEGIN NOT IN (SELECT ISNULL(O.[DATE],'18000101') FROM ITEM_MOVE im 
								INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK and im.active=1 AND IM.NEW_FACE not in(2,1)
								inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
								LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
									WHERE 
								im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear)
			AND DATE_BEGIN >= ISNULL((SELECT MIN(O.[DATE]) FROM ITEM_MOVE im 
								INNER JOIN ORDERS O ON im.ORDER_LINK=o.LINK /*and im.active=1*/ AND IM.NEW_FACE not in(2,1)
								inner join ORDERS_REESTR ORD on im.ORDER_LINK=ord.LINK 
								LEFT OUTER JOIN #STAFF_INFO S ON S.link_up=im.staff_link and im.date_begin between s.date_begin and s.date_end
									WHERE 
								im.EMPL_LINK = @varKSnLinkEmpl AND YEAR(IM.DATE_BEGIN) = @varKSnYear), '18000101')
								
		/*ORDER BY 
			DATE_BEGIN ASC*/
		-----------------------------
			
		-- Приказы об увольнении
		DECLARE @DICTIONARY_PUV INT
		SET @DICTIONARY_PUV = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS WHERE CODE = 'DICTIONARY_PUV')

		INSERT INTO #TMP2 (ORDER_DATE, ORDER_NUM, SUBDIV, POST, CONDITION, KATEG, REAL_REC)
		SELECT 
			o.[DATE], o.NUMBER, 'УВОЛЕН(А) ' + CONVERT(VARCHAR(10),DIS_DATE,104), LEFT(D.NAME,254), '', '', 1
		FROM 
			dbo.ITEM_DIS_FACE DF
			INNER JOIN dbo.ORDERS O ON DF.ORDER_LINK=o.LINK and DF.active=1
			INNER JOIN dbo.DICTION D ON D.LINK = DF.REASON
		WHERE 
			DF.EMPL_LINK = @varKSnLinkEmpl AND YEAR(DF.DIS_DATE) = @varKSnYear	
		ORDER BY 
			DF.DIS_DATE DESC		
		*/	
		DECLARE @varKSDATE_MIN_P DATETIME, 
				@varKSADVANCE_P NUMERIC(20, 2)

		set @varKSADVANCE_P = 0
		
		/*SELECT @varKSADVANCE_P = OKL.OKLAD * ISNULL(AVANCE, 0) / 100.0 
		FROM EMPL E,dbo.salary_oklad(@varKSEND_DATE, @varKSnLinkEmpl, DEFAULT, @DEP_LINK) OKL  
		WHERE OKL.LINK_EMPL = @varKSnLinkEmpl AND E.LINK = OKL.LINK_EMPL 
		*/
		SET @varKSDATE_MIN_P = ISNULL((SELECT MIN(ORDER_DATE) FROM #TMP2_P), '18000101')

		/*INSERT INTO #TMP2_P(ORDER_DATE, REAL_REC)
		SELECT DISTINCT DATE_BEGIN, 1
		FROM #PAYS_PERS
		WHERE 
			DATE_BEGIN NOT IN (SELECT ISNULL(ORDER_DATE,'18000101') FROM #TMP2_P)
			AND DATE_BEGIN >= @varKSDATE_MIN
		*/

		DECLARE #TMP_CUR CURSOR LOCAL FAST_FORWARD FOR 
			SELECT ID, ORDER_DATE, link_DGH
			FROM #TMP2_P
			ORDER BY ORDER_DATE DESC, id DESC
		DECLARE @varKSID_P INT, @varKSORDER_DATE_P DATETIME , @varKSORDL_P INT
		
		OPEN #TMP_CUR
		FETCH #TMP_CUR INTO @varKSID_P, @varKSORDER_DATE_P, @varKSORDL_P
		WHILE @@FETCH_STATUS = 0 BEGIN
		
			UPDATE #PAYS_PERS
			SET PARENT_ID = @varKSID_P
			WHERE 
				PARENT_ID = 0 
				AND DATE_BEGIN >= @varKSORDER_DATE_P and ORD_LINK = @varKSORDL_P
			FETCH #TMP_CUR INTO @varKSID_P, @varKSORDER_DATE_P ,@varKSORDL_P
		END
		CLOSE #TMP_CUR
		DEALLOCATE #TMP_CUR
		
		UPDATE #PAYS_PERS
		SET PARENT_ID = @varKSID_P 
		WHERE 
			PARENT_ID = 0 

		UPDATE #TMP2_P SET AVANSE = @varKSADVANCE_P WHERE ORDER_DATE = @varKSDATE_MIN_P
		DECLARE @varKSPAYS_PERS VARCHAR(100), @varKSTMP2_P VARCHAR(120)
		EXEC X_GET_TABLE_NAME @varKSPAYS_PERS OUTPUT
		SET @varKSTMP2_P = @varKSPAYS_PERS + '_1'

		EXEC M_CROSS_TABLE 
			'PARENT_ID',
			'CP, NP',
			'VARCHAR(10)#VARCHAR(254)',
			'S',
			'NUMERIC(20,2)',
			'SUM(S) AS S',
			'#PAYS_PERS',
			@varKSPAYS_PERS


		INSERT INTO #TMP2_P(REAL_REC) VALUES(0)
		INSERT INTO #TMP2_P(REAL_REC) VALUES(0)
		INSERT INTO #TMP2_P(REAL_REC) VALUES(0)
		INSERT INTO #TMP2_P(REAL_REC) VALUES(0)
		INSERT INTO #TMP2_P(REAL_REC) VALUES(0)
		INSERT INTO #TMP2_P(REAL_REC) VALUES(0)

		-- у договорников нет отпусков
		CREATE TABLE #TMP_3_P ( ID INT IDENTITY,
			ORD_DATE DATETIME,	ORD_NUM VARCHAR(30),
			VAC_TYPE VARCHAR(254),
			PERIOD_B DATETIME,	PERIOD_E DATETIME,
			VAC_BEG DATETIME,	VAC_END DATETIME,
			DAYS VARCHAR(254),
			REAL_REC BIT
			)
		INSERT INTO #TMP_3_P
		(
			ORD_DATE, ORD_NUM, 
			VAC_TYPE,
			PERIOD_B, PERIOD_E,
			VAC_BEG, VAC_END,
			DAYS, REAL_REC
		)
		SELECT 
			null, null,
			'',
			null, null,
			null, null,
			null,
			1
		/*INSERT INTO #TMP_3_P
		(
			ORD_DATE, ORD_NUM, 
			VAC_TYPE,
			PERIOD_B, PERIOD_E,
			VAC_BEG, VAC_END,
			DAYS, REAL_REC
		)
		SELECT 
			DATE, NUMBER,
			TYPE_NAME,
			PERIOD_BEGIN, PERIOD_END,
			DATE_BEGIN, DATE_END,
			dbo.W_DAYS(7, DATE_BEGIN,DATE_END),
			1
		FROM VACATION
		WHERE
			EMPL_LINK = @varKSnLinkEmpl
			AND YEAR([DATE_BEGIN]) = @varKSnYear
		*/	
	
		CREATE TABLE #TMP_DED_P (
			ID INT IDENTITY, 
			DOC_NAME VARCHAR(254), DOC_NUM VARCHAR(50), DOC_DST VARCHAR(254), DOC_ADR VARCHAR(254), 
			link_tax int, NAME_TAX VARCHAR(254), DATE1 DATETIME, DATE2 DATETIME, 
			SUMMA_PROC NUMERIC(20,2), SUMMA NUMERIC(20, 2), REAL_REC BIT )

		INSERT INTO #TMP_DED_P (DOC_NAME, DOC_NUM, DOC_DST, DOC_ADR, link_tax, NAME_TAX, DATE1, DATE2, SUMMA_PROC, SUMMA, REAL_REC)
		SELECT 
			DOC_NAME, 
			DOC_NUM = '№ ' + DOC_NUM + ' от ' + CONVERT(VARCHAR(10),DOC_DATE,104),
			DOC_DST = D.NAME,
			DOC_ADR = 
				LEFT(
					(
					LEFT(ISNULL(dbo.GetAddressByKladr(D.KLADR_LINK), ''), 254) + 
					CASE WHEN LEN(ISNULL(HOUSE, '')) = 0 THEN '' ELSE ', д. ' + LTRIM(RTRIM(HOUSE)) END 
					--+ CASE WHEN LEN(ISNULL(CORP_REAL, '')) = 0 THEN '' ELSE ', корп. ' + LTRIM(RTRIM(CORP_REAL)) END 
					+ CASE WHEN LEN(ISNULL(FLAT, '')) = 0 THEN '' ELSE ', оф. ' + LTRIM(RTRIM(FLAT)) END
					--Расчётный счёт		
					+ ISNULL(
						CASE WHEN DA.CODE IS NOT NULL THEN DA.CODE
							ELSE (SELECT TOP 1 DA1.CODE FROM dbo.DEPARTMENT_ACCOUNTS DA1 WHERE DA1.[TYPE] = 1 AND DA1.LINK_UP = ET.LINK_DEST)
						END, '')
				),254),	
			
			link_tax, NAME_TAX, DATE1, DATE2, SUMMA, SUMMA, 1
		FROM 
			dbo.SD_EMPL_TAX ET
			inner join #TMP2_P  p2 on ET.LINK_DGH = p2.LINK_DGH
			LEFT JOIN dbo.DEPARTMENTS D ON D.LINK = ET.LINK_DEST
			LEFT JOIN dbo.DEPARTMENT_ACCOUNTS DA ON DA.LINK = D.MAIN_LINK
		WHERE 
			ET.LINK_DGH is not null
			and ET.LINK_EMPL is null
			AND (DATE2 IS NULL OR DATE2 >= @varKSstart_date)
			AND (DATE1 <= @varKSEND_DATE)

		DECLARE @varKSTMP_INT_P INT, 
			@varKSCOUNT_2_P INT, @varKSCOUNT_3_P INT, @varKSCOUNT_4_P INT, @varKSCOUNT_MAX_P INT, @varKSDELTA_P INT
		SET @varKSCOUNT_2_P = 0
		SET @varKSCOUNT_MAX_P = @varKSCOUNT_2_P
		SET @varKSCOUNT_3_P = (SELECT COUNT(*) FROM #TMP_DED_P)
		IF @varKSCOUNT_MAX_P < @varKSCOUNT_3_P SET @varKSCOUNT_MAX_P = @varKSCOUNT_3_P
		IF @varKSCOUNT_MAX_P =0 SET @varKSCOUNT_MAX_P = 1
		SET @varKSDELTA_P = @varKSCOUNT_MAX_P - @varKSCOUNT_2_P
		SET @varKSTMP_INT_P = 1
		/*WHILE @varKSTMP_INT_P <= @varKSDELTA_P BEGIN
			INSERT INTO #TMP_3(REAL_REC) VALUES(0)
			SET @varKSTMP_INT_P=@varKSTMP_INT_P+1
		END
		*/

		SET @varKSDELTA_P=@varKSCOUNT_MAX_P-@varKSCOUNT_3_P
		SET @varKSTMP_INT_P=1
		WHILE @varKSTMP_INT_P<=@varKSDELTA_P BEGIN
			INSERT INTO #TMP_DED_P (REAL_REC) VALUES(0)
			SET @varKSTMP_INT_P=@varKSTMP_INT_P+1
		END


		--INSERT INTO #TMP_3(REAL_REC) VALUES(0)
		--INSERT INTO #TMP_3(REAL_REC) VALUES(0)
		--INSERT INTO #TMP_3(REAL_REC) VALUES(0)
		INSERT INTO #TMP_DED_P (REAL_REC) VALUES(0)
		INSERT INTO #TMP_DED_P (REAL_REC) VALUES(0)
		INSERT INTO #TMP_DED_P (REAL_REC) VALUES(0)
		

		CREATE TABLE #PART2_p (mode int, NAME_STR VARCHAR(254), 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)
		)


		
		insert into #PART2_P 
		select 1, 'отработано дней', '',
			max(case when month_begin = 1 then days else 0 end),
			max(case when month_begin = 2 then days else 0 end),
			max(case when month_begin = 3 then days else 0 end),
			max(case when month_begin = 4 then days else 0 end),
			max(case when month_begin = 5 then days else 0 end),
			max(case when month_begin = 6 then days else 0 end),
			max(case when month_begin = 7 then days else 0 end),
			max(case when month_begin = 8 then days else 0 end),
			max(case when month_begin = 9 then days else 0 end),
			max(case when month_begin = 10 then days else 0 end),
			max(case when month_begin = 11 then days else 0 end),
			max(case when month_begin = 12 then days else 0 end)
		from s_j_c 
		where  
			link_empl IS NULL AND  PERS_LINK = @varKSnLinkPers
			and year_begin = @varKSnYear
			and typ_oper = 1 /*and (way_calc = 1 or way_calc = 2)*/

		insert into #PART2_P 
		select 2, 'всего начислено', '',
			sum(case when month_begin = 1 then summa else 0 end),
			sum(case when month_begin = 2 then summa else 0 end),
			sum(case when month_begin = 3 then summa else 0 end),
			sum(case when month_begin = 4 then summa else 0 end),
			sum(case when month_begin = 5 then summa else 0 end),
			sum(case when month_begin = 6 then summa else 0 end),
			sum(case when month_begin = 7 then summa else 0 end),
			sum(case when month_begin = 8 then summa else 0 end),
			sum(case when month_begin = 9 then summa else 0 end),
			sum(case when month_begin = 10 then summa else 0 end),
			sum(case when month_begin = 11 then summa else 0 end),
			sum(case when month_begin = 12 then summa else 0 end)
		from s_j_c where link_empl IS NULL AND  PERS_LINK = @varKSnLinkPers
			and year_begin = @varKSnYear
			and typ_oper = 1


		
		insert into #PART2_P 
		select 4, 'всего удержано', '',
			sum(case when month_begin = 1 then summa else 0 end),
			sum(case when month_begin = 2 then summa else 0 end),
			sum(case when month_begin = 3 then summa else 0 end),
			sum(case when month_begin = 4 then summa else 0 end),
			sum(case when month_begin = 5 then summa else 0 end),
			sum(case when month_begin = 6 then summa else 0 end),
			sum(case when month_begin = 7 then summa else 0 end),
			sum(case when month_begin = 8 then summa else 0 end),
			sum(case when month_begin = 9 then summa else 0 end),
			sum(case when month_begin = 10 then summa else 0 end),
			sum(case when month_begin = 11 then summa else 0 end),
			sum(case when month_begin = 12 then summa else 0 end)
		from s_j_c where link_empl IS NULL AND  PERS_LINK = @varKSnLinkPers
			and year_begin = @varKSnYear
			and typ_oper = 2 
			and link_doc not in (
				select link from DOCUMENTS_DED_PR_DGH 
				where year_base = @varKSnYear

					and flag_jc = 1
					and TYP_PAYMENT = 1
			)



	-----Начисленные суммы
		CREATE TABLE #SJ_P (typ_oper TINYINT , month_begin TINYINT, LINK_PAYS INT, NAME_PAYS VARCHAR(254), CODE_PAYS  varchar(10), SUMMA NUMERIC(18,2))
		INSERT INTO #SJ_P (typ_oper, month_begin, LINK_PAYS, NAME_PAYS, CODE_PAYS, SUMMA)
		SELECT P.[OBJECT], MONTH(J.PERIOD_BEGIN), ISNULL(P1.LINK,P.LINK), ISNULL(P1.NAME,P.NAME), ISNULL(P1.CODE,P.CODE), SUMMA
		from 
			dbo.CALCULATE_JURNAL J
			INNER JOIN dbo.PAYS P ON P.LINK = J.LINK_PAYS
			LEFT JOIN dbo.PAYS P1 ON P1.LINK = P.LINK_MPAY AND @nCheck1 = 1
		where 
			link_empl IS NULL
			AND  PERS_LINK = @varKSnLinkPers
			and YEAR(J.PERIOD_BEGIN) = @varKSnYear
			and P.[OBJECT] in(1, 2)
			and link_doc not in (
				select link from DOCUMENTS_DED_PR_DGH 
				where year_base = @varKSnYear
					and flag_jc = 1
					and TYP_PAYMENT = 1
			)
		--
		UPDATE R
		SET NAME_PAYS = NAME_PAYS + '*', CODE_PAYS = CODE_PAYS + '*'
		FROM
			#SJ_P R
			INNER JOIN dbo.PAYS P on P.LINK_MPAY = R.LINK_PAYS
		--	
		insert into #PART2_P 
		select 
			case when typ_oper = 1 then 3 else 5 end, 
			name_pays, code_pays,
			sum(case when month_begin = 1 then summa else 0 end),
			sum(case when month_begin = 2 then summa else 0 end),
			sum(case when month_begin = 3 then summa else 0 end),
			sum(case when month_begin = 4 then summa else 0 end),
			sum(case when month_begin = 5 then summa else 0 end),
			sum(case when month_begin = 6 then summa else 0 end),
			sum(case when month_begin = 7 then summa else 0 end),
			sum(case when month_begin = 8 then summa else 0 end),
			sum(case when month_begin = 9 then summa else 0 end),
			sum(case when month_begin = 10 then summa else 0 end),
			sum(case when month_begin = 11 then summa else 0 end),
			sum(case when month_begin = 12 then summa else 0 end)
		from #SJ_P
		group by 
			case when typ_oper = 1 then 3 else 5 end, 
			name_pays, code_pays


		insert into #PART2_P 
		select 6, 'сумма к выдаче', '',
			sum(case when month_base = 1 then d1.summa else 0.00 end),
			sum(case when month_base = 2 then d1.summa else 0.00 end),
			sum(case when month_base = 3 then d1.summa else 0.00 end),
			sum(case when month_base = 4 then d1.summa else 0.00 end),
			sum(case when month_base = 5 then d1.summa else 0.00 end),
			sum(case when month_base = 6 then d1.summa else 0.00 end),
			sum(case when month_base = 7 then d1.summa else 0.00 end),
			sum(case when month_base = 8 then d1.summa else 0.00 end),
			sum(case when month_base = 9 then d1.summa else 0.00 end),
			sum(case when month_base = 10 then d1.summa else 0.00 end),
			sum(case when month_base = 11 then d1.summa else 0.00 end),
			sum(case when month_base = 12 then d1.summa else 0.00 end)
		from DOCUMENTS_DED_PR_DGH d inner join DOCUMENTS_DED_PR_TABLE_DGH d1
			on (d.link = d1.link and d1.PERS_LINK = @varKSnLinkPers 
				and year_base = @varKSnYear
				and flag_jc = 1
				and TYP_PAYMENT = 1)

		SELECT *,
			@varKSCODE_FKR_D AS CODE_FKR_D, @varKSNAME_FKR_D AS NAME_FKR_D,
			@varKSCODE_FKR_T AS CODE_FKR_T, @varKSNAME_FKR_T AS NAME_FKR_T,
			@varKSCODE_FKR_E AS CODE_FKR_E, @varKSNAME_FKR_E AS NAME_FKR_E
		FROM #PART1_P

		EXEC ('
			SELECT * 
			INTO ' + @varKSTMP2_P + ' 
			FROM #TMP2_P T2 LEFT OUTER JOIN ' + @varKSPAYS_PERS + ' PE
			ON T2.ID = PE.PARENT_ID
		')	
	 
		DECLARE @varKSCNT_PAYS_P INT, @varKSFIELD_NAME_P VARCHAR(254), @varKSSQL_STR_P VARCHAR(8000), @varKSI_P INT
		SELECT @varKSCNT_PAYS_P = COUNT(DISTINCT CP) FROM #PAYS_PERS
		SET @varKSI_P=1
		WHILE @varKSI_P <= @varKSCNT_PAYS_P BEGIN
			SET @varKSFIELD_NAME_P = 'CP_' + RTRIM(LTRIM(STR(@varKSI_P))) 
			SET @varKSSQL_STR_P= ' UPDATE ' + @varKSTMP2_P + '  SET '+@varKSFIELD_NAME_P+ ' = (SELECT TOP 1 '+@varKSFIELD_NAME_P + ' FROM ' + @varKSPAYS_PERS + ' WHERE '+
				@varKSFIELD_NAME_P+ '  IS NOT NULL ) ' 
			EXEC (@varKSSQL_STR_P)
			SET @varKSFIELD_NAME_P= 'NP_'  +  RTRIM(LTRIM(STR(@varKSI_P)))  + '_'  +  RTRIM(LTRIM(STR(@varKSI_P))) 
			SET @varKSSQL_STR_P= ' UPDATE ' + @varKSTMP2_P + '  SET '+@varKSFIELD_NAME_P+ ' = (SELECT TOP 1 '+@varKSFIELD_NAME_P + ' FROM ' + @varKSPAYS_PERS + ' WHERE '+
				@varKSFIELD_NAME_P+ '  IS NOT NULL ) ' 
			EXEC (@varKSSQL_STR_P)
			SET @varKSFIELD_NAME_P= 'S_'  +  RTRIM(LTRIM(STR(@varKSI_P)))  + '_'  +  RTRIM(LTRIM(STR(@varKSI_P))) 
			SET @varKSSQL_STR_P= ' UPDATE '+@varKSTMP2_P + '  SET '+@varKSFIELD_NAME_P+ ' = 0  WHERE ' +
				@varKSFIELD_NAME_P+ '  IS  NULL ' 

			SET @varKSI_P=@varKSI_P+1
		END

		IF @varKSCNT_PAYS_P >= 1 AND @varKSCNT_PAYS_P < 9  BEGIN
			SET @varKSDELTA_P = 9 - @varKSCNT_PAYS_P
			SET @varKSI_P = 1
			WHILE @varKSI_P <= @varKSDELTA_P BEGIN
				SET @varKSSQL_STR_P= 'ALTER TABLE '  + @varKSTMP2_P + 
				'  ADD CP_' + LTRIM(STR(@varKSCNT_PAYS_P + @varKSI_P)) + '  VARCHAR(10), 
				NP_' + LTRIM(STR(@varKSCNT_PAYS_P + @varKSI_P)) + '_' + LTRIM(STR(@varKSCNT_PAYS_P + @varKSI_P)) + ' VARCHAR(254), 
				S_' + LTRIM(STR(@varKSCNT_PAYS_P + @varKSI_P)) + '_' + LTRIM(STR(@varKSCNT_PAYS_P + @varKSI_P)) + '  NUMERIC(20,2) '
				EXEC (@varKSSQL_STR_P)
				SET @varKSI_P=@varKSI_P+1
			END
		END

		IF @varKSCNT_PAYS_P = 0 BEGIN
			SET @varKSSQL_STR_P= 
				'ALTER TABLE '  + @varKSTMP2_P + 
				'  ADD CP_0  VARCHAR(10), 
				NP_0_0 VARCHAR(254), 
				S_0_0  NUMERIC(20,2) '
				EXEC (@varKSSQL_STR_P)
		END


		EXEC( 'SELECT *, ITOGOZP = NULL 
		FROM ' + @varKSTMP2_P + ' ORDER  by ID, REAL_REC DESC, ORDER_DATE ASC')
	/*
		EXEC( 'SELECT *, ITOGOZP = (SELECT SUM(S) FROM #PAYS_EMPL WHERE ORDER_DATE BETWEEN DATE_BEGIN AND COALESCE(DATE_END,''29990101'')) 
		FROM ' + @varKSTMP2 + ' ORDER BY REAL_REC DESC, ORDER_DATE ASC')
	*/
		SELECT * 
		FROM #TMP_3_P INNER JOIN #TMP_DED_P ON #TMP_3_P.ID = #TMP_DED_P.ID
		ORDER BY #TMP_3_P.REAL_REC DESC, ORD_DATE

		select * from #part2_P
		order by mode, code


		EXEC ('DROP TABLE ' + @varKSPAYS_PERS )
		EXEC ('DROP TABLE ' + @varKSTMP2_P )
	
	
	END
END













GO


GRANT EXECUTE ON dbo.[SD_REP_F417] TO PUBLIC

GO




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

GO
-- Выгрузка бухгалтерских операций (МинЗдрав РФ 2013) --
CREATE PROCEDURE dbo.BK_EXPORT_AHD_PROV
	@dDate1		DATETIME = NULL,
	@dDate2		DATETIME = NULL,
	@iExport	TINYINT	= NULL
AS
BEGIN
	DECLARE 
		@F_NAME	VARCHAR (100)

	-- Данные Учреждения
	IF OBJECT_ID('tempdb..#DEPARTMENTS') IS NOT NULL 
		DROP TABLE #DEPARTMENTS

	CREATE TABLE #DEPARTMENTS(
		LINK	INT
		,KPP	VARCHAR(9)
		,INN	VARCHAR(13)
		,NAME	VARCHAR(254)
		,[TYPE] VARCHAR(60)
		)

	INSERT INTO #DEPARTMENTS  
		(
		LINK
		,KPP
		,INN
		,NAME
		,[TYPE]
		)
	SELECT 
		LINK	= D.LINK
		,KPP	= D.KPP
		,INN	= D.INN
		,NAME	= D.NAME
		,[type]	= DBT.BT_NAME1
	FROM dbo.DEPARTMENTS D
	INNER JOIN dbo.DICTIONARY_BUH_TYPE DBT ON (DBT.BUH_TYPE = D.BUH_TYPE)
	WHERE d.LINK = ISNULL (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())

-- SELECT * FROM #DEPARTMENTS
	
	-- Операции --
	IF OBJECT_ID('tempdb..#OPER') IS NOT NULL 
		DROP TABLE #OPER
		
	CREATE TABLE #OPER
		(
		ID				INT IDENTITY
		,[Date]			DATETIME
		,Summa			NUMERIC(28,2)
		,FS_CODE		VARCHAR(1)
		,D_CODE			VARCHAR(13)	
		,D_KBK			VARCHAR(30)
		,D_SGU			VARCHAR(3)
		,K_CODE			VARCHAR(13)	
		,K_KBK			VARCHAR(30)
		,K_SGU			VARCHAR(3)
		,DEP			INT
		,[Description]	VARCHAR(254)
		)

	CREATE INDEX #IDX_REST ON #OPER(ID)

	INSERT INTO #OPER 
		([Date]
		,Summa
		,FS_CODE
		,D_CODE
		,D_KBK
		,D_SGU
		,K_CODE
		,K_KBK
		,K_SGU
		,DEP
		,[Description]	
		)
		
	SELECT
		[Date]			= GP.DATE_PROV	
		,SUMMA			= SUM (GP2.SUMMA)
		,FS_CODE		= D_SA.cSOURCE
		,D_CODE			= RTRIM (D_SA.cSinth)
							+ CASE
									WHEN D_SA.cAnalit <> '' THEN '.' + D_SA.cAnalit
									ELSE ''
								END
		,D_KBK			= ISNULL (D_KK.CODE, '00000000000000000')
		,D_SGU			= ISNULL(D_K.CODE, '000')
		,K_CODE			= RTRIM (K_SA.CsINTH)
							+ CASE
									WHEN K_SA.cAnalit <> '' THEN '.' + K_SA.cAnalit
									ELSE ''
							END

		,K_KBK			= ISNULL (K_KK.CODE, '00000000000000000')
		,K_SGU			= ISNULL(K_K.CODE, '000')
		,DEP			= GP.DEP
		,[Description]	= MAX(XO.NAME)
	--,DB_KR			= gpa.DB_KR
	FROM dbo.G_PROV GP
	INNER JOIN #DEPARTMENTS D ON D.LINK = GP.DEP
	INNER JOIN dbo.S_OBJECTS SO ON (SO.LINK = GP.[OBJECT])
	INNER JOIN dbo.G_PROV1 GP1 ON GP1.LINK_UP = GP.LINK
	INNER JOIN dbo.G_PROV2 GP2 ON GP2.LINK_UP = GP1.LINK
		AND GP2.STORNO = 0
	LEFT  JOIN dbo.XOZ_OPER XO ON XO.LINK = GP2.ECON_OPER
	INNER JOIN dbo.G_PROV_AP GPA_D ON GPA_D.LINK_UP = GP2.LINK AND GPA_D.DB_KR = 0
	INNER JOIN dbo.S_ACCOUNTS D_SA ON D_SA.LINK = GPA_D.ACCOUNT
	INNER JOIN dbo.G_PROV_AP GPA_K ON GPA_K.LINK_UP = GP2.LINK AND GPA_K.DB_KR = 1
	INNER JOIN dbo.S_ACCOUNTS K_SA ON K_SA.LINK = GPA_K.ACCOUNT

	LEFT JOIN dbo.KL_KBK D_KK ON D_KK.LINK = GPA_D.KBK 
	LEFT JOIN dbo.KL_KBK K_KK ON K_KK.LINK = GPA_K.KBK 
	LEFT JOIN dbo.KOSGU D_K ON D_K.LINK = GPA_D.SGU 
	LEFT JOIN dbo.KOSGU K_K ON K_K.LINK = GPA_K.SGU 

	WHERE GP.DATE_PROV BETWEEN @dDate1 AND @dDate2
		AND SO.CODE <> 'SHABLON_DOCUMENTS_PROV'
	--GROUP BY gp.DATE_PROV,d_sa.cSource,d_sa.cSinth,d_sa.cAnalit,d_kk.CODE,d_k.CODE,k_sa.cSinth,k_sa.cAnalit,k_kk.CODE,k_k.CODE,gp.DEP,sgu_d.CODE,sgu_k.CODE
	GROUP BY
		GP.DATE_PROV,
		D_SA.cSOURCE,
		D_SA.cSinth,
		D_SA.cAnalit,
		K_SA.cSinth,
		K_SA.cAnalit,
		D_KK.CODE, 
		D_K.CODE,
		K_KK.CODE, 
		K_K.CODE,
		GP.DEP

-- select * from #OPER

	IF ISNULL (@iExport, 0) = 1
	BEGIN 
		IF OBJECT_ID('tempdb..#OUT') IS NOT NULL 
			DROP TABLE #OUT

		CREATE TABLE #OUT (ID INT IDENTITY, TXT VARCHAR(8000))

		INSERT INTO #OUT (TXT)
		SELECT
			'UTF-8'

		INSERT INTO #OUT (TXT)
		SELECT 
		'<?xml version="1.0" encoding="UTF-8"?>
		<Exchange version="1.0">
			<Operation Version="1.0" date="'+CONVERT(VARCHAR(30),@dDate2,126) +'" period="Месяц" TypeOperation="Обороты">
				<Organization INN="'+ISNULL(d.INN,'')+'" KPP="'+ISNULL(d.KPP,'')+'">
					<Name>'+ISNULL(d.NAME,'')+'</Name>
					<type>'+ISNULL(d.[TYPE],'')+'</type>
				</Organization>'
		FROM #DEPARTMENTS d

		INSERT INTO #OUT (TXT)
		SELECT 
		'
		<Record ID="'+ CONVERT(VARCHAR(30),o.ID) +'" Date="'+CONVERT(VARCHAR(30),o.Date,126)+'">
			<KFO>' + ISNULL (o.FS_CODE, '') + '</KFO>
			<Schet_Dt Cod="' + ISNULL (o.D_CODE, '') + '" KPS="' + REPLACE (o.D_KBK, '.', '') + '" KEK="' + ISNULL (o.D_SGU, '000')+'"/>
			<Schet_Kt Cod="' + ISNULL (o.K_CODE, '') + '" KPS="' + REPLACE (o.K_KBK, '.', '') + '" KEK="' + ISNULL (o.K_SGU, '000')+'"/>
			<Summa>' + ISNULL (convert (varchar(30), o.Summa), '0') + '</Summa>
			<Description>' + ISNULL (o.[Description], 'Операция') + '</Description>
		</Record>'
		FROM #OPER o
		ORDER BY o.Date

		INSERT INTO #OUT (TXT)
		SELECT 
		'
			</Operation>
		</Exchange>'

		EXEC dbo.GetRandStr 15, @F_NAME OUTPUT
		
		SELECT 
			@F_NAME = 'PROV_'+ ISNULL(RTRIM (D.INN),'') + '_' + ISNULL(RTRIM (D.KPP),'') +
						'_' + ISNULL(CONVERT(VARCHAR(30), @dDate1, 112),'') + '_' + @F_NAME + '.xml'
		FROM #DEPARTMENTS d

		SELECT
			R.ID,
			ENCODING	= 'UTF-8',
			OUT_TEXT	= R.TXT 
			,[F_NAME]	= @F_NAME
		FROM #OUT R
		ORDER BY R.ID
		
		DROP TABLE #OUT
	END
	ELSE
 		SELECT
 			[version]		= '1.0',
 			DATE1	=	@dDate1,
			DATE2	=	@dDate2
 			,period			= 'Месяц'
 			,TypeOper		= 'Обороты'
 			,DEP_INN		= D.INN 
 			,DEP_KPP		= D.KPP
 			,DEP_NAME		= D.NAME
 			,DEP_TYPE		= D.[TYPE]
 			,ID				= R.ID
 			,DATE_OPER		= R.[Date]
 			,R.FS_CODE
 			,R.D_CODE
 			,R.D_KBK
 			,R.D_SGU
 			,R.K_CODE
 			,R.K_KBK
 			,R.K_SGU
 			,R.Summa
 			,Comment	= ISNULL (R.[Description], 'Операция')
 		FROM #DEPARTMENTS d
 		INNER JOIN #OPER r ON r.DEP = d.LINK

	 DROP TABLE #DEPARTMENTS
	 DROP TABLE #OPER
	 
END
 






GO


GRANT EXECUTE ON dbo.[BK_EXPORT_AHD_PROV] TO PUBLIC

GO




GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if EXISTS (SELECT * 
           FROM dbo.SYSOBJECTS 
           WHERE [ID] = OBJECT_ID(N'dbo.[RA_IMPORT_FORM_128]') AND 
                 OBJECTPROPERTY([ID], N'IsProcedure') = 1)
BEGIN
   DROP PROCEDURE dbo.[RA_IMPORT_FORM_128]
END
GO

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

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

*******************************************************************************/
CREATE PROCEDURE dbo.[RA_IMPORT_FORM_128]
	@lbSvodWEB	     BIT     = 1,    -- 1 - Вызов с тонкого клиента, 0 - иначе.
	@liRepeatRequest INT     = NULL, -- Если IS NOT NULL - повторный вызов из Свод-WEB, если >0 - то подтверждение загрузки, <0 - импорт отклонен.
   @tIsAppend       TINYINT = 0,    -- 1 - Импорт отчета в режиме добавления, 0 - обычный импорт.
	@bDinamicRows    BIT     = 0,    -- Строки даже для статических таблиц хранятся динамически (для 14-х форм)
   @iLINK_SELF      INT     = NULL,
   @tMode           TINYINT = 0 -- Режим работы 0 - обычный, 1 - демо.
AS
SET NOCOUNT ON

DECLARE @liORDER     INT,
        @liORDER_RD5 INT,
        @i           INT,
        @iOrder      INT,
        @iOrder2     INT,
        @liReturn    INT,
        @vcText      VARCHAR(8000)
        

IF ISNULL(@liRepeatRequest,0) > 0 OR
   EXISTS (SELECT *
           FROM #IMPORT_TABLE
           WHERE [TXT] IN ('ВФ=0','ВФ=1'))

BEGIN
   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode

   RETURN @liReturn
END

IF NOT EXISTS (SELECT *
               FROM #IMPORT_TABLE
               WHERE [TXT] IN ('ВФ=0','ВФ=1'))
BEGIN
   SELECT @vcText = [TXT],
          @iOrder = [ORDER]
   FROM #IMPORT_TABLE
   WHERE [TXT] LIKE '999|***|****|****|**|****|***|%'

   IF @vcText IS NULL
   BEGIN
      SELECT @vcText = [TXT],
             @iOrder = [ORDER]
      FROM #IMPORT_TABLE
      WHERE [TXT] LIKE '999|*****************%'
   END

   DELETE  #IMPORT_TABLE   
   WHERE [ORDER] = @iOrder OR
         [ORDER] >= (SELECT MAX([ORDER])
                    FROM #IMPORT_TABLE
                    WHERE [TXT] = '#&')

   IF @vcText is NOT NULL
   BEGIN     
      INSERT #IMPORT_TABLE([TXT]) VALUES ('#@')   
      INSERT #IMPORT_TABLE([TXT]) VALUES ('ТБ=04')
      INSERT #IMPORT_TABLE([TXT]) VALUES ('#$')
      INSERT #IMPORT_TABLE([TXT]) VALUES (@vcText)
   END

 --  select * from #IMPORT_TABLE order by [order]

   EXEC @liReturn = dbo.[RA_IMPORT_FORM_STANDART] @lbSvodWEB,
                                                  @liRepeatRequest,
                                                  @tIsAppend,
                                                  @bDinamicRows,
                                                  @iLINK_SELF,
                                                  @tMode
   --select * from #IMPORT_TABLE
END


RETURN @liReturn

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

/*
select * from report_forms where exportcode='225'

update report_forms set exportcode='' where code='0503125'

SELECT * FROM tabTest


LEFT(RTRIM(isnull(dbo.[RA_GETWORDNUM]([TXT],2,'|'),''))+'000',3)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],3,'|'),''))+'        ',8)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],4,'|'),''))+'  ',2)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],5,'|') + dbo.[RA_GETWORDNUM]([TXT],6,'|') + dbo.[RA_GETWORDNUM]([TXT],7,'|'),''))+'         ',9)+
LEFT(RTRIM(ISNULL(dbo.[RA_GETWORDNUM]([TXT],8,'|') + dbo.[RA_GETWORDNUM]([TXT],9,'|') + dbo.[RA_GETWORDNUM]([TXT],10,'|'),''))+'         ',9)

*/

GO




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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE      PROCEDURE dbo.BK_PRINT_INV_CARD_F0504031
	@varKSc_BufferName	VARCHAR (100)
AS
BEGIN
	DECLARE	@varKSintLINK	INT,
		@varKSnCALC_RATE	NUMERIC (28,4),
		@varKSdDATE_WORK	DATETIME,
		@varKSdDATE_REST	DATETIME,
		@varKSACCT_CODE	VARCHAR (20),
		@varKSDEP		INT,
		@varKSDEP_CODE	VARCHAR (20),
		@varKSDEP_OKPO	VARCHAR (20),
		@varKSDEP_NAME	VARCHAR (254),
		@varKSEMP		INT,
		@varKSEMP_CODE	VARCHAR (20),
		@varKSEMP_NAME	VARCHAR (254),
		@varKSSUB_CODE	VARCHAR (20),
		@varKSSUB_NAME	VARCHAR (254),
		@varKSKBK	INT,
		@varKSACCT	INT,
		@nBALANSE	NUMERIC (28,4),
		@BEGIN_DATE_USED DATETIME,
		@DATE_CALC_REST_AMORT	DATETIME,
		@DATE_AMORT	DATETIME,
		@SUMMA_AM	NUMERIC (28, 4),
		@REST_SUMMA_AM	NUMERIC (28, 4),
		@PREV_SUMMA_AM	NUMERIC (28, 4),
		@YEAR_AM	INT,
		@LAST_RECNO	INT,
		@ACCOUNT_AM	INT,

		@PRN_MOVE_EMP	INT,

		@dDATE_RECALC DATETIME,
		@nSUM_RECALC NUMERIC (28,4),
		@cINFO_RECALC VARCHAR (254)

	SELECT TOP 1 @varKSintLINK = LINK
		FROM dbo.BufferGetTableByID (@varKSc_BufferName)

--	SELECT @varKSdDATE_WORK = DATEADD (DAY, 1, WORKDATE) FROM USER_INFO
	SELECT @varKSdDATE_WORK = WORKDATE FROM dbo.USER_INFO
	SET @varKSdDATE_REST = DATEADD (DAY, 1, @varKSdDATE_WORK) 

	DECLARE @varKSINV_REST TABLE
			(ACCOUNT INT,
			ACCT_SINT VARCHAR (10),
			ACCT_CODE VARCHAR (20),
			DEP INT,
			SUB INT,
			EMP INT,
			INV INT,
			KBK INT,
			SUMMA NUMERIC (28,4))

	INSERT INTO @varKSINV_REST
	SELECT --*
		T1.ACCOUNT,
		SA.cSinth,
		SA.CODE,
		T1.DEP,
		T1.SUB,
		T1.EMP,
		T1.INV,
		T1.KBK,
		CASE 
			WHEN SA.S_ACTIVE = 1 THEN SUM (T1.D_SUMMA)
			WHEN SA.S_PASSIVE = 1 THEN SUM (T1.K_SUMMA)
		END
	FROM dbo.ARestTableByDate (@varKSdDATE_REST, DEFAULT) T1
	INNER JOIN dbo.S_ACCOUNTS SA ON (T1.ACCOUNT = SA.LINK)
	INNER JOIN dbo.BufferGetTableByID (@varKSc_BufferName) BUF ON (BUF.LINK = T1.INV)
--	WHERE T1.INV = @varKSintLINK
	GROUP BY T1.ACCOUNT, T1.DEP, T1.SUB, T1.EMP, T1.INV, T1.KBK, SA.S_ACTIVE, SA.S_PASSIVE, SA.cSinth, SA.CODE

--SELECT * FROM @varKSINV_REST
--SELECT * FROM dbo.ARestTableByDate ('20140101', DEFAULT) T1

	
	SELECT TOP 1
		@varKSACCT_CODE = ACCT_CODE,
		@varKSDEP = DEP.LINK,
		@varKSDEP_CODE = DEP.CODE,
		@varKSDEP_NAME = DEP.NAME, 
		@varKSDEP_OKPO = DEP.OKPO,
		@varKSEMP = EMP.LINK,
		@varKSEMP_CODE = EMP.TAB,
		@varKSEMP_NAME = EMP.NAME_EMPL,
		@varKSSUB_CODE	= SUB.CODE,
		@varKSSUB_NAME	= SUB.[NAME],
		@nBALANSE = SUMMA,
		@varKSKBK = KBK,
		@varKSACCT = T1.ACCOUNT
	FROM @varKSINV_REST T1
	LEFT OUTER JOIN dbo.DICTIONARY_DEPARTMENT DEP ON (DEP.LINK = T1.DEP)
	LEFT OUTER JOIN dbo.KU_EMPL_PLACING EMP ON (EMP.LINK = T1.EMP)
	LEFT OUTER JOIN dbo.DICTIONARY_SUBDIVISION SUB ON (SUB.LINK = T1.SUB)
	WHERE
		T1.ACCT_SINT = '101'
		OR T1.ACCT_SINT = '102'
		OR T1.ACCT_SINT = '103'
		OR T1.ACCT_SINT = '108'

	IF @varKSDEP IS NULL
		SELECT TOP 1
			@varKSDEP = DEP.LINK,
			@varKSDEP_CODE = DEP.CODE,
			@varKSDEP_NAME = DEP.NAME, 
			@varKSDEP_OKPO = DEP.OKPO
		FROM dbo.DICTIONARY_DEPARTMENT DEP 
		WHERE DEP.LINK = COALESCE (dbo.BK_GetDepZB (), dbo.GetOwnDepLink ())

	SELECT @varKSnCALC_RATE = SUM (SUMMA)
	FROM @varKSINV_REST T1
	WHERE T1.ACCT_SINT = '104'


	--- вычисляем балансовую стоимость 
	DECLARE @nBALANSE_R NUMERIC(18,2)
	SELECT @nBALANSE_R = SUM (BALANS)
	 FROM dbo.BK_GetTableRestINV (@varKSdDATE_WORK, @varKSintLINK, @varKSDEP)
	GROUP BY INV,
		ACCOUNT_B,
		ACCOUNT_A	
	


	-- Вычисляем переоценку --
	DECLARE @TAB_RECALL TABLE (REC_NO INT IDENTITY, DATE_OPER2 VARCHAR (10), dDATE_OPER DATETIME,
		JO_NUM2 VARCHAR (20), SUMMA2 NUMERIC (20,2), NAME2 VARCHAR(100), DOC_NUM2 VARCHAR (30) )

	INSERT INTO @TAB_RECALL	
	SELECT CONVERT (VARCHAR (10), a.DATE_OPER, 104) AS DATE_OPER2, a.DATE_OPER,
		CONVERT (VARCHAR (20), RTRIM (a.JO_NUM) + '(баланс)') AS JO_NUM2,
		a.SUMMA AS SUMMA2,
		left(s.NAME,100) AS NAME2,
		CONVERT (VARCHAR (20), RTRIM (a.DOC_NUM) + '(баланс)') AS DOC_NUM2
	FROM dbo.BK_GetOperationsByOS (@varKSintLINK, @varKSdDATE_WORK,
		'17.15#17.16#17.17#17.18') a  -- Переоценка ОС
	INNER JOIN G_PROV2 g2 ON  g2.LINK = a.LINK_G2
	INNER JOIN G_PROV1 g1 ON g1.LINK = g2.LINK_UP
	INNER JOIN G_PROV g ON g.LINK = g1.LINK_UP
	INNER JOIN S_OBJECTS s ON s.LINK = g.[OBJECT]-- Переоценка ОС


	IF @@ROWCOUNT = 0
		INSERT INTO @TAB_RECALL	 (DATE_OPER2, JO_NUM2, SUMMA2,NAME2, DOC_NUM2) VALUES ('', '', 0,'','')
	ELSE
	BEGIN

		SELECT TOP 1 @dDATE_RECALC = dDATE_OPER FROM @TAB_RECALL
		IF @dDATE_RECALC IS NOT NULL AND @dDATE_RECALC <= @varKSdDATE_WORK
		BEGIN
			SET @dDATE_RECALC = DATEADD (DAY, 1, @dDATE_RECALC)
			SELECT @nSUM_RECALC = SUM (D_SUMMA)
			FROM dbo.ARestTableByDate (@dDATE_RECALC, DEFAULT) TR
			INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = TR.ACCOUNT)
			WHERE SA.cSINTH = '101'
				AND TR.INV = @varKSintLINK

			IF ISNULL (@nSUM_RECALC, 0) > 0 
				SET @cINFO_RECALC = 'Стоимость после переоценки на '
					+ CONVERT (VARCHAR (10), @dDATE_RECALC, 104) + ' г. '
		END
	END

	SELECT @varKSDEP AS DEP,
		CONVERT (VARCHAR (10), @varKSdDATE_WORK, 104) AS REP_DATE,
		ISNULL (@varKSDEP_CODE, '') AS DEP_CODE,
		ISNULL (@varKSDEP_OKPO, '') AS DEP_OKPO,
		ISNULL (@varKSDEP_NAME, '') AS DEP_NAME,
		ISNULL (@varKSEMP_CODE, '') AS EMP_CODE,
		ISNULL (@varKSEMP_NAME, '') AS EMP_NAME,
		ISNULL (@varKSSUB_CODE, '') AS SUB_CODE,
		ISNULL (@varKSSUB_NAME, '') AS SUB_NAME,
		
		ISNULL (@cINFO_RECALC, '') AS INFRECALC,
		ISNULL (@nSUM_RECALC, 0) AS SUMRECALC,

		T1.LINK,
		ISNULL (T1.CODE, '') AS INV_CODE,
		ISNULL (T1.NAME, '') AS INV_NAME,
		ISNULL (dbo.BK_GetAcctFullCode1 (@varKSACCT, @varKSKBK, NULL, 1, 0), ISNULL (T1.CODE_ACC, '')) AS ACCT_CODE,
		ISNULL (T1.BALANCE, 0)	 AS FIRST_COST,
		ISNULL (@nBALANSE_R, 0)	 AS BALANSE_R,
		GRP_TYPE = case when LEFT(ISNULL(T1.CODE_GRP,''),4) = '1011' then 'недвижимое имущество'
						WHEN LEFT(ISNULL(T1.CODE_GRP,''),4) = '1012' then 'особо ценное движимое имущество' 
						WHEN LEFT(ISNULL(T1.CODE_GRP,''),4) = '1013' then 'иное движимое имущество' 
						else '' END ,
		ISNULL (T2.CARD_NO, '') AS CARD_NO,
		ISNULL (T2.PASSPORT, '') AS PASSPORT,
		ISNULL (T2.PLANT_NUM, '') AS PLANT_NUM,
		ISNULL (T2.OTHER_NUM, '') AS OTHER_NUM,
		ISNULL (T2.CODE_OKOF, '') AS CODE_OKOF,
		ISNULL (CONVERT (VARCHAR (10), T2.DATE_PROD, 104), '') AS DATE_PROD,
		ISNULL (T2.FIXING, '') AS FIXING,
		ISNULL (T2.LOCATION, '') AS LOCATION,
		ISNULL (T2.MANUFACT, '') AS MANUFACT,		
		ISNULL (CONVERT (VARCHAR (10), T2.DATE_BEGIN, 104), '') AS DATE_BEGIN,
		ISNULL (T2.DOC_NUM, '') AS DOC_BEGIN,
		ISNULL (CONVERT (VARCHAR (10), T2.DATE_FILLING, 104), '') as DATE_FILL,
		(SELECT  top 1 (case when CONVERT (VARCHAR (10), DATE_OPER, 104) = '01.01.1900' then '' else CONVERT (VARCHAR (10), DATE_OPER, 104) END)   FROM dbo.BK_GetDateTableOutOS(@varKSintLINK, DEFAULT))  as DATE_END,
		CASE
			WHEN T2.D_DT_CALC IS NULL THEN ISNULL (T2.PERIOD_USED, 0)
			ELSE (ISNULL (T2.PER_USED, 0)
--				+ ROUND((CONVERT (NUMERIC (19,2), ISNULL((T2.D_DT_CALC - T2.DATE_BEGIN), 0)) / 365.25), 0)
				+ DATEDIFF (MONTH, T2.DATE_BEGIN, T2.D_DT_CALC) - 1)/ 12
		END AS PER_USED,
		ISNULL (T2.D_GRP_CODE, ISNULL (T2.CODE_RATE, ISNULL (T4.CODE, ''))) AS CODE_RATE,
		CASE
			WHEN T2.WEAR_FLAG = 2 THEN CONVERT (NUMERIC (10,2), 0)
			ELSE ISNULL (ND.DEPRE_RATE, 0)
		END AS DEPRE_Y_R,
		CASE
			WHEN T2.WEAR_FLAG = 2 THEN CONVERT (NUMERIC (10,2), 0)
			ELSE CONVERT (NUMERIC (10,2), ISNULL (ND.DEPRE_RATE/12, 0)) 
		END AS DEPRE_M_R,
		CASE
			WHEN T2.WEAR_FLAG = 2 THEN CONVERT (NUMERIC (28,2), 0)
			ELSE CONVERT (NUMERIC (28,2), ISNULL (@nBALANSE * ND.DEPRE_RATE / 100, 0))
		END AS SUM_Y_N,
		CASE
			WHEN T2.WEAR_FLAG = 2 THEN CONVERT (NUMERIC (28,2), 0)
			ELSE CONVERT (NUMERIC (28,2), ISNULL (ND.DEPRE_RATE / 100 / 12 * @nBALANSE, 0))
		END AS SUM_M_N,
		isnull(t2.WEAR_FLAG,0) AS WEAR_FLAG,
		ISNULL (@varKSnCALC_RATE, 0) AS SUM_RATE,
		ISNULL (EMP.NAME_EMPL, '') AS FIL_NAME,
		ISNULL (EMP.POST_NAME, '') AS FIL_POST,
		ISNULL (CONVERT (VARCHAR (10), DATE_FILLING, 104), '') AS FIL_DATE,
		ISNULL (dbo.DateMonthName (month (dbo.CalcLastDateWearOS (T1.LINK)))
			+ SPACE (1) + LTRIM (STR (dbo.CalcLastYearWearOS (T1.LINK))), '') AS LAST_DATE,
		T1.NOTICE AS COMMENT,
		T2.ALOCATION,
		LAST_COST = (select isnull(dbo.RestOSByDate(T1.LINK_ACC,T1.LINK,DEFAULT),0) - isnull(dbo.RestOSDepreByDate(DEFAULT, T1.LINK,DEFAULT),0) ) 
	FROM dbo.INVENTORY_CARD T1
	LEFT OUTER JOIN dbo.BV_INVENTORY_CARD_DOP T2 ON (T2.LINK_UP = T1.LINK)
	LEFT OUTER JOIN dbo.ASSETS_GROUP_OKOF T3 ON (T3.LINK = T2.LINK_OKOF)
	LEFT OUTER JOIN dbo.DEPRE_GROUP T4 ON (T4.LINK = T3.DEPRE_GROUP)
	LEFT OUTER JOIN dbo.KU_EMPL_PLACING EMP ON (EMP.LINK = T2.LINK_EMP_F)
	LEFT OUTER JOIN dbo.BK_GetNormDepreTableByOS (@varKSintLINK) ND ON (ND.INV = T1.LINK)
	WHERE T1.LINK = @varKSintLINK

	DECLARE @TAB_MODERN TABLE (REC_NO INT IDENTITY, DATE_OPER1 VARCHAR (10),
		JO_NUM1 VARCHAR (20), SUMMA1 NUMERIC (20,2), NAME1 VARCHAR(100), DOC_NUM1 VARCHAR (30) )

	INSERT INTO @TAB_MODERN
	SELECT CONVERT (VARCHAR (10), a.DATE_OPER, 104) AS DATE_OPER1,
		a.JO_NUM AS JO_NUM1,
		a.SUMMA AS SUMMA1,
		left(s.NAME,100) AS NAME1,
		a.DOC_NUM AS DOC_NUM1
	FROM dbo.BK_GetOperationsByOS (@varKSintLINK, @varKSdDATE_WORK, '17.20')  a -- Реконструкция, модернизация
	INNER JOIN G_PROV2 g2 ON  g2.LINK = a.LINK_G2
	INNER JOIN G_PROV1 g1 ON g1.LINK = g2.LINK_UP
	INNER JOIN G_PROV g ON g.LINK = g1.LINK_UP
	INNER JOIN S_OBJECTS s ON s.LINK = g.[OBJECT]-- Реконструкция, модернизация
--  С_DATA1
	IF @@ROWCOUNT = 0
		INSERT INTO @TAB_MODERN (DATE_OPER1, JO_NUM1, SUMMA1,NAME1,DOC_NUM1) VALUES ('', '', 0,'','')
	SELECT * FROM @TAB_MODERN

-- C_DATA2
	SELECT * FROM @TAB_RECALL	

	--- Поступление НФА ---
	DECLARE @TAB_INPUT TABLE (REC_NO INT IDENTITY, DATE_OPER1 VARCHAR (10),
		JO_NUM1 VARCHAR (20), SUMMA1 NUMERIC (20,2), NAME1 VARCHAR(100), DOC_NUM1 VARCHAR (30) )

	INSERT INTO @TAB_INPUT	
	SELECT 	CONVERT (VARCHAR (10), a.DATE_OPER, 104) AS DATE_OPER1,
		a.JO_NUM AS JO_NUM1,
		a.SUMMA AS SUMMA1,
		left(s.NAME,100) AS NAME1,
		a.DOC_NUM AS DOC_NUM1
	FROM dbo.BK_GetOperationsByOS (@varKSintLINK, @varKSdDATE_WORK,
		'17.01#17.02#17.03#17.05#17.06#17.12#17.13') a  
	INNER JOIN G_PROV2 g2 ON  g2.LINK = a.LINK_G2
	INNER JOIN G_PROV1 g1 ON g1.LINK = g2.LINK_UP
	INNER JOIN G_PROV g ON g.LINK = g1.LINK_UP
	INNER JOIN S_OBJECTS s ON s.LINK = g.[OBJECT]-- Поступление НФА 

-- C_DATA3
	IF @@ROWCOUNT = 0
		INSERT INTO @TAB_INPUT (DATE_OPER1, JO_NUM1, SUMMA1,NAME1,DOC_NUM1) VALUES ('', '', 0,'','')

	SELECT TOP 1 * FROM @TAB_INPUT

	SELECT @PRN_MOVE_EMP = ISNULL (dbo.XK_GET_NASTR_INT ('INV_CARD_OPT_PRN_MOVE_EMP'), 0)

	SELECT IDENTITY (INT) AS REC_NO,
		ISNULL (T1.DOC_NUM, '') AS DOC_NUM2,
		CONVERT (VARCHAR (10), T1.DATE_OPER, 104) AS DATE_OPER2,
		T1.JO_NUM AS JO_NUM2,
		T1.SUMMA AS SUMMA2,
		ISNULL (dbo.sd_GetEmplName (GAP.EMP), '') AS MOV_EMPL2
	INTO #TAB_MOVED
	FROM dbo.BK_GetOperationsByOS (@varKSintLINK, @varKSdDATE_WORK, '17.07') T1 -- Внутреннее перемещение НФА
	LEFT OUTER JOIN dbo.G_PROV_AP GAP ON (GAP.LINK_UP = T1.LINK_G2
				AND ((@PRN_MOVE_EMP = 1 AND GAP.DB_KR = 0)
					OR (@PRN_MOVE_EMP = 0 AND GAP.DB_KR = 1)))
					
					
--	LEFT OUTER JOIN dbo.G_PROV_AP GAP ON (GAP.LINK_UP = T1.LINK_G2 AND GAP.DB_KR = 1) -- поменял в 10604

-- C_DATA4
	IF @@ROWCOUNT = 0
		INSERT INTO #TAB_MOVED (DOC_NUM2, DATE_OPER2, JO_NUM2, SUMMA2, MOV_EMPL2) VALUES ('', '', '',0, '')


	SELECT * FROM #TAB_MOVED
	DROP TABLE #TAB_MOVED

	DECLARE @TAB_OUTPUT TABLE (REC_NO INT IDENTITY, DATE_OPER3 VARCHAR (10),
		JO_NUM3 VARCHAR (20), SUMMA3 NUMERIC (20,2), NAME3 VARCHAR (100), DOC_NUM3 varchar (30) , COMMENT3 VARCHAR (100)  )

	INSERT INTO @TAB_OUTPUT	
	SELECT 	CONVERT (VARCHAR (10), a.DATE_OPER, 104) AS DATE_OPER3,
		a.JO_NUM AS JO_NUM3,
		a.SUMMA AS SUMMA3,
		left(s.NAME,100) AS NAME3,
		a.DOC_NUM AS DOC_NUM3,
		g.COMMENT AS COMMENT3
	FROM dbo.BK_GetDateTableOutOS (@varKSintLINK, @varKSdDATE_WORK) a 
	INNER JOIN G_PROV2 g2 ON  g2.LINK = a.LINK_G2
	INNER JOIN G_PROV1 g1 ON g1.LINK = g2.LINK_UP
	INNER JOIN G_PROV g ON g.LINK = g1.LINK_UP
	INNER JOIN S_OBJECTS s ON s.LINK = g.[OBJECT]
	
	IF @@ROWCOUNT = 0
		INSERT INTO @TAB_OUTPUT (DATE_OPER3, JO_NUM3, SUMMA3,NAME3, DOC_NUM3, COMMENT3) VALUES ('', '', 0,'','', '')

-- C_DATA5
	SELECT TOP 1 * FROM @TAB_OUTPUT

	SELECT ISNULL (NAME, '') AS NAME_C,
		ISNULL (BASIC_OBJ, '') AS BASIC_OBJ,
		ISNULL (ATTR1, '') AS ATTR1,
		ISNULL (ATTR2, '') AS ATTR2,
		ISNULL (ATTR3, '') AS ATTR3,
		ISNULL (ATTR4, '') AS ATTR4
	INTO #TAB_CHAR
	FROM dbo.BV_DICTIONARY_SHORT_DESC
	WHERE LINK_UP = @varKSintLINK

	IF @@ROWCOUNT = 0
		INSERT INTO #TAB_CHAR (NAME_C, BASIC_OBJ, ATTR1, ATTR2, ATTR3, ATTR4)
			VALUES ('', '', '', '', '', '')


-- C_DATA6
	SELECT * FROM #TAB_CHAR
	DROP TABLE #TAB_CHAR

	SELECT ISNULL (BASIC_OBJ, '') AS BASIC_OBJ1,
		ISNULL (NAME_PREC, '') AS NAME_PREC,
		ISNULL (NAME_UM, '') AS NAME_UM,
		ISNULL (CODE_UM, '') AS CODE_UM,
		ISNULL (WEIGTH, 0) AS WEIGTH
	INTO #TAB_DRAG
	FROM dbo.BV_DICTIONARY_PRECIOUS_CONTENT
	WHERE LINK_UP = @varKSintLINK

	IF @@ROWCOUNT = 0
		INSERT INTO #TAB_DRAG (BASIC_OBJ1, NAME_PREC, NAME_UM, CODE_UM, WEIGTH)
			VALUES ('', '', '', '',0)


-- C_DATA7
	SELECT * FROM #TAB_DRAG
	DROP TABLE #TAB_DRAG

	DECLARE @TAB_AMORT TABLE (REC_NO INT IDENTITY,
			SUM_AM NUMERIC (28,4),
			YEAR_AM INT)

	SELECT @BEGIN_DATE_USED = DATE_BEGIN FROM dbo.BV_INVENTORY_CARD_DOP WHERE LINK_UP = @varKSintLINK

	IF @BEGIN_DATE_USED IS NULL
		SET @BEGIN_DATE_USED = @varKSdDATE_WORK
	
--SET @BEGIN_DATE_USED = '20060101'

	SET @DATE_CALC_REST_AMORT = dbo.DateEndOfYear (@BEGIN_DATE_USED)
	SET @YEAR_AM = YEAR (@DATE_CALC_REST_AMORT)
	SET @PREV_SUMMA_AM = 0

	SELECT
		@ACCOUNT_AM = LINK
	FROM dbo.S_ACCOUNTS
	WHERE CODE = '104'	
		AND ZABALANS = 0

	WHILE @YEAR_AM <= YEAR (@varKSdDATE_WORK)
	BEGIN
		SET @DATE_AMORT = DATEADD (DAY, 1, @DATE_CALC_REST_AMORT)

		SET @REST_SUMMA_AM = (SELECT
									SUM (T1.K_SUMMA)
								FROM dbo.ARestTableByDate (@DATE_AMORT, @ACCOUNT_AM) T1
								WHERE T1.INV = @varKSintLINK
								)

/*
	--- !!! ЭТОТ ВАРИАНТ ДЛЯ ВЫВОДА СУММЫ АМОРТИЗАЦИИ, НАЧИСЛЕННОЙ ЗА ГОД!!!

		IF ISNULL (@REST_SUMMA_AM, 0) <> 0
		BEGIN
			SET @SUMMA_AM = @REST_SUMMA_AM - @PREV_SUMMA_AM
			SET @PREV_SUMMA_AM = @REST_SUMMA_AM

			IF @SUMMA_AM > 0
			BEGIN
				INSERT INTO @TAB_AMORT (SUM_AM, YEAR_AM) VALUES (@SUMMA_AM, @YEAR_AM)
				SET @LAST_RECNO = @@IDENTITY
			END
		END

*/
	--- !!! ЭТОТ ВАРИАНТ ДЛЯ ВЫВОДА СУММЫ АМОРТИЗАЦИИ НАРАСТАЮЩИМ ИТОГОМ !!!

		IF ISNULL (@REST_SUMMA_AM, 0) <> 0
		BEGIN
			IF @REST_SUMMA_AM <> @PREV_SUMMA_AM
			BEGIN
				INSERT INTO @TAB_AMORT (SUM_AM, YEAR_AM) VALUES (@REST_SUMMA_AM, @YEAR_AM)
				SET @LAST_RECNO = @@IDENTITY

				SET @PREV_SUMMA_AM = @REST_SUMMA_AM
			END
		END


/*
		IF @SUMMA_AM IS NOT NULL
		BEGIN
			INSERT INTO @TAB_AMORT (SUM_AM, YEAR_AM) VALUES (@SUMMA_AM, @YEAR_AM)
			SET @LAST_RECNO = @@IDENTITY
		END
*/
		SET @DATE_CALC_REST_AMORT = DATEADD (YEAR, 1, @DATE_CALC_REST_AMORT)
		SET @YEAR_AM = YEAR (@DATE_CALC_REST_AMORT)
	END

	IF @LAST_RECNO IS NULL
		INSERT INTO @TAB_AMORT (SUM_AM, YEAR_AM) VALUES (0, 0)		
-- C_DATA8
	SELECT TOP 1 * FROM @TAB_AMORT ORDER BY YEAR_AM DESC

	EXEC dbo.BUFFERCLEAR @varKSc_BufferName
END





GO


GRANT EXECUTE ON dbo.[BK_PRINT_INV_CARD_F0504031] TO PUBLIC

GO



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

GO

  
/*
© Кейсистемс (Keysystems), 2005
*/
CREATE    PROCEDURE [dbo].U_SAVE_DICTIONARY_STAFF_ALL
	@parLINK	int	OUTPUT,
	@parLINK_UP	int = null,
	@parSUBDIV_LINK	int = null,
	@parPOST_LINK	int = null,
	@parNUM_STAKE	numeric(5, 2) = null,
	@parOKLAD	numeric(10, 2) = null,
	@parETS_RAZR int = null,
	@parETS_RAZR2 int = null,
	@parKAT_LINK int = null,
	@parGOSSL int = null,
	@parFIN int = null,
	@parFIN_FOND int = null,
	@parKAT_GOS_LINK int = null,
	@parGR_GOS_LINK int = null,
	@parDATE_BEGIN datetime = null,
	@parDATE_END datetime = '99991231',
	@parLINK_KBK int = NULL,
	@parDAY_VAC_O	numeric(2) = null,
	@parDAY_VAC_D	numeric(2) = 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_UP = 0 SET @parLINK_UP = null
if @parSUBDIV_LINK = 0 SET @parSUBDIV_LINK = null
if @parPOST_LINK = 0 SET @parPOST_LINK = null
if @parKAT_LINK = 0 SET @parKAT_LINK = null
if @parKAT_GOS_LINK = 0 SET @parKAT_GOS_LINK = null
if @parGR_GOS_LINK = 0 SET @parGR_GOS_LINK = null
if @parLINK_KBK = 0 SET @parLINK_KBK = null
IF @parDATE_END IS NULL SET @parDATE_END = '99991231'

	
SELECT @parLINK_UP, @parSUBDIV_LINK, @parPOST_LINK, @parNUM_STAKE, @parNUM_STAKE, @parGOSSL, @parDATE_BEGIN, @parLINK_KBK
	
	IF @parLINK_UP is null or @parSUBDIV_LINK is null or @parPOST_LINK is null or @parNUM_STAKE is null or @parNUM_STAKE=0
		or @parGOSSL is null or @parDATE_BEGIN is null OR @parLINK_KBK IS NULL
		BEGIN
			ROLLBACK
			RETURN 5
		END

	IF @parLINK is null or @parLINK=0 BEGIN
	
		INSERT INTO staff (link_up, subdiv_link, post_link, num_stake, oklad, ets_razr, ets_razr2,kat_link, gossl, fin, fin_fond, kat_gos_link, gr_gos_link, date_begin, date_end, LINK_KBK,DAYS_VAC_O,DAYS_VAC_D)
			VALUES (@parLINK_UP, @parSUBDIV_LINK, @parPOST_LINK, @parNUM_STAKE, @parOKLAD, @parETS_RAZR, @parETS_RAZR2, @parKAT_LINK, 
					@parGOSSL, @parFIN, @parFIN_FOND, @parKAT_GOS_LINK, @parGR_GOS_LINK, @parDATE_BEGIN, @parDATE_END, @parLINK_KBK,@parDAY_VAC_O,@parDAY_VAC_D)
	
		SELECT @SQLError = @@ERROR, @parLINK = @@IDENTITY
		IF @SQLError <> 0 BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	ELSE	BEGIN
		UPDATE staff SET link_up = @parLINK_UP, subdiv_link = @parSUBDIV_LINK, post_link = @parPOST_LINK, num_stake = @parNUM_STAKE, oklad = @parOKLAD, ets_razr = @parETS_RAZR, ets_razr2 = @parETS_RAZR2,
			kat_link = @parKAT_LINK, gossl = @parGOSSL, fin = @parFIN, fin_fond = @parFIN_FOND, kat_gos_link = @parKAT_GOS_LINK, gr_gos_link = @parGR_GOS_LINK,
			date_begin = @parDATE_BEGIN, date_end = @parDATE_END, LINK_KBK = @parLINK_KBK, DAYS_VAC_O = @parDAY_VAC_O,DAYS_VAC_D = @parDAY_VAC_D 
			WHERE link=@parLINK

		SELECT @SQLError = @@ERROR, @parLINK = @@IDENTITY
		IF @SQLError <> 0 BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	EXEC @ERROR = ku_adjust_staff @parLINK_UP
	IF @ERROR<>0 BEGIN
		ROLLBACK
		RETURN @ERROR
	END
	
	SELECT @ObjectLink = LINK FROM S_OBJECTS WHERE CODE = 'DICTIONARY_STAFF_ALL'
	SET @EventText = 'История штатного расписания'
	EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @EventText, @ObjectLink, 'STAFF', @parLINK
IF @@TRANCOUNT > @trancount
	COMMIT TRAN
RETURN 0








GO


GRANT EXECUTE ON dbo.[U_SAVE_DICTIONARY_STAFF_ALL] TO PUBLIC

GO


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

GO

-- Выгрузка остатков по бухгалтерским счетам (МинЗдрав РФ 2013) --
CREATE PROCEDURE dbo.BK_EXPORT_AHD_REST
	@dDate1		DATETIME = NULL
	,@iExport	TINYINT	= NULL
AS
BEGIN
	DECLARE 
		@F_NAME	VARCHAR (100)

	-- Данные Учреждения
	IF OBJECT_ID('tempdb..#DEPARTMENTS') IS NOT NULL 
		DROP TABLE #DEPARTMENTS

	CREATE TABLE #DEPARTMENTS(
		LINK INT
		,KPP	VARCHAR(9)
		,INN	VARCHAR(13)
		,NAME	VARCHAR(254)
		,[TYPE] VARCHAR(60)
		)

	INSERT INTO #DEPARTMENTS  
		(
		LINK
		,KPP
		,INN
		,NAME
		,[TYPE]
		)
	SELECT 
		LINK	= D.LINK
		,KPP	= D.KPP
		,INN	= D.INN
		,NAME	= D.NAME
		,[type]	= DBT.BT_NAME1
	FROM dbo.DEPARTMENTS D
	INNER JOIN dbo.DICTIONARY_BUH_TYPE DBT ON (DBT.BUH_TYPE = D.BUH_TYPE)
	WHERE d.LINK = ISNULL (dbo.BK_GetDepZB (), dbo.GetOwnDepLink())

	-- SELECT * FROM #DEPARTMENTS

	-- Остатки
	IF OBJECT_ID('tempdb..#REST') IS NOT NULL 
		DROP TABLE #REST
		
	CREATE TABLE #REST (
		ID			int IDENTITY
		,[DATE]		DATETIME
		,D_SUMMA	NUMERIC(28,2)
		,K_SUMMA	NUMERIC(28,2)
		,ACCOUNT	INT
		,S_ACTIVE	TINYINT
		,FS_CODE	VARCHAR(1)
		,CODE		VARCHAR(13)	
		,KBK		VARCHAR(30)
		,SGU		VARCHAR(3)
		,DEP		INT
		)

	CREATE INDEX #IDX_REST ON #REST(ID, ACCOUNT)

	INSERT INTO #REST (
		[DATE]
		,D_SUMMA
		,K_SUMMA
		,ACCOUNT
		,S_ACTIVE
		,FS_CODE
		,CODE
		,KBK
		,SGU
		,DEP
		)

	SELECT 
		[Date] = @dDate1
		,D_Summa	= SUM(R.D_SUMMA)
		,K_SUMMA	= SUM(R.K_SUMMA)
		,ACCOUNT	= R.ACCOUNT
		,SA.S_ACTIVE
		,FS_CODE	= sa.cSource
		,CODE		= RTRIM (SA.cSinth) +
									CASE
										WHEN SA.cAnalit <> '' THEN '.' + SA.cAnalit
										ELSE ''
									END
		,KBK		= ISNULL (KK.CODE, '00000000000000000')
		,SGU		= ISNULL (K.CODE, '000')
		,DEP		= R.DEP_LINK
	FROM dbo.ARestTableByDate (@dDate1, DEFAULT) R
	INNER JOIN #DEPARTMENTS D ON d.LINK = R.DEP_LINK
	INNER JOIN dbo.S_ACCOUNTS SA ON SA.LINK = R.ACCOUNT
	LEFT JOIN dbo.KL_KBK KK ON KK.LINK = R.KBK
	LEFT JOIN dbo.S_ACCOUNTS_SGU SAS ON (SAS.ACCOUNT = R.ACCOUNT)
	LEFT JOIN dbo.KOSGU K ON (SA.P_KASSA = 1 AND K.LINK = R.SGU
		OR SA.P_KASSA = 0 AND K.LINK = SAS.LINK_SGU)
	WHERE
		SA.P_KASSA = 1
		OR (SA.P_KASSA = 0 AND (SA.S_ACTIVE = 1 AND K.DB_KR = 0
								OR SA.S_PASSIVE = 1 AND K.DB_KR = 1))
	GROUP BY
		R.ACCOUNT
		,SA.S_ACTIVE
		,SA.cSource
		,SA.cSinth, SA.cAnalit
		,SA.P_KASSA
		,KK.CODE
		,K.CODE 
		,R.DEP_LINK

-- SELECT * FROM #REST

	IF ISNULL (@iExport, 0) = 1
	BEGIN
		IF OBJECT_ID('tempdb..#OUT') IS NOT NULL 
			DROP TABLE #OUT

		CREATE TABLE #OUT (ID INT IDENTITY (1,1), TXT VARCHAR(8000))

		INSERT INTO #OUT (TXT)
		SELECT
			'UTF-8'
		
		INSERT INTO #OUT (TXT)
		SELECT 
		'<?xml version="1.0" encoding="UTF-8"?>
		<Exchange version="1.0">
			<Operation Version="1.0" date="'+CONVERT(VARCHAR(30), GETDATE (),126) +'" period="Месяц" TypeOperation="Остатки">
				<Organization INN="' + ISNULL (RTRIM (d.INN),'')+'" KPP="' + ISNULL (RTRIM (d.KPP),'')+'">
					<Name>' + ISNULL (RTRIM (d.NAME),'')+'</Name>
					<type>' + ISNULL (RTRIM (d.[TYPE]),'')+'</type>
				</Organization>'
		FROM #DEPARTMENTS d

		INSERT INTO #OUT (TXT)
		SELECT 
		'
				<Record ID="'+ CONVERT(VARCHAR(30),(ROW_NUMBER() OVER (ORDER BY O.CODE, O.FS_CODE, O.KBK)) ) +'" Date="'+CONVERT(VARCHAR(30),o.Date,126)+'">
					<KFO>' + o.FS_CODE + '</KFO>
					' +CASE WHEN o.D_Summa  <> 0 THEN '<Schet_Dt Cod="' ELSE '<Schet_Kt Cod="' end + ISNULL(o.CODE,'')+'" KPS="' + REPLACE (O.KBK, '.', '') + '" KEK="' + o.SGU +'"/>
					<Summa>'+CASE WHEN o.D_Summa  <> 0 THEN ISNULL(convert(varchar(30),o.D_Summa),'0') ELSE ISNULL(convert(varchar(30),o.K_Summa),'0') END +'</Summa>
					<Description/>
				</Record>'
		FROM #REST o
		WHERE o.D_Summa <> 0 OR o.K_Summa <> 0

		INSERT INTO #OUT(txt)
		SELECT 
		'
			</Operation>
		</Exchange>'
	
		EXEC dbo.GetRandStr 15, @F_NAME OUTPUT
		
		SELECT 
			@F_NAME = 'OSTATOK_'+ ISNULL(RTRIM (D.INN),'') + '_' + ISNULL(RTRIM (D.KPP),'') +
						'_' + ISNULL(CONVERT(VARCHAR(30), @dDate1, 112),'') + '_' + @F_NAME + '.xml'
		FROM #DEPARTMENTS d
		
		SELECT
			R.ID,
			ENCODING	= 'UTF-8',
			OUT_TEXT	= R.TXT 
			,[F_NAME]	= @F_NAME
		FROM #OUT r
		ORDER BY R.ID
		
		DROP TABLE #OUT
	END
	ELSE
		SELECT
			[version]		= '1.0'
			,[date_rest]	= @dDate1
			,period			= 'Месяц'
			,TypeOper		= 'Остатки'
			,DEP_INN		= d.INN 
			,DEP_KPP		= d.KPP
			,DEP_NAME		= d.NAME
			,DEP_TYPE			= d.[TYPE]
			,ID				= ROW_NUMBER() OVER (ORDER BY R.CODE, R.FS_CODE, R.KBK)
			,[date]			= @dDate1
			,KFO			= r.FS_CODE
			,Cod			= r.CODE
			,KPS			= r.KBK
			,R.KBK
			,KOSGU			= r.SGU
			,Summa			= CASE WHEN S_ACTIVE = 1 THEN R.D_Summa ELSE R.K_Summa END
			,D_SUMMA,
			K_SUMMA
			,Comment		= ''
		FROM #DEPARTMENTS D
		INNER JOIN #REST R ON R.DEP = d.LINK
		WHERE R.D_Summa <> 0 OR R.K_Summa <> 0 

	DROP TABLE #DEPARTMENTS
	DROP TABLE #REST

END


GO


GRANT EXECUTE ON dbo.[BK_EXPORT_AHD_REST] TO PUBLIC

GO



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

GO

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

CREATE      PROCEDURE dbo.BI_SAVE_VKR
	@varKSparLINK	int	OUTPUT,
	@varKSparNAME        VARCHAR(250) = '',
	@varKSLink_Adm	int = null,
	@varKSLink_Div	int,
	@varKSLink_Csr	int = null,
	@varKSLink_Exp	int = null,
	@iUsed			int = 1,
	@cDelim			char(1) = '.'

AS
DECLARE @varKSERROR	tinyint,
	@varKSRowCount INT,
	@varKSstrVALUE	varchar(7000),
	@varKStrancount	int,
	@varKSEventText	varchar(254),
	@varKSintObj		int,
	@varKSCode	char(30)
SET LOCK_TIMEOUT 30000
SET @varKStrancount = @@TRANCOUNT

SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN

	IF @varKSparNAME IS NULL OR @varKSparNAME = ''
	BEGIN
		ROLLBACK
		RETURN 5
	END
	IF @varKSLink_Div IS NULL OR @varKSLink_Div = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END
	IF @varKSLink_Adm IS NULL OR @varKSLink_Adm = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END
	IF @varKSLink_Csr <= 0
	BEGIN
		SET @varKSLink_Csr = null
	END
	IF @varKSLink_Exp <= 0
	BEGIN
		SET @varKSLink_Exp = null
	END

	if (@varKSLink_Csr>0 and (select count(*) from KL_TARGET_ITEM where link = @varKSLink_Csr)<>1)
	OR (@varKSLink_Exp>0 and (select count(*) from KL_EXPEND where link = @varKSLink_Exp)<>1)
	OR (select count(*) from KL_DIVISION where link = @varKSLink_Div)<>1
	OR (select count(*) from KL_ADMIN_BS where link = @varKSLink_Adm)<>1
	BEGIN
		ROLLBACK
		RETURN 5
	END

	SET @varKSCode = coalesce ((SELECT code FROM KL_ADMIN_BS WHERE link = @varKSLink_Adm),'000') + @cDelim +
			coalesce ((SELECT code FROM KL_DIVISION WHERE link = @varKSLink_Div),'0000') + @cDelim +
			coalesce ((SELECT code FROM KL_TARGET_ITEM WHERE link = @varKSLink_Csr),'0000000') + @cDelim +
			coalesce ((SELECT code FROM KL_EXPEND WHERE link = @varKSLink_Exp),'000')
	
	If (select count(*) from KL_KBK where link <> @varKSparLINK and CODE = @varKSCode AND TYPE = 1) <> 0 
	BEGIN
		ROLLBACK
		RETURN 4
	END

	If (Select count(*) from KL_KBK where link = @varKSparLINK) > 0
	BEGIN
		UPDATE KL_KBK
		SET 	TYPE = 1,
			CODE = @varKSCode,
			NAME = @varKSparNAME,
			Link_Adm = @varKSLink_Adm,
			USED = @iUsed
		WHERE LINK = @varKSparLINK
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		DELETE FROM KL_KBK_IVF WHERE LINK_KBK = @varKSparLINK
		DELETE FROM KL_KBK_KD WHERE LINK_KBK = @varKSparLINK
	END
	ELSE
	BEGIN
		INSERT INTO KL_KBK(Type, code, name, link_adm, USED)
			VALUES(1, @varKSCode, @varKSparNAME, @varKSLink_Adm, @iUsed)
		SELECT @varKSERROR = @@ERROR, @varKSparLINK = @@IDENTITY
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END

		--- Создание нового источника финансирования

		insert into dbo.sal_sfin (code, [NAME], KBK, SOURCE, COMMENT)
		SELECT LEFT(@varKSCode,30), left(@varKSparNAME,120), @varKSparLINK, 1, 'Сформировано при добавлении нового ВКР'
		----

		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END

	END

	IF (select count(*) from KL_VKR where link_kbk = @varKSparLINK) = 1
	BEGIN
		UPDATE KL_VKR
		SET 	LINK_DIV = @varKSLink_Div,
			LINK_CSR = @varKSLink_Csr,
			LINK_EXP = @varKSLink_Exp
		WHERE LINK_KBK = @varKSparLINK
		
		SELECT @varKSRowCount = @@ROWCOUNT, @varKSERROR = @@ERROR
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	ELSE
	BEGIN
		INSERT INTO KL_VKR 
			(Link_KBK, Link_Div, Link_Csr, Link_Exp)
		VALUES (@varKSparLINK, @varKSLink_Div, @varKSLink_Csr, @varKSLink_Exp)
		SELECT @varKSERROR = @@ERROR
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END

	SELECT @varKSEventText = 'КБК. ВКР ' + @varKSCode + ' ' + @varKSparNAME, @varKSintObj = LINK FROM S_OBJECTS WHERE CODE = 'BI_DICTION_KBK'
	EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @varKSEventText, @varKSintObj, 'KL_KBK', @varKSparLINK
IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0


GO


GRANT EXECUTE ON dbo.[BI_SAVE_VKR] TO PUBLIC

GO


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

GO


CREATE   PROCEDURE dbo.SD_PROV_DATA
	@varKSnMonth INT,
	@varKSnYear INT
AS

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

---
declare @DEP_LINK int
exec dbo.xd_whats_zb @DEP_LINK output

/*Удаляем все документы по зарплате из G_PROV за заданный период только по активной подотчетной организации*/
EXEC dbo.SD_PROV_DELETE @varKSnMonth, @varKSnYear

--------------------
/*Формирование проводок начисления для штатников, кроме НДФЛ и ЕСН и формирование для внештатников*/
EXEC dbo.SA_CREATE_PROV_N @varKSnMonth, @varKSnYear, @DEP_LINK

/*Формирование проводок по удержаниям НДФЛ и другим*/
EXEC dbo.SA_CREATE_PROV_U @varKSnMonth, @varKSnYear, @DEP_LINK

/*Формирование проводок по удержанию из зарплаты при выплате через банкомат штатным сотрудникам и внештатникам*/
EXEC dbo.SA_CREATE_PROV_VEDOM @varKSnMonth, @varKSnYear, @DEP_LINK

/*Формирование проводок по ЕСН*/
EXEC dbo.SA_CREATE_PROV_O @varKSnMonth, @varKSnYear, @DEP_LINK


/*Формирование XML с проводками для синхронизации */
EXEC dbo.SA_CREATE_XML_TO_SYNCH @varKSnMonth, @varKSnYear, @DEP_LINK

GO


GRANT EXECUTE ON dbo.[SD_PROV_DATA] TO PUBLIC

GO


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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE      PROCEDURE [dbo].U_SAVE_DICTIONARY_STAFF
	@parLINK	int	OUTPUT,
	@parSUBDIV_LINK	int = null,
	@parPOST_LINK	int = null,
	@parNUM_STAKE	numeric(5, 2) = null,
	@parOKLAD	numeric(10, 2) = null,
	@parETS_RAZR int = null,
	@parETS_RAZR2 int = null,
	@parKAT_LINK int = null,
	@parGOSSL int = null,
	@parFIN int = null,
	@parFIN_FOND int = null,
	@parKAT_GOS_LINK int = null,
	@parGR_GOS_LINK int = null,
	@parDATE_BEGIN datetime = null,
	@parDEP_LINK	int = null,
	@parLINK_KBK	int = null,
	@parDAY_VAC_O	numeric(2) = null,
	@parDAY_VAC_D	numeric(2) = null
AS
DECLARE @ERROR	tinyint,
		@strVALUE	varchar(7000),
		@trancount	int,
		@ObjectLink int,
		@EventText	varchar(254),
		@SQLError int,
		@WorkDate datetime, @DATE_END datetime, @staff_link int, @prev_link int
SET @trancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN
	
	IF @parSUBDIV_LINK is null or @parPOST_LINK is null or @parNUM_STAKE is null or @parNUM_STAKE=0 OR @parLINK_KBK IS NULL
		or @parGOSSL is null
		BEGIN
			ROLLBACK
			RETURN 5
		END

if @parSUBDIV_LINK = 0 SET @parSUBDIV_LINK = null
if @parPOST_LINK = 0 SET @parPOST_LINK = null
if @parKAT_LINK = 0 SET @parKAT_LINK = null
if @parKAT_GOS_LINK = 0 SET @parKAT_GOS_LINK = null
if @parGR_GOS_LINK = 0 SET @parGR_GOS_LINK = null
if @parDEP_LINK = 0 SET @parDEP_LINK = null
if @parLINK_KBK = 0 SET @parLINK_KBK = null

	SELECT @parDEP_LINK = isnull(@parDEP_LINK, dep_link), @parDATE_BEGIN = isnull(@parDATE_BEGIN, workdate), @WorkDate = workdate
	FROM user_info

	IF @parLINK=0 or @parLINK is null BEGIN
		INSERT INTO staff_head (dep_link) VALUES (@parDEP_LINK)
		SELECT @SQLError = @@error, @parLINK = @@identity 
		IF @SQLError <> 0 BEGIN
			ROLLBACK
			RETURN @SQLError
		END

		SET @DATE_END = '99991231'
		EXEC @ERROR = U_SAVE_DICTIONARY_STAFF_ALL 0, @parLINK, @parSUBDIV_LINK, @parPOST_LINK, @parNUM_STAKE, @parOKLAD, @parETS_RAZR, @parETS_RAZR2, @parKAT_LINK, @parGOSSL,
									@parFIN, @parFIN_FOND, @parKAT_GOS_LINK, @parGR_GOS_LINK, @parDATE_BEGIN, @DATE_END, @parLINK_KBK,@parDAY_VAC_O,@parDAY_VAC_D
		IF @ERROR <> 0 RETURN @ERROR
	END
	ELSE BEGIN
		SELECT @prev_link = link FROM staff WHERE link_up=@parLINK and @WorkDate between date_begin and date_end and date_begin>@WorkDate

		UPDATE staff SET date_end = @WorkDate - 1 WHERE link = @prev_link
		SELECT @SQLError = @@error
		IF @SQLError <> 0 BEGIN
			ROLLBACK
			RETURN @SQLError
		END		

		
		SELECT @DATE_END = MIN(date_begin)-1 FROM staff WHERE link_up=@parLINK and date_begin>@WorkDate

		IF @DATE_END is null SET @DATE_END = '99991231'
		
		SELECT @staff_link = link FROM staff WHERE link_up=@parLINK and date_begin=@WorkDate
		IF @@rowcount = 0 SET @staff_link = 0

		EXEC @ERROR = U_SAVE_DICTIONARY_STAFF_ALL @staff_link, @parLINK, @parSUBDIV_LINK, @parPOST_LINK, @parNUM_STAKE, @parOKLAD, @parETS_RAZR, @parETS_RAZR2, @parKAT_LINK, @parGOSSL,
									@parFIN, @parFIN_FOND, @parKAT_GOS_LINK, @parGR_GOS_LINK, @WorkDate, @DATE_END, @parLINK_KBK,@parDAY_VAC_O,@parDAY_VAC_D
		IF @ERROR <> 0 RETURN @ERROR
			
	END

	
	SELECT @ObjectLink = LINK FROM S_OBJECTS WHERE CODE = 'DICTIONARY_STAFF'
	SET @EventText = 'Штатное расписание'
	EXECUTE WF_GENERATEEVENT 'Сохранение строки штатного', @EventText, @ObjectLink, 'STAFF', @parLINK
IF @@TRANCOUNT > @trancount
	COMMIT TRAN
RETURN 0






GO


GRANT EXECUTE ON dbo.[U_SAVE_DICTIONARY_STAFF] TO PUBLIC

GO


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


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

GO


--select * from nomenclature
--select * from INVENTORY
CREATE PROCEDURE dbo.XK_MOVING_INV_TO_NOMEN
	@strACCT_cSINTH	VARCHAR (3),
	@strACCT_ANALIT	VARCHAR (2),
	@strBUFFER_NAME	VARCHAR (100) = NULL,
	@strBUFFER_NAME_NOMEN VARCHAR (100) = NULL,
	@intCLEAR_BUFFER_NOMEN TINYINT = 1,
	@strNEW_GRP_CODE	VARCHAR (5) = NULL

AS
BEGIN
	DECLARE 
		@intINV_LINK	INT,
--		@strBUFFER_NAME_NOMEN	VARCHAR (100),
	
		/* -- НОВАЯ ЗАПИСЬ -- */
		@intNEW_NOMEN	INT,
		@strNOM_CODE	VARCHAR (20),
		@strNOM_NAME	VARCHAR (254),
		@intGRP_INV	INT,
		@intUM		INT,
		@strSERIES	VARCHAR (30),
		@strGRP_CODE	VARCHAR (5),
		@bitIS_EXTRA	BIT,
		@intLINK_OKDP INT,
		@nCOEFF NUMERIC (18,9),
		@intPRICE_TYPE TINYINT,
		@intLINK_OKPD INT,
		@nCOEFF_OKPD NUMERIC (18,9),
		@intISUSED	TINYINT,
		
		@intSGU_340	INT,
		@intSGU_440	INT
/*	
		@kassa int,
		@BB datetime,
		@BE datetime,
	
		@BB_old datetime,
		@BE_old datetime
	
	select @BB_old = BEGINDATE,
		@BE_old = ENDDATE
	from admin_info
	
	Select @kassa = LINK from S_OBJECTS Where CODE = 'KASSA'
	SELECT @BB = convert(datetime, '19000101', 112), @BE = convert(datetime, '20100101', 112)
	EXECUTE I_SET_ADMIN_DATE @kassa, @BB, @BB, @BE
*/	
	SELECT	@intSGU_340 = LINK FROM KOSGU WHERE CODE = '340'
	SELECT	@intSGU_440 = LINK FROM KOSGU WHERE CODE = '440'
	
	IF @strBUFFER_NAME_NOMEN IS NULL
		SET @strBUFFER_NAME_NOMEN = '_MOVING_MZ_FROM_10601_TO_10604'
	
	DECLARE @TAB_RES TABLE (LINK INT, INV_CODE VARCHAR (20), INV_NAME VARCHAR (254))
	
	DECLARE #INV_TO_NOMEN CURSOR LOCAL
	FOR
		SELECT
			INV.LINK, INV.[NAME], NOMEN.GROUP_INV, NOMEN.UM, NOMEN.SERIES, NOMEN.IS_EXTRA, GR.CODE,
			NOMEN.LINK_OKDP, NOMEN.COEFF, NOMEN.PRICE_TYPE, NOMEN.LINK_OKPD, NOMEN.COEFF_OKPD, NOMEN.ISUSED
--		FROM INVENTORY INV
		FROM (SELECT ACCOUNT, INV FROM dbo.ARestTableByDate ('20061231', DEFAULT) GROUP BY ACCOUNT, INV) T
		INNER JOIN dbo.INVENTORY INV ON (INV.LINK = T.INV)
		INNER JOIN dbo.NOMENCLATURE NOMEN ON (NOMEN.LINK = INV.NOMENCLATURE)
		INNER JOIN dbo.GROUP_INV GR ON (GR.LINK = NOMEN.GROUP_INV)
		INNER JOIN dbo.S_ACCOUNTS_OLD70N SA ON (SA.LINK = T.ACCOUNT)
--INNER JOIN dbo.S_ACCOUNTS_OLD70N SA ON (SA.LINK = GR.ACCOUNT)
		WHERE (@strBUFFER_NAME IS NOT NULL
					AND EXISTS (SELECT * FROM dbo.BufferGetTableByID (@strBUFFER_NAME) TTT WHERE TTT.LINK = INV.LINK))
			OR (@strBUFFER_NAME IS NULL AND SA.cSINTH = @strACCT_cSINTH
				AND SA.cANALIT = @strACCT_ANALIT)
	
	OPEN #INV_TO_NOMEN
	FETCH #INV_TO_NOMEN
		INTO @intINV_LINK, @strNOM_NAME, @intGRP_INV, @intUM, @strSERIES, @bitIS_EXTRA, @strGRP_CODE,
			@intLINK_OKDP, @nCOEFF, @intPRICE_TYPE, @intLINK_OKPD, @nCOEFF_OKPD, @intISUSED
	
	WHILE @@FETCH_STATUS = 0
	BEGIN
		/* ---  СОЗДАЕМ НОВУЮ ЗАПИСЬ В НОМЕНКЛАТОРЕ --- */
--		IF @strGRP_CODE IS NOT NULL
		IF @strNEW_GRP_CODE IS NOT NULL
			SET @strGRP_CODE = @strNEW_GRP_CODE
		EXEC dbo.BV_GET_NOMEN_NEXT_CCODE @strNOM_CODE OUTPUT, @strGRP_CODE
		SET @intNEW_NOMEN = NULL
/*		
		EXEC dbo.BV_SAVE_NOMENCLATURE @intNEW_NOMEN OUTPUT, @intGRP_INV, @strNOM_CODE,
			@strNOM_NAME, @strSERIES, @intUM, @bitIS_EXTRA 
*/	
		EXEC dbo.BV_SAVE_NOMENCLATURE 
				@varKSparLINK		=	@intNEW_NOMEN OUTPUT,
				@varKSparLINK_GRP	=	@intGRP_INV,
				@varKSparCODE		=	@strNOM_CODE,
				@varKSparNAME		=	@strNOM_NAME,
				@varKSparSERIES		=	@strSERIES,
				@varKSparLINK_UM	=	@intUM,
				@lbIS_EXTRA			=	@bitIS_EXTRA,
				@varKSparLINK_OKDP	=	@intLINK_OKDP,
				@varKSparLINK_OKPD	=	@intLINK_OKPD,
				@nCOEFF			=	@nCOEFF,
				@nCOEFF_OKPD	=	@nCOEFF_OKPD,
				@intPRICE_TYPE		=	@intPRICE_TYPE,
				@intISUSED	= @intISUSED

		EXEC dbo.BufferPush @intNEW_NOMEN, @strBUFFER_NAME_NOMEN
	
		UPDATE G_PROV_AP
		SET INV = NULL,
			NOMEN = @intNEW_NOMEN,
			SGU = CASE
					WHEN EXISTS (SELECT * FROM KOSGU K WHERE K.LINK = GAP.SGU AND CODE LIKE '3%') THEN @intSGU_340
					WHEN EXISTS (SELECT * FROM KOSGU K WHERE K.LINK = GAP.SGU AND CODE LIKE '4%') THEN @intSGU_440
					ELSE GAP.SGU
				END,
			EKR = CASE
					WHEN EXISTS (SELECT * FROM KOSGU K WHERE K.LINK = GAP.EKR AND CODE LIKE '3%') THEN @intSGU_340
					WHEN EXISTS (SELECT * FROM KOSGU K WHERE K.LINK = GAP.EKR AND CODE LIKE '4%') THEN @intSGU_440
					ELSE GAP.EKR
				END
		FROM G_PROV_AP GAP
		WHERE GAP.INV = @intINV_LINK
	
		UPDATE SALDO SET INV = NULL,
			NOMEN = @intNEW_NOMEN,
			SGU = CASE
					WHEN EXISTS (SELECT * FROM KOSGU K WHERE K.LINK = GAP.SGU AND CODE LIKE '3%') THEN @intSGU_340
					WHEN EXISTS (SELECT * FROM KOSGU K WHERE K.LINK = GAP.SGU AND CODE LIKE '4%') THEN @intSGU_440
					ELSE GAP.SGU
				END,
			EKR = CASE
					WHEN EXISTS (SELECT * FROM KOSGU K WHERE K.LINK = GAP.EKR AND CODE LIKE '3%') THEN @intSGU_340
					WHEN EXISTS (SELECT * FROM KOSGU K WHERE K.LINK = GAP.EKR AND CODE LIKE '4%') THEN @intSGU_440
					ELSE GAP.EKR
				END
		FROM SALDO GAP
		WHERE GAP.INV = @intINV_LINK
	
		FETCH #INV_TO_NOMEN
			INTO @intINV_LINK, @strNOM_NAME, @intGRP_INV, @intUM, @strSERIES, @bitIS_EXTRA, @strGRP_CODE,
				@intLINK_OKDP, @nCOEFF, @intPRICE_TYPE, @intLINK_OKPD, @nCOEFF_OKPD, @intISUSED
	END
	
	EXEC XK_MOVING_MZ_10601_TO_10604 @strBUFFER_NAME_NOMEN
	
--	EXECUTE I_SET_ADMIN_DATE @kassa, @BB_OLD, @BB_OLD, @BB_OLD
	--SELECT * FROM @TAB_RES
	IF @intCLEAR_BUFFER_NOMEN = 1
		EXEC dbo.BufferClear @strBUFFER_NAME_NOMEN
END



GO


GRANT EXECUTE ON dbo.[XK_MOVING_INV_TO_NOMEN] TO PUBLIC

GO


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


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


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

CREATE PROCEDURE dbo.BB_EXPORT_FORM_CALC @cCalcFormID varchar(100)	

as

-- ВЫГРУЗКА расчетов
DECLARE @iCalcLink INT,
		@cFormCode varchar(50),
		@cFormDate varchar(8),
		@iCalcFormLink int
		
	
declare @tTemp table ([TEXT] varchar(8000), ord int identity)
declare @curCalc cursor  

--SELECT * FROM dbo.RB_CALC_NASTR

SET @curCalc = CURSOR FORWARD_ONLY FOR 
SELECT LINK from dbo.BufferGetTableByID(@cCalcFormID)


OPEN @curCalc	
FETCH NEXT FROM @curCalc INTO @iCalcFormLink
while @@fetch_status = 0
begin

	select @cFormDate = rtrim(convert(char(8),FORM_DATE,112)), @cFormCode = rtrim(FORM_CODE) from RB_CALC_NASTR where LINK = @iCalcFormLink
	insert into @tTemp([TEXT])
	SELECT 'DECLARE @iCalcFormLink INT,
			@iCalcLink INT
			
	delete RCF
	FROM dbo.REPORT_CALC_FORMS RCF
	inner join dbo.REPORT_CALC RC on RC.LINK_UP = RCF.LINK and RC.[isUSER] = 0
	inner join dbo.REPORT_FORMS RF on RCF.LINK_FORM = RF.Link_Form 
	WHERE RF.CODE = ''' + @cFormCode + ''' AND RF.START_DATE = ''' + @cFormDate + ''' and RCF.[ORDER] = ' + LTRIM(str([ORDER])) + ' and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = ''' + rtrim(dbo.BB_CALC_GET_ATR_VAL(LINK,FORM_LINK ,1)) + '''


	UPDATE RCF 
	set [ORDER] = 1
	FROM dbo.REPORT_CALC_FORMS RCF
	inner join dbo.REPORT_CALC RC on RC.LINK_UP = RCF.LINK and RC.[isUSER] = 1
	inner join dbo.REPORT_FORMS RF on RCF.LINK_FORM = RF.Link_Form 
	WHERE RF.CODE = ''' + @cFormCode + ''' AND RF.START_DATE = ''' + @cFormDate + ''' and RCF.[ORDER] = ' + LTRIM(str([ORDER])) + ' and dbo.BB_CALC_GET_ATR_VAL(RCF.LINK,RF.Link_Form ,1) = ''' + rtrim(dbo.BB_CALC_GET_ATR_VAL(LINK,FORM_LINK ,1)) + '''

	INSERT INTO dbo.REPORT_CALC_FORMS(LINK_FORM, USED, [ORDER], COMMENT)
	SELECT LINK_FORM, ' + LTRIM(str(USED)) + ',' + LTRIM(str([ORDER])) + ',''' + RTRIM(COMMENT) + '''
	from dbo.REPORT_FORMS where CODE = ''' + @cFormCode +  ''' AND [START_DATE] = ''' + @cFormDate + ''' 
	SET @iCalcFormLink = @@IDENTITY
	'
	--select * 
	FROM dbo.RB_CALC_NASTR 
	WHERE LINK = @iCalcFormLink




	insert into @tTemp([TEXT])
	SELECT 'INSERT INTO dbo.REPORT_CALC_ATRIBUTE(LINK_CALC_FORM, CODE_ATR, STR_VAL, INT_VAL)
	VALUES(@iCalcFormLink, ''' + RTRIM(CODE_ATR) + ''', ''' + isnull(RTRIM(STR_VAL),'NULL') + ''', ' + isnull(LTRIM(str(INT_VAL)),'NULL') + ')'
	FROM dbo.REPORT_CALC_ATRIBUTE 
	WHERE LINK_CALC_FORM = @iCalcFormLink


	DECLARE CALC_CUR CURSOR LOCAL STATIC READ_ONLY FOR
	SELECT DISTINCT LINK 
	FROM dbo.REPORT_CALC
	WHERE LINK_UP = @iCalcFormLink

	OPEN CALC_CUR
	FETCH NEXT FROM CALC_CUR INTO @iCalcLink

	WHILE @@FETCH_STATUS = 0
	BEGIN
		insert into @tTemp([TEXT])
		SELECT 'set @iCalcLink = NULL
			INSERT INTO dbo.REPORT_CALC(LINK_UP, Link_Col, Code_Row, IsUser, Calc_Order, Comment)
			SELECT @iCalcFormLink, RC.LINK_COL, ''' + RTRIM(Code_Row) + ''','  + LTRIM(STR(IsUser)) + ','  + LTRIM(STR(Calc_Order)) + ',''' + RTRIM(Comment) + '''
			from dbo.REPORT_TABLES RT 
			inner join dbo.REPORT_COLOUMNS RC on RC.Link_Table = RT.Link_Table and RC.EXPORT_ORDER = ' + RTRIM(ORDER_COL) + '
			inner join dbo.REPORT_CALC_FORMS CF on CF.LINK = @iCalcFormLink AND CF.Link_Form = RT.Link_Form and RT.ORDERS = ''' + LTRIM(STR(ORDERS)) + '''
			
			SET @iCalcLink = @@IDENTITY
		'
		FROM dbo.RO_CALC
		WHERE LINK = @iCalcLink
		--select @varKSBlockLink

		insert into @tTemp([TEXT])
		select '	INSERT INTO REPORT_CALC_ROWS (Link_Calc, Orders, [Sign], DT_Mask, KT_Mask, DT_EKR, KT_EKR, Type_KBK, [Type], Mask_KBK, DT_KT, oper)
		SELECT @iCalcLink, ' + LTRIM(STR(ORDERS)) + ',' + LTRIM(STR([Sign])) + ',''' + RTRIM(DT_Mask) + ''',''' + RTRIM(KT_Mask) + ''',''' + 
		RTRIM(DT_EKR) + ''',''' + RTRIM(KT_EKR) + ''',' + LTRIM(STR(Type_KBK)) + ',' + LTRIM(STR(Type)) + ',''' + RTRIM(Mask_KBK) + ''',' + LTRIM(STR(DT_KT))+ ',''' + RTRIM(OPER) + ''''
		FROM dbo.REPORT_CALC_ROWS 
		WHERE LINK_CALC = @iCalcLink
		order by ORDERS

		FETCH NEXT FROM CALC_CUR INTO @iCalcLink
	END
	CLOSE CALC_CUR
	DEALLOCATE CALC_CUR

	insert into @tTemp ([TEXT])
	select 'GO'
	FETCH NEXT FROM @curCalc INTO @iCalcFormLink

end
CLOSE @curCalc
DEALLOCATE @curCalc

SELECT [TEXT] from @tTemp order by ord

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

GO
CREATE PROCEDURE dbo.BK_EXPORT_F1151006 (@iLINK_FORM INT)
AS
BEGIN

--перенос формы из архивной базы
exec 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),
		@POST_GL_BUH	VARCHAR (254),
		@DEP_NAME VARCHAR (254),

		@SONO VARCHAR (4),

		@DOC_ID		VARCHAR (36),

		@NAME_RUK	VARCHAR (60),
		@FAM_RUK	VARCHAR (60),
		@OT_RUK		VARCHAR (60),

		@NAME_GL_BUH	VARCHAR (60),
		@FAM_GL_BUH	VARCHAR (60),
		@OT_GL_BUH	VARCHAR (60),

		@dDATE_FORM	DATETIME,
		@PERIOD_TYPE	INT,
		@PERIOD_NUM	INT,
		@cPERIOD_NUM	VARCHAR (2),

		@iLINK_TABLE	INT,
		@PROC_NAME	VARCHAR (254),

		--- Раздел 1 ---
		@OKATO_D VARCHAR (15),
		@OKATO VARCHAR (15),
		
		@KBK VARCHAR (30),
		@SUMMA1 VARCHAR (100),
		@SUMMA2 VARCHAR (100),
/*		@SUMMA	NUMERIC (15,0),

		@SUM_AV NUMERIC (15,0),
		@SUM_PAY NUMERIC (15,0),
		@SUM_LOW NUMERIC (15,0),

		@LINK_COL_CODE INT,
*/
		--- Лист 02 ---
		@CODE VARCHAR (50),
		@COL1 VARCHAR (50),
		@COL3 VARCHAR (100), 	
		@COL4 VARCHAR(100), 	

		@strINS_VALUE	VARCHAR (100),

/*		--- Раздел 2 ---
		@LINK_COL_VIDTS	INT,
		@LINK_COL_VIN	INT,
		@LINK_COL_MARKA	INT,
		@LINK_COL_REGNO	INT,
		@LINK_COL_NALBAS INT,
		@LINK_COL_OKEI	INT,
		@LINK_COL_SROK	INT,
		@LINK_COL_K3623	INT,
		@LINK_COL_STAVKA INT,
		@LINK_COL_SUM_IS	INT,
		@LINK_COL_LGOTA	INT,
		@LINK_COL_SUM_LGOTA	INT,
		@LINK_COL_SUM_UPL	INT,
*/
		@strEXEC	VARCHAR (8000)
	--- ---
	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

	SET @cPERIOD_NUM = CASE
				WHEN @PERIOD_TYPE = 1 THEN '34'	-- ПЕРИОД ГОД
				WHEN @PERIOD_TYPE = 2 THEN 	-- ПЕРИОД КВАРТАЛ
					CASE 
						WHEN @PERIOD_NUM = 1 THEN '21'
						WHEN @PERIOD_NUM = 2 THEN '31'
						WHEN @PERIOD_NUM = 3 THEN '33'
					END
				WHEN @PERIOD_TYPE = 4 THEN LTRIM (STR (34 + @PERIOD_NUM ))
			END

	EXEC dbo.GetRandStr 36, @DOC_ID OUTPUT

	SELECT @PART_NAME_NNN = @DOC_ID

	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],
			@OKATO_D = CONVERT (VARCHAR (11), REPLACE (OKATO, ' ', '')),
			@SONO = CONVERT (VARCHAR (4), ISNULL (IMNS, ''))
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @DEP_LINK

	SET @DEP_NAME = REPLACE (@DEP_NAME, '"', '&quot;')

	SELECT @TLF_GL_BUH = A.PHONE,
		@POST_GL_BUH = B.POST_NAME,

		@NAME_GL_BUH = B.IM,
		@FAM_GL_BUH = B.FM,
		@OT_GL_BUH = B.OT

	FROM dbo.DICTIONARY_OTV_FACE A
	LEFT JOIN dbo.KU_EMPL_PLACING B ON (B.LINK = A.FACE_LINK)
	WHERE A.DEP_LINK = @DEP_LINK
		AND A.[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.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 #TABLE_R1_1 (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), 	-- Сумма1 (ФБ)
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Сумма2 (ФБ)
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- КБК (Субъект)
		FCOL6 VARCHAR (254),
		COL7 VARCHAR(100), 	-- Сумма1 (Субъект)
		FCOL7 VARCHAR (254),
		COL8 VARCHAR(100), 	-- Сумма2 (Субъект)
		FCOL8 VARCHAR (254),
		COL9 VARCHAR(100), 	-- Номер корректировки
		FCOL9 VARCHAR (254),
		COL10 VARCHAR(100), 	-- По месту использования
		FCOL10 VARCHAR (254),
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TABLE_R1_1 (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, ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

	--- Данные листа 02 ---
	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 #TEMP (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),	-- Показатель
		COL3 VARCHAR (100), 	-- Сумма
		FCOL3 VARCHAR,
		COL4 VARCHAR(100), 	-- Ставка
		FCOL4 varchar,
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TEMP (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'

	EXECUTE (@strEXEC)

	--- Формирование XML ---
	SELECT @FNAME_ID = 'NO_PRIB_' + 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.02">')


	--- Документ ---
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Документ КНД="1151006"')
	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, 'КодНО="' + @SONO + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НомКорр="0"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ПоМесту="214"')
	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 (@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, '<НПЮЛ')
	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, '/>')

	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, '<ФИО')
	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, '<Прибыль>')
	
	--- Раздел 1 ---
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НалПУ>')
	--- 1.1. для организаций, уплачивающих авансовые платежи и налог на прибыль организаций ---
	--- ОКАТО ---
	SELECT @OKATO = COL2
	FROM #TABLE_R1_1 

	IF ISNULL (@OKATO, '') = ''
		SET @OKATO = ISNULL (@OKATO_D, '')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НалПУАв ТипНП="1" ОКАТО="'
		+ @OKATO + '">')

	-- Фед. бюджет --
	SELECT @KBK = COL3,
		@SUMMA1 = COL4,
		@SUMMA2 = COL5
	FROM #TABLE_R1_1 

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ФедБдж')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КБК="' + RTRIM (@KBK) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + RTRIM (@SUMMA2) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '/>')	

	-- Бюджет субъекта --
	SELECT @KBK = COL6,
		@SUMMA1 = COL7,
		@SUMMA2 = COL8
	FROM #TABLE_R1_1 

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СубБдж')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КБК="' + RTRIM (@KBK) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + RTRIM (@SUMMA2) + '"')
	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, '</НалПУ>')

	--- Лист 02 ---
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасчНал')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ТипНП="1"')

	--- Таблица ---
	DECLARE #DATA_CURSOR CURSOR LOCAL STATIC	
		FOR SELECT CODE,
			COL1,
			COL3,
			COL4
		FROM #TEMP
		ORDER BY ORDERS

	OPEN #DATA_CURSOR

	FETCH FROM #DATA_CURSOR
		INTO @CODE,
			@COL1, 
			@COL3, 
			@COL4 


	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @strINS_VALUE = CASE
					WHEN @CODE = '010' THEN 'ДохРеал="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '020' THEN 'ДохВнереал="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '030' THEN 'РасхУмРеал="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '040' THEN 'РасхВнереал="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '050' THEN 'Убытки="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '060' THEN 'ПрибУб="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '070' THEN 'ДохИсклПриб="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '080' THEN 'ПрибБРСт0="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '090' THEN 'СумЛьгот="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '100' THEN 'НалБаза="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '110' THEN 'УбытУмНБ="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '120' THEN 'НалБазаИсч="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '130' THEN 'НалБазаИсчСуб="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '140' THEN 'СтавНалВсего="' +  ISNULL (@COL4, '0') + '"'
					WHEN @CODE = '150' THEN 'СтавНалФБ="' +  ISNULL (@COL4, '0') + '"'
					WHEN @CODE = '160' THEN 'СтавНалСуб="' +  ISNULL (@COL4, '0') + '"'
					WHEN @CODE = '170' THEN 'СтавНалСуб284="' +  ISNULL (@COL4, '0') + '"'
					WHEN @CODE = '180' THEN 'НалИсчисл="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '190' THEN 'НалИсчислФБ="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '200' THEN 'НалИсчислСуб="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '210' THEN 'АвНачисл="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '220' THEN 'АвНачислФБ="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '230' THEN 'АвНачислСуб="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '240' THEN 'НалВыпл311="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '250' THEN 'НалВыпл311ФБ="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '260' THEN 'НалВыпл311Суб="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '270' THEN 'НалДоплФБ="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '271' THEN 'НалДоплСуб="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '280' THEN 'НалУменФБ="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '281' THEN 'НалУменСуб="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '290' THEN 'АвПлатМес="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '300' THEN 'АвПлатМесФБ="' +  ISNULL (@COL3, '0') + '"'
					WHEN @CODE = '310' THEN 'АвПлатМесСуб="' +  ISNULL (@COL3, '0') + '"'
					ELSE ''
				END	
				
		IF LEN (@strINS_VALUE) > 0
			INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, @strINS_VALUE)

		FETCH NEXT FROM #DATA_CURSOR
			INTO @CODE,
				@COL1, 
				@COL3, 
				@COL4 
	END	--- WHILE @@FETCH_STATUS = 0

	CLOSE #DATA_CURSOR
	DEALLOCATE #DATA_CURSOR
	------------------------------
	------------------------------
	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, '</Файл>')

	DROP TABLE #TASK_PROP

	DROP TABLE #TEMP
	DROP TABLE #TABLE_R1_1

	SELECT * FROM @OUTPUT ORDER BY [ID]
END 



GO


GRANT EXECUTE ON dbo.[BK_EXPORT_F1151006] TO PUBLIC

GO


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

GO
CREATE PROCEDURE dbo.BK_CREATE_PROV_MOVE_INV_GRP
		@intDOC_LINK	INT,
		@intDEL_OLD		TINYINT = 0
AS
BEGIN
	DECLARE
		@intTO_MZ		INT,
		@intTO_OS		INT,
		@intTO_TMC		INT, 
		@intTO_SERV		INT,
		@intKIND_DOC		INT ,
		@intTYPE_NUMBER		INT, 

		@intOBJ_REF		INT,
		@intACC_LINK	INT,
		@intDEP_LINK	INT,
		
		@intAC_DOC_B	INT,
		@intAC_DOC_A	INT,
		@intKBK_DOC		INT,

		@intLINK_EMPL	INT,
		@intLINK_SUB	INT,
		@intLINK_KBK	INT,
		@strDOC_NUMBER	VARCHAR (25),
		@strINVOICE_NUMBER	VARCHAR (25),
		@dDOC_DATE		DATETIME,
		@intSELLER		INT,
		@intDOG_LINK	INT,
		@intDOG_TYPE	INT,
		@intLINK_OSNOV	INT,
		@intLINK_TO	INT,
		@intERROR	INT,
		@intNOT_SGU_401	INT,

	-- Табличная часть
		@cTYPE_INV			VARCHAR (30),
		@intLINK_INV		INT,
		@strINV_CODE		VARCHAR (20),
		@strNEW_INV_CODE	VARCHAR (20),
		@intNEW_GRP_LINK	INT,
		@intNEW_GRP_CODE	VARCHAR (10),
		@intACC_101			INT,
		@intACC_104			INT,
		@nBALANCE			NUMERIC (20,2),
		@nAMORT				NUMERIC (20,2),

		@intSTEP1	INT,	-- 1=Баланс\2=амортизация
		@intSTEP2	INT,	-- 1=Списание со 101(104)\2=Счет новый 101(104)
		
		@cGRID_SOURCE	CHAR (1),

		@intDEP_LINK1	INT,

		@intNEW_NOMEN	INT,
		@intOLD_NOMEN	INT,

		--- Для создания номеклатуры ---
		@strNOM_CODE	VARCHAR (20),
		@strNOM_NAME	VARCHAR (254),
		@intGRP_INV	INT,
		@intUM		INT,
		@strSERIES	VARCHAR (30),
		@strGRP_CODE	VARCHAR (5),
		@bitIS_EXTRA	BIT,
		@intLINK_OKDP INT,
		@nCOEFF NUMERIC (18,9),
		@intPRICE_TYPE TINYINT,
		@intLINK_OKPD INT,
		@nCOEFF_OKPD NUMERIC (18,9),
		@intISUSED	TINYINT,

		@SUM		NUMERIC (28,4),
		@SUM_NALOG	NUMERIC (28,4),
		@SUMMA_ALL	NUMERIC (28,4),
		@LINK_EKR	INT,
		@cCODE_EKR	VARCHAR (3),
		@intROWCOUNT	INT,

	/* -- 20070317 -- */
		@cSOURCE	CHAR (1),
		@cSINTH	CHAR (3),
		@cANALIT CHAR (3),
		@cANALIT_NEW_B CHAR (3),
		@cFIN_SOURCE_NEW CHAR (1),
		@cFIN_SOURCE_OLD CHAR (1),
		@intP_EKR	TINYINT,
		@p_KASSA	TINYINT,
		@intKBK_DEFAULT	INT,
		@intBUH_TYPE	TINYINT,

		@intSGU_241	INT,
		@intSGU_180	INT,
		
	/* --- РАБОТА С G_PROV1 --- */
		@intLINK_G1	INT,
		@strNAME_OPER	VARCHAR (254),
		@intORDERS	INT,

	/* --- РАБОТА С G_PROV2 --- */
		@intLINK_G2	INT,
		@intECON_OPER	INT,
		@intSTORNO	INT,
		@strNAME_OPER2	VARCHAR (254),
		@strNAME_OPER21	VARCHAR (254),
		@intLINK_G2_TO	INT,
		@SUMMA_G2	NUMERIC (28,4),
			
		@D_SUMMA	NUMERIC (28,4),
		@K_SUMMA	NUMERIC (28,4),
		@QTY		NUMERIC (28,4),

	/* --- РАБОТА С G_PROV_AP --- */
		@intSGU		INT,
		@intACCOUNT	INT,
		@intAP_KBK	INT,
		@intEKR		INT,
		@intKAU		INT,
		@intDB_KR	TINYINT,
		@intAP_DEP	INT,
		@intAP_SUB	INT,
		@intAP_EMP	INT,
		@intAP_ACC	INT,
		@intAP_NOMEN	INT,
		@AP_INDATE	DATETIME,
		@intAP_INV	INT,
		@intAP_TMC	INT,
		@intAP1		INT,
		@intAP2		INT,
		@intAP3		INT,

	--- ТАБЛИЦА АНАЛИТИЧЕСКИХ ПРИЗНАКОВ ---
		@intSGU_DT	INT,
		@intACCOUNT_DT	INT,
		@intAP_KBK_DT	INT,
		@intEKR_DT		INT,
		@intKAU_DT		INT,
		@intDB_KR_DT	TINYINT,
		@intAP_DEP_DT	INT,
		@intAP_SUB_DT	INT,
		@intAP_EMP_DT	INT,
		@intAP_ACC_DT	INT,
		@intAP_NOMEN_DT	INT,
		@intAP_INDATE_DT	INT,
		@intAP_INV_DT	INT,
		@intAP_TMC_DT	INT,
		@intAP1_DT		INT,
		@intAP2_DT		INT,
		@intAP3_DT		INT,

		@intSGU_KT	INT,
		@intACCOUNT_KT	INT,
		@intAP_KBK_KT	INT,
		@intEKR_KT		INT,
		@intKAU_KT		INT,
		@intDB_KR_KT	TINYINT,
		@intAP_DEP_KT	INT,
		@intAP_SUB_KT	INT,
		@intAP_EMP_KT	INT,
		@intAP_ACC_KT	INT,
		@intAP_NOMEN_KT	INT,
		@intAP_INDATE_KT	INT,
		@intAP_INV_KT	INT,
		@intAP_TMC_KT	INT,
		@intAP1_KT		INT,
		@intAP2_KT		INT,
		@intAP3_KT		INT,

		@dDATE_REST		DATETIME

	--- ЧИСТИМ ПРОТОКОЛ ОТ ОШИБОЧНЫХ ЗАПИСЕЙ ---
	DELETE T1
	FROM dbo.PROTOKOL_MOVE_INV_GRP T1
	LEFT JOIN dbo.NOMENCLATURE NOM_NEW ON (NOM_NEW.LINK = T1.NOMEN_NEW)
	LEFT JOIN dbo.NOMENCLATURE NOM_OLD ON (NOM_OLD.LINK = T1.NOMEN_OLD)
	WHERE NOM_NEW.LINK IS NULL
		OR NOM_OLD.LINK IS NULL

	--- !!!СОХРАНЯЕМ ПРОВОДКИ!!! --- 
	IF @intDEL_OLD = 1
	BEGIN
		DELETE FROM dbo.G_PROV1 WHERE LINK_UP = @intDOC_LINK
		SET @intERROR = @@ERROR
		IF @intERROR <> 0
			RETURN @intERROR
	END

	SELECT
		@intDEP_LINK = DOC.DEP_LINK,
		@dDOC_DATE = DOC.[DATE],
		@intAC_DOC_B	= DOC.LN_AC_B,
		@intAC_DOC_A	= DOC.LN_AC_A,
		@intKBK_DOC = DOC.LN_KBK,
		@intNEW_GRP_LINK = DOC.LN_GRP,
		@intNEW_GRP_CODE = DOC.CD_GRP,
		@intBUH_TYPE = DEP.BUH_TYPE,
		@intNOT_SGU_401 = SGU_401
	FROM dbo.DOC_CONV_MOVE_INV_GRP DOC
	INNER JOIN dbo.DEPARTMENTS DEP ON (DEP.LINK = DOC.DEP_LINK)
	WHERE DOC.LINK = @intDOC_LINK

	IF ISNULL (@intNOT_SGU_401, 0) = 0
	BEGIN
		SELECT @intSGU_241 = LINK FROM dbo.KOSGU WHERE CODE = '241'
		SELECT @intSGU_180 = LINK FROM dbo.KOSGU WHERE CODE = '180'
	END
	ELSE
		SELECT @intSGU_241 = LINK, @intSGU_180 = LINK FROM dbo.KOSGU WHERE CODE = '000'

	SET @dDATE_REST = DATEADD (DAY, 1, @dDOC_DATE)

	DECLARE #DATA_CURSOR CURSOR LOCAL STATIC	
		FOR SELECT TYPE_INV,
			INV_LINK,
			INV_CODE,
			INV_CODE1,
			AC_LN_OLD1,
			AC_LN_OLD2,
			BALANCE,
			AMORT
		FROM dbo.DOC_CONV_MOVE_INV_GRP_TABLE 
		WHERE LINK_UP = @intDOC_LINK

	OPEN #DATA_CURSOR
	FETCH FROM #DATA_CURSOR
		INTO @cTYPE_INV, @intLINK_INV, @strINV_CODE, @strNEW_INV_CODE,
			@intACC_101, @intACC_104, @nBALANCE, @nAMORT

	WHILE @@FETCH_STATUS = 0
	BEGIN
		
		-- ЗАПИСЬ В G_PROV1 --
		SELECT	@strNAME_OPER = 'Перенос остатков по НФА № ' + @strINV_CODE
		SET	@intORDERS = COALESCE ((SELECT MAX (ORDERS) FROM G_PROV1 WHERE LINK_UP = @intDOC_LINK), 0) + 1
		
		SET @intLINK_G1 = NULL
		EXEC @intERROR = dbo.X_UPDATE_G_PROV1 @intLINK_G1 OUTPUT, @intDOC_LINK, @intLINK_TO,
			@strNAME_OPER, @intORDERS
		IF @intERROR <> 0
			RETURN @intERROR

		IF @intLINK_G1 IS NULL
		BEGIN
			FETCH NEXT FROM #DATA_CURSOR
				INTO @cTYPE_INV, @intLINK_INV, @strINV_CODE, @strNEW_INV_CODE,
					@intACC_101, @intACC_104, @nBALANCE, @nAMORT
			CONTINUE
		END

		SET @intAP_NOMEN = CASE WHEN @cTYPE_INV IN ('DICTIONARY_SERV', 'BV_NOMENCLATURE') THEN @intLINK_INV ELSE NULL END
		SET @intAP_INV = CASE WHEN @cTYPE_INV = 'INVENTORY_CARD' THEN @intLINK_INV ELSE NULL END
		SET @intAP_TMC	= CASE WHEN @cTYPE_INV = 'DICTIONARY_TMC' THEN @intLINK_INV ELSE NULL END

		-- !!!ПЕРЕВОДИМ ОСТАТКИ!!! --
		SET @intSTEP1 = 0
		WHILE @intSTEP1 < 2
		BEGIN
			SELECT @intSTEP1 = @intSTEP1 + 1
			IF @intSTEP1 = 1		-- @intSTEP1 = 1 баланс. стоимость
				SELECT @intACCOUNT = @intACC_101
			ELSE	-- @intSTEP1 = 2 амортиация
				SELECT @intACCOUNT = @intACC_104
			
			IF @intACCOUNT IS NULL
				CONTINUE

			DECLARE #CURSOR_REST CURSOR STATIC LOCAL
			FOR SELECT R.ACCOUNT, R.KBK, R.EKR, R.DEP, R.SUB,
						R.EMP, R.KAU, R.DEP_ACC, R.INDATE,
						R.AP1, R.AP2, R.AP3, R.D_QUANTITY, R.D_SUMMA, R.K_SUMMA,
						SA.cSINTH, SA.cANALIT, SA.cSOURCE
				FROM dbo.ARestTableByDate (@dDATE_REST, @intACCOUNT) R
				INNER JOIN dbo.S_ACCOUNTS SA ON (SA.LINK = R.ACCOUNT)
				WHERE R.DEP_LINK = @intDEP_LINK
					AND	((@intAP_NOMEN IS NOT NULL AND R.NOMEN = @intLINK_INV)
						OR (@intAP_INV IS NOT NULL AND R.INV = @intLINK_INV)
						OR (@intAP_TMC IS NOT NULL AND R.TMC = @intLINK_INV))

			OPEN #CURSOR_REST 
			
			FETCH FROM #CURSOR_REST
				INTO @intACCOUNT, @intLINK_KBK, @LINK_EKR,
						@intAP_DEP, @intLINK_SUB, @intLINK_EMPL, @intKAU,
						@intACC_LINK, @AP_INDATE, @intAP1, @intAP2, @intAP3,
						@QTY, @D_SUMMA, @K_SUMMA,
						@cSINTH, @cANALIT, @cFIN_SOURCE_OLD
			
			WHILE @@FETCH_STATUS = 0
			BEGIN
				SET @intSTEP2 = 0
				WHILE @intSTEP2 < 2
				BEGIN
					SELECT @intSGU_DT = NULL, @intSGU_KT = NULL,
							@intEKR_DT = @LINK_EKR, @intEKR_KT = @LINK_EKR

					SET @intSTEP2 = @intSTEP2 + 1

					IF @intSTEP2 = 1	--- Отдельный КБК для учета имущества казны ---
						SELECT @intAP_KBK_DT = @intLINK_KBK, @intAP_KBK_KT = @intLINK_KBK

					IF @intSTEP1 = 1		-- !!!Балансовая стоимсоть!!! 
						IF @intSTEP2 = 1	-- Списание балансовой стоимости --
						BEGIN
							SELECT @intACCOUNT_KT = @intACCOUNT,
									@intACCOUNT_DT = dbo.BK_GetDBKTAccount (@intACCOUNT, '401', '30', DEFAULT),
									@SUMMA_G2 = ISNULL (@D_SUMMA, 0), @QTY = ISNULL (@QTY, 0),
									@strNAME_OPER2 = 'Списание балансовой стоимости'

							EXEC dbo.BX_BPROV_GET_DEFAULT_SGU @intACCOUNT_KT, 1, @intSGU_KT OUTPUT
							SELECT @intSGU_DT = @intSGU_241

							IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS
										WHERE LINK = @intACCOUNT_DT
											AND P_KASSA = 1)
								SET @intEKR_DT = @intSGU_DT
						END
						ELSE	-- @intSTEP2 = 2 Счет новый --
						BEGIN
							SELECT @intAP_KBK_DT = ISNULL (@intKBK_DOC, @intLINK_KBK),
								@intAP_KBK_KT = @intLINK_KBK

							SET @cFIN_SOURCE_NEW = @cFIN_SOURCE_OLD 

							IF ISNULL (@intAC_DOC_B, 0) = 0
							BEGIN 
								SET @cANALIT_NEW_B = (SELECT SA.cANALIT
											FROM dbo.GROUP_INV G
											INNER JOIN dbo.S_ACCOUTS SA
												ON (SA.LINK = G.ACCOUNT)
											WHERE LINK = @intNEW_GRP_LINK)
					
								SET @intACCOUNT_DT = dbo.BK_GetDBKTAccount (@intACCOUNT, DEFAULT, @cANALIT_NEW_B, @cFIN_SOURCE_NEW)
							END
							ELSE
								IF dbo.AccountsHasNoChild (@intAC_DOC_B) = 1
									SET @intACCOUNT_DT = @intAC_DOC_B
								ELSE
									SET @intACCOUNT_DT = dbo.BK_GetDBKTAccount (@intAC_DOC_B, DEFAULT, DEFAULT, @cFIN_SOURCE_NEW)

							SELECT @intACCOUNT_KT = dbo.BK_GetDBKTAccount (@intACCOUNT, '401', '30', DEFAULT),
									@SUMMA_G2 = ISNULL (@D_SUMMA, 0), @QTY = ISNULL (@QTY, 0),
									@strNAME_OPER2 = 'Стоимость НФА'

							exec dbo.BX_BPROV_GET_DEFAULT_SGU @intACCOUNT_DT, 0, @intSGU_DT output
							SELECT @intSGU_KT = @intSGU_180
							IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS
										WHERE LINK = @intACCOUNT_KT
											AND P_KASSA = 1)
								SET @intEKR_KT = @intSGU_KT
						END
					ELSE	-- @intSTEP1 = 2 !!!Амортизация!!! 
						IF @intSTEP2 = 1	-- Списание амортизации --
						BEGIN
							SELECT @intACCOUNT_DT = @intACCOUNT,
									@intACCOUNT_KT = dbo.BK_GetDBKTAccount (@intACCOUNT, '401', '30', DEFAULT),
									@SUMMA_G2 = ISNULL (@K_SUMMA, 0), @QTY = 0,
									@strNAME_OPER2 = 'Списание амортизации'

							exec dbo.BX_BPROV_GET_DEFAULT_SGU @intACCOUNT_DT, 0, @intSGU_DT output
							IF @intSGU_DT IS NULL 
								SELECT @intSGU_DT = (SELECT TOP 1 LINK_SGU
											FROM dbo.S_ACCOUNTS_SGU WHERE ACCOUNT = @intACCOUNT_DT)

							SELECT @intSGU_KT = @intSGU_241
							IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS
										WHERE LINK = @intACCOUNT_KT
											AND P_KASSA = 1)
								SET @intEKR_KT = @intSGU_KT
						END
						ELSE	-- @intSTEP2 = 2 Счет новый --
						BEGIN
							SELECT @intAP_KBK_DT = @intLINK_KBK,
								@intAP_KBK_KT = ISNULL (@intKBK_DOC, @intLINK_KBK)

							IF ISNULL (@intAC_DOC_A, 0) = 0
							BEGIN 
								SET @cANALIT_NEW_B = (SELECT SA.cANALIT
											FROM dbo.GROUP_INV G
											INNER JOIN dbo.S_ACCOUTS SA
												ON (SA.LINK = G.ACCOUNT_AM)
											WHERE LINK = @intNEW_GRP_LINK)
					
								SET @intACCOUNT_KT = dbo.BK_GetDBKTAccount (@intACCOUNT, DEFAULT, @cANALIT_NEW_B, @cFIN_SOURCE_NEW)
							END
							ELSE
								IF dbo.AccountsHasNoChild (@intAC_DOC_A) = 1
									SET @intACCOUNT_KT = @intAC_DOC_A
								ELSE
									SET @intACCOUNT_KT = dbo.BK_GetDBKTAccount (@intAC_DOC_A, DEFAULT, DEFAULT, @cFIN_SOURCE_NEW)

							SELECT @intACCOUNT_DT = dbo.BK_GetDBKTAccount (@intACCOUNT, '401', '30', DEFAULT),
									@SUMMA_G2 = ISNULL (@K_SUMMA, 0), @QTY = 0,
									@strNAME_OPER2 = 'Амортиация ОС'

							exec dbo.BX_BPROV_GET_DEFAULT_SGU @intACCOUNT_KT, 1, @intSGU_KT output
							IF @intSGU_KT IS NULL 
								SELECT @intSGU_KT = (SELECT TOP 1 LINK_SGU
											FROM dbo.S_ACCOUNTS_SGU WHERE ACCOUNT = @intACCOUNT_KT)

							SELECT @intSGU_DT = @intSGU_180
							IF EXISTS (SELECT * FROM dbo.S_ACCOUNTS
										WHERE LINK = @intACCOUNT_DT
											AND P_KASSA = 1)
								SET @intEKR_DT = @intSGU_DT
						END
					
					SET @intLINK_G2 = NULL
					SET	@intORDERS = COALESCE ((SELECT MAX (ORDERS)
												FROM G_PROV2 WHERE LINK_UP = @intLINK_G1), 0) + 1
					EXEC @intERROR = dbo.X_UPDATE_G_PROV2 @intLINK_G2 OUTPUT, @intLINK_G1, NULL,
								@SUMMA_G2, @QTY, 0, @strNAME_OPER2, @intECON_OPER, @intORDERS
					IF @intERROR <> 0
						RETURN @intERROR

					IF @intLINK_G2 IS NULL 
						OR @intACCOUNT_DT IS NULL
						OR @intACCOUNT_KT IS NULL
					BEGIN
						FETCH NEXT FROM #CURSOR_REST
							INTO @intACCOUNT, @intLINK_KBK, @LINK_EKR,
									@intAP_DEP, @intLINK_SUB, @intLINK_EMPL, @intKAU,
									@intACC_LINK, @AP_INDATE, @intAP1, @intAP2, @intAP3,
									@QTY, @D_SUMMA, @K_SUMMA,
									@cSINTH, @cANALIT, @cFIN_SOURCE_OLD
						CONTINUE
					END
					
					--- СОХРАНЯЕМ ДБ ---
					EXEC @intERROR = dbo.X_UPDATE_G_PROV_AP @intLINK_G2, 0, @intACCOUNT_DT,
								@intAP_KBK_DT, @intEKR_DT, @intAP_DEP,
								@intLINK_SUB, @intLINK_EMPL, @intAP_NOMEN, @intAP_INV,
								@intKAU, @intACC_LINK, 
								@intAP_TMC, @AP_INDATE, @intAP1, @intAP2, @intAP3, @intSGU_DT

					--- СОХРАНЯЕМ КТ ---
					EXEC @intERROR = dbo.X_UPDATE_G_PROV_AP @intLINK_G2, 1, @intACCOUNT_KT,
								@intAP_KBK_KT, @intEKR_KT, @intAP_DEP,
								@intLINK_SUB, @intLINK_EMPL, @intAP_NOMEN, @intAP_INV,
								@intKAU, @intACC_LINK, 
								@intAP_TMC, @AP_INDATE, @intAP1, @intAP2, @intAP3, @intSGU_KT

				END		-- @intSTEP2 < 2
				FETCH NEXT FROM #CURSOR_REST
					INTO @intACCOUNT, @intLINK_KBK, @LINK_EKR,
							@intAP_DEP, @intLINK_SUB, @intLINK_EMPL, @intKAU,
							@intACC_LINK, @AP_INDATE, @intAP1, @intAP2, @intAP3,
							@QTY, @D_SUMMA, @K_SUMMA,
							@cSINTH, @cANALIT, @cFIN_SOURCE_OLD
			END	-- #CURSOR_REST

			CLOSE #CURSOR_REST
			DEALLOCATE #CURSOR_REST

			IF @cTYPE_INV = 'BV_NOMENCLATURE' 
				SELECT @intSTEP1 = 2
		END		-- @intSTEP1 < 2

		IF NOT EXISTS (SELECT * FROM dbo.G_PROV2 WHERE LINK_UP = @intLINK_G1)
			DELETE FROM dbo.G_PROV1 WHERE LINK = @intLINK_G1

		---!!!ПЕРЕНОС МАТ.ЦЕННОСТЕЙ НА НОВЫЕ ГРУППЫ!!!---
		SELECT @intNEW_NOMEN = NULL, @intOLD_NOMEN = NULL
		IF @cTYPE_INV = 'INVENTORY_CARD' 
		BEGIN
			SELECT
				@intOLD_NOMEN = T1.NOMENCLATURE,
				@intNEW_NOMEN = T3.LINK
			FROM dbo.INVENTORY T1
			LEFT JOIN dbo.PROTOKOL_MOVE_INV_GRP T2 ON (T2.NOMEN_OLD = T1.NOMENCLATURE)
			LEFT JOIN dbo.NOMENCLATURE T3 ON (T3.LINK = T2.NOMEN_NEW)
			WHERE T1.LINK = @intLINK_INV

			--- Создание новой записи в номенклаторе ---
			IF @intNEW_NOMEN IS NULL
			BEGIN
				SELECT 
					@strNOM_NAME = N.[NAME],
					@intUM 	= N.UM,
					@strSERIES	= N.SERIES,
					@bitIS_EXTRA	=  N.IS_EXTRA,
					@intLINK_OKDP = O.LINK,
					@nCOEFF = N.COEFF,
					@intPRICE_TYPE = N.PRICE_TYPE,
					@intLINK_OKPD =	LINK_OKPD,
					@nCOEFF_OKPD =	COEFF_OKPD,
					@intISUSED	=	ISUSED
				FROM dbo.NOMENCLATURE N
				LEFT JOIN dbo.OKDP O ON (O.LINK = N.LINK_OKDP)
				WHERE N.LINK = @intOLD_NOMEN

				EXEC @intERROR = dbo.BV_GET_NOMEN_NEXT_CCODE @strNOM_CODE OUTPUT, @intNEW_GRP_CODE
				IF @intERROR <> 0
					RETURN @intERROR

				EXEC @intERROR = dbo.BV_SAVE_NOMENCLATURE 
						@varKSparLINK		=	@intNEW_NOMEN OUTPUT,
						@varKSparLINK_GRP	=	@intNEW_GRP_LINK,
						@varKSparCODE		=	@strNOM_CODE,
						@varKSparNAME		=	@strNOM_NAME,
						@varKSparSERIES		=	@strSERIES,
						@varKSparLINK_UM	=	@intUM,
						@lbIS_EXTRA			=	@bitIS_EXTRA,
						@varKSparLINK_OKDP	=	@intLINK_OKDP,
						@varKSparLINK_OKPD	=	@intLINK_OKPD,
						@nCOEFF			=	@nCOEFF,
						@nCOEFF_OKPD	=	@nCOEFF_OKPD,
						@intPRICE_TYPE		=	@intPRICE_TYPE,
						@intISUSED	= @intISUSED

				IF @intERROR <> 0
					RETURN @intERROR
			END	-- IF @intNEW_NOMEN IS NULL
			
			IF ISNULL (@strNEW_INV_CODE, '') = ''
				SELECT @strNEW_INV_CODE = @strINV_CODE

			UPDATE dbo.INVENTORY SET NOMENCLATURE = @intNEW_NOMEN,
					CODE = @strNEW_INV_CODE
			WHERE LINK = @intLINK_INV

			INSERT INTO dbo.PROTOKOL_MOVE_INV_GRP (NOMEN_OLD, INV, NOMEN_NEW)
			VALUES (@intOLD_NOMEN, @intLINK_INV, @intNEW_NOMEN)
		END	-- IF @cTYPE_INV = 'INVENTORY_CARD' 

		IF @cTYPE_INV = 'BV_NOMENCLATURE' 
		BEGIN
		--- Перенос на новую группу ---
			UPDATE dbo.NOMENCLATURE SET GROUP_INV = @intNEW_GRP_LINK,
						CODE = @strNEW_INV_CODE
			WHERE LINK = @intLINK_INV
		END	-- @cTYPE_INV = 'BV_NOMENCLATURE' 

		FETCH NEXT FROM #DATA_CURSOR
			INTO @cTYPE_INV, @intLINK_INV, @strINV_CODE, @strNEW_INV_CODE,
				@intACC_101, @intACC_104, @nBALANCE, @nAMORT
	END	-- #DATA_CURSOR

	CLOSE #DATA_CURSOR
	DEALLOCATE #DATA_CURSOR

	UPDATE dbo.G_PROV SET SUMMA = ISNULL(dbo.CalcDocSumma(LINK), 0)
	WHERE LINK = @intDOC_LINK
END

GO

GRANT EXECUTE ON dbo.[BK_CREATE_PROV_MOVE_INV_GRP] TO PUBLIC

GO


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


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

GO
CREATE PROCEDURE dbo.BK_EXPORT_F1151006_503 (@iLINK_FORM INT)
AS
BEGIN

--перенос формы из архивной базы
exec 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),
		@POST_GL_BUH	VARCHAR (254),
		@DEP_NAME VARCHAR (254),

		@SONO VARCHAR (4),

		@DOC_ID		VARCHAR (36),

		@NAME_RUK	VARCHAR (60),
		@FAM_RUK	VARCHAR (60),
		@OT_RUK		VARCHAR (60),

		@NAME_GL_BUH	VARCHAR (60),
		@FAM_GL_BUH	VARCHAR (60),
		@OT_GL_BUH	VARCHAR (60),

		@dDATE_FORM	DATETIME,
		@PERIOD_TYPE	INT,
		@PERIOD_NUM	INT,
		@cPERIOD_NUM	VARCHAR (2),

		@iLINK_TABLE	INT,
		@PROC_NAME	VARCHAR (254),

		--- Раздел 1 ---
		@OKATO_D VARCHAR (15),
		@OKATO VARCHAR (15),
		
		@KBK VARCHAR (30),
		@SUMMA1 VARCHAR (100),
		@SUMMA2 VARCHAR (100),
		@NUM_KOR	VARCHAR (3),
		@PLACE_USED	VARCHAR (3),

		--- Лист 02 ---
		@CODE VARCHAR (50),
		@COL1 VARCHAR (50),
		@COL3 NUMERIC (20,4), 	
		@COL4 NUMERIC (20,4), 	

		@strINS_VALUE	VARCHAR (100),

		@strEXEC	VARCHAR (8000)
	--- ---
	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

	SET @cPERIOD_NUM = CASE
				WHEN @PERIOD_TYPE = 1 THEN '34'	-- ПЕРИОД ГОД
				WHEN @PERIOD_TYPE = 2 THEN 	-- ПЕРИОД КВАРТАЛ
					CASE 
						WHEN @PERIOD_NUM = 1 THEN '21'
						WHEN @PERIOD_NUM = 2 THEN '31'
						WHEN @PERIOD_NUM = 3 THEN '33'
					END
				WHEN @PERIOD_TYPE = 4 THEN LTRIM (STR (34 + @PERIOD_NUM ))
			END

	EXEC dbo.GetRandStr 36, @DOC_ID OUTPUT

	SELECT @PART_NAME_NNN = @DOC_ID

	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],
			@OKATO_D = CONVERT (VARCHAR (11), REPLACE (OKATO, ' ', '')),
			@SONO = CONVERT (VARCHAR (4), ISNULL (IMNS, ''))
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @DEP_LINK

	SET @DEP_NAME = REPLACE (@DEP_NAME, '"', '&quot;')

	SELECT @TLF_GL_BUH = A.PHONE,
		@POST_GL_BUH = B.POST_NAME,

		@NAME_GL_BUH = B.IM,
		@FAM_GL_BUH = B.FM,
		@OT_GL_BUH = B.OT

	FROM dbo.DICTIONARY_OTV_FACE A
	LEFT JOIN dbo.KU_EMPL_PLACING B ON (B.LINK = A.FACE_LINK)
	WHERE A.DEP_LINK = @DEP_LINK
		AND A.[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.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 #TABLE_R1_1 (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), 	-- Сумма1 (ФБ)
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Сумма2 (ФБ)
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- КБК (Субъект)
		FCOL6 VARCHAR (254),
		COL7 VARCHAR(100), 	-- Сумма1 (Субъект)
		FCOL7 VARCHAR (254),
		COL8 VARCHAR(100), 	-- Сумма2 (Субъект)
		FCOL8 VARCHAR (254),
		COL9 VARCHAR(100), 	-- Номер корректировки
		FCOL9 VARCHAR (254),
		COL10 VARCHAR(100), 	-- По месту использования
		FCOL10 VARCHAR (254),
		ITOG NUMERIC (20)) 	
	
	SET @strEXEC = 'INSERT INTO #TABLE_R1_1 (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, ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

	--- Данные листа 02 ---
	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 #TEMP (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),	-- Показатель
		COL3 NUMERIC (20,4), 	-- Сумма
		FCOL3 VARCHAR (8000),
		COL4 NUMERIC (20,4), 	-- Ставка
		FCOL4 varchar (8000),
		ITOG NUMERIC (20,4)) 	
	
	SET @strEXEC = 'INSERT INTO #TEMP (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'

	EXECUTE (@strEXEC)

	--- Формирование XML ---
	SELECT @FNAME_ID = 'NO_PRIB_' + 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">')


	--- Документ ---
	SELECT @NUM_KOR = COL9,
		@PLACE_USED = COL10
	FROM #TABLE_R1_1

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Документ КНД="1151006"')
	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, 'КодНО="' + @SONO + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НомКорр="' + ISNULL (@NUM_KOR, '0') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ПоМесту="' + ISNULL (@PLACE_USED, '214') + '"')
	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 (@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, '<НПЮЛ')
	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, '/>')

	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, '<ФИО')
	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, '<Прибыль>')
	
	--- Раздел 1 ---
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НалПУ>')
	--- 1.1. для организаций, уплачивающих авансовые платежи и налог на прибыль организаций ---
	--- ОКАТО ---
	SELECT @OKATO = COL2
	FROM #TABLE_R1_1 

	IF ISNULL (@OKATO, '') = ''
		SET @OKATO = ISNULL (@OKATO_D, '')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НалПУАв ТипНП="1" ОКАТО="'
		+ @OKATO + '">')

	-- Фед. бюджет --
	SELECT @KBK = COL3,
		@SUMMA1 = COL4,
		@SUMMA2 = COL5
	FROM #TABLE_R1_1 

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ФедБдж')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КБК="' + RTRIM (@KBK) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + RTRIM (@SUMMA2) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '/>')	

	-- Бюджет субъекта --
	SELECT @KBK = COL6,
		@SUMMA1 = COL7,
		@SUMMA2 = COL8
	FROM #TABLE_R1_1 

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СубБдж')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КБК="' + RTRIM (@KBK) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + RTRIM (@SUMMA2) + '"')
	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, '</НалПУ>')

	--- Лист 02 ---
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасчНал')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ТипНП="1"')

	--- Таблица ---
	DECLARE #DATA_CURSOR CURSOR LOCAL STATIC	
		FOR SELECT CODE,
			COL1,
			COL3,
			COL4
		FROM #TEMP
		ORDER BY ORDERS

	OPEN #DATA_CURSOR

	FETCH FROM #DATA_CURSOR
		INTO @CODE,
			@COL1, 
			@COL3, 
			@COL4 


	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @strINS_VALUE = CASE
					WHEN @CODE = '010' THEN 'ДохРеал="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '020' THEN 'ДохВнереал="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '030' THEN 'РасхУмРеал="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '040' THEN 'РасхВнереал="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '050' THEN 'Убытки="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '060' THEN 'ПрибУб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '070' THEN 'ДохИсклПриб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '080' THEN 'ПрибБРСт0="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '090' THEN 'СумЛьгот="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '100' THEN 'НалБаза="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '110' THEN 'УбытУмНБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '120' THEN 'НалБазаИсч="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '130' THEN 'НалБазаИсчСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '140' THEN 'СтавНалВсего="' + LTRIM (STR (ISNULL (@COL4, 0), 20, 2)) + '"'
					WHEN @CODE = '150' THEN 'СтавНалФБ="' + LTRIM (STR (ISNULL (@COL4, 0), 20, 2)) + '"'
					WHEN @CODE = '160' THEN 'СтавНалСуб="' + LTRIM (STR (ISNULL (@COL4, 0), 20, 2)) + '"'
					WHEN @CODE = '170' THEN 'СтавНалСуб284="' + LTRIM (STR (ISNULL (@COL4, 0), 20, 2)) + '"'
					WHEN @CODE = '180' THEN 'НалИсчисл="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '190' THEN 'НалИсчислФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '200' THEN 'НалИсчислСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '210' THEN 'АвНачисл="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '220' THEN 'АвНачислФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '230' THEN 'АвНачислСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '240' THEN 'НалВыпл311="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '250' THEN 'НалВыпл311ФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '260' THEN 'НалВыпл311Суб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '270' THEN 'НалДоплФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '271' THEN 'НалДоплСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '280' THEN 'НалУменФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '281' THEN 'НалУменСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '290' THEN 'АвПлатМес="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '300' THEN 'АвПлатМесФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '310' THEN 'АвПлатМесСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '320' THEN 'АвПлатУпл1Кв="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '330' THEN 'АвПлатУпл1КвФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '340' THEN 'АвПлатУпл1КвСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					ELSE ''
				END	
				
		IF LEN (@strINS_VALUE) > 0
			INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, @strINS_VALUE)

		FETCH NEXT FROM #DATA_CURSOR
			INTO @CODE,
				@COL1, 
				@COL3, 
				@COL4 
	END	--- WHILE @@FETCH_STATUS = 0

	CLOSE #DATA_CURSOR
	DEALLOCATE #DATA_CURSOR
	------------------------------
	------------------------------
	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, '</Файл>')

	DROP TABLE #TASK_PROP

	DROP TABLE #TEMP
	DROP TABLE #TABLE_R1_1

	SELECT * FROM @OUTPUT ORDER BY [ID]
END 






GO


GRANT EXECUTE ON dbo.[BK_EXPORT_F1151006_503] TO PUBLIC

GO


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

GO
CREATE PROCEDURE dbo.BK_EXPORT_F1151006_505 (@iLINK_FORM INT)
AS
BEGIN

--перенос формы из архивной базы
exec 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),
		@POST_GL_BUH	VARCHAR (254),
		@DEP_NAME VARCHAR (254),

		@SONO VARCHAR (4),

		@DOC_ID		VARCHAR (36),

		@NAME_RUK	VARCHAR (60),
		@FAM_RUK	VARCHAR (60),
		@OT_RUK		VARCHAR (60),

		@NAME_GL_BUH	VARCHAR (60),
		@FAM_GL_BUH	VARCHAR (60),
		@OT_GL_BUH	VARCHAR (60),

		@dDATE_FORM	DATETIME,
		@PERIOD_TYPE	INT,
		@PERIOD_NUM	INT,
		@cPERIOD_NUM	VARCHAR (2),

		@iLINK_TABLE	INT,
		@PROC_NAME	VARCHAR (254),

		--- Раздел 1 ---
		@OKTMO_D VARCHAR (15),
		@OKTMO VARCHAR (15),
		
		@KBK VARCHAR (30),
		@SUMMA1 VARCHAR (100),
		@SUMMA2 VARCHAR (100),
		@NUM_KOR	VARCHAR (3),
		@PLACE_USED	VARCHAR (3),

		--- Лист 02 ---
		@CODE VARCHAR (50),
		@COL1 VARCHAR (50),
		@COL3 NUMERIC (20,4), 	
		@COL4 NUMERIC (20,4), 	

		@strINS_VALUE	VARCHAR (100),

		@strEXEC	VARCHAR (8000)
	--- ---
	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

	SET @cPERIOD_NUM =
			CASE
				WHEN @PERIOD_TYPE = 1 THEN '34'	-- ПЕРИОД ГОД
				WHEN @PERIOD_TYPE = 2 THEN 	-- ПЕРИОД КВАРТАЛ
					CASE 
						WHEN @PERIOD_NUM = 1 THEN '21'
						WHEN @PERIOD_NUM = 2 THEN '31'
						WHEN @PERIOD_NUM = 3 THEN '33'
					END
				WHEN @PERIOD_TYPE = 4 THEN LTRIM (STR (34 + @PERIOD_NUM ))
			END

	EXEC dbo.GetRandStr 36, @DOC_ID OUTPUT

	SELECT @PART_NAME_NNN = @DOC_ID

	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_D = CONVERT (VARCHAR (11), REPLACE (OKTMO, ' ', '')),
		@SONO = CONVERT (VARCHAR (4), ISNULL (IMNS, ''))
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @DEP_LINK

	SET @DEP_NAME = REPLACE (@DEP_NAME, '"', '&quot;')

	SELECT
		@TLF_GL_BUH = A.PHONE,
		@POST_GL_BUH = B.POST_NAME,

		@NAME_GL_BUH = B.IM,
		@FAM_GL_BUH = B.FM,
		@OT_GL_BUH = B.OT

	FROM dbo.DICTIONARY_OTV_FACE A
	LEFT JOIN dbo.KU_EMPL_PLACING B ON (B.LINK = A.FACE_LINK)
	WHERE A.DEP_LINK = @DEP_LINK
		AND A.[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.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 #TABLE_R1_1
		(
		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), 	-- Сумма1 (ФБ)
		FCOL4 VARCHAR (254),
		COL5 VARCHAR(100), 	-- Сумма2 (ФБ)
		FCOL5 VARCHAR (254),
		COL6 VARCHAR (100), 	-- КБК (Субъект)
		FCOL6 VARCHAR (254),
		COL7 VARCHAR(100), 	-- Сумма1 (Субъект)
		FCOL7 VARCHAR (254),
		COL8 VARCHAR(100), 	-- Сумма2 (Субъект)
		FCOL8 VARCHAR (254),
		COL9 VARCHAR(100), 	-- Номер корректировки
		FCOL9 VARCHAR (254),
		COL10 VARCHAR(100), 	-- По месту использования
		FCOL10 VARCHAR (254),
		ITOG NUMERIC (20)
		) 	
	
	SET @strEXEC = 'INSERT INTO #TABLE_R1_1 (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, ITOG)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)

	--- Данные листа 02 ---
	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 #TEMP
		(
		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),	-- Показатель
		COL3 NUMERIC (20,4), 	-- Сумма
		FCOL3 VARCHAR (8000),
		COL4 NUMERIC (20,4), 	-- Ставка
		FCOL4 varchar (8000),
		ITOG NUMERIC (20,4)
		) 	
	
	SET @strEXEC = 'INSERT INTO #TEMP (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'

	EXECUTE (@strEXEC)

	--- Формирование XML ---
	SELECT @FNAME_ID = 'NO_PRIB_' + 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.05">')


	--- Документ ---
	SELECT
		@NUM_KOR = COL9,
		@PLACE_USED = COL10
	FROM #TABLE_R1_1

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Документ КНД="1151006"')
	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, 'КодНО="' + @SONO + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НомКорр="' + ISNULL (@NUM_KOR, '0') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ПоМесту="' + ISNULL (@PLACE_USED, '214') + '"')
	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 (@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, '<НПЮЛ')
	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, '/>')

	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, '<ФИО')
	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, '<Прибыль>')
	
	--- Раздел 1 ---
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НалПУ>')
	--- 1.1. для организаций, уплачивающих авансовые платежи и налог на прибыль организаций ---
	--- ОКТМО ---
	SELECT @OKTMO = COL2
	FROM #TABLE_R1_1 

	IF ISNULL (@OKTMO, '') = ''
		SET @OKTMO = ISNULL (@OKTMO_D, '')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<НалПУАв ТипНП="1" ОКТМО="'
		+ @OKTMO + '">')

	-- Фед. бюджет --
	SELECT
		@KBK = COL3,
		@SUMMA1 = COL4,
		@SUMMA2 = COL5
	FROM #TABLE_R1_1 

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ФедБдж')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КБК="' + RTRIM (@KBK) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + RTRIM (@SUMMA2) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '/>')	

	-- Бюджет субъекта --
	SELECT
		@KBK = COL6,
		@SUMMA1 = COL7,
		@SUMMA2 = COL8
	FROM #TABLE_R1_1 

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СубБдж')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КБК="' + RTRIM (@KBK) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + RTRIM (@SUMMA2) + '"')
	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, '</НалПУ>')

	--- Лист 02 ---
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасчНал')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ТипНП="1"')

	--- Таблица ---
	DECLARE #DATA_CURSOR CURSOR LOCAL STATIC	
		FOR
		SELECT
			CODE,
			COL1,
			COL3,
			COL4
		FROM #TEMP
		ORDER BY ORDERS

	OPEN #DATA_CURSOR

	FETCH FROM #DATA_CURSOR
		INTO @CODE,
			@COL1, 
			@COL3, 
			@COL4 


	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @strINS_VALUE = CASE
					WHEN @CODE = '010' THEN 'ДохРеал="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '020' THEN 'ДохВнереал="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '030' THEN 'РасхУмРеал="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '040' THEN 'РасхВнереал="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '050' THEN 'Убытки="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '060' THEN 'ПрибУб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '070' THEN 'ДохИсклПриб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '080' THEN 'ПрибБРСт0="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '090' THEN 'СумЛьгот="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '100' THEN 'НалБаза="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '110' THEN 'УбытУмНБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '120' THEN 'НалБазаИсч="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '130' THEN 'НалБазаИсчСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '140' THEN 'СтавНалВсего="' + LTRIM (STR (ISNULL (@COL4, 0), 20, 2)) + '"'
					WHEN @CODE = '150' THEN 'СтавНалФБ="' + LTRIM (STR (ISNULL (@COL4, 0), 20, 2)) + '"'
					WHEN @CODE = '160' THEN 'СтавНалСуб="' + LTRIM (STR (ISNULL (@COL4, 0), 20, 2)) + '"'
					WHEN @CODE = '170' THEN 'СтавНалСуб284="' + LTRIM (STR (ISNULL (@COL4, 0), 20, 2)) + '"'
					WHEN @CODE = '180' THEN 'НалИсчисл="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '190' THEN 'НалИсчислФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '200' THEN 'НалИсчислСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '210' THEN 'АвНачисл="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '220' THEN 'АвНачислФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '230' THEN 'АвНачислСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '240' THEN 'НалВыпл311="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '250' THEN 'НалВыпл311ФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '260' THEN 'НалВыпл311Суб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '270' THEN 'НалДоплФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '271' THEN 'НалДоплСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '280' THEN 'НалУменФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '281' THEN 'НалУменСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '290' THEN 'АвПлатМес="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '300' THEN 'АвПлатМесФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '310' THEN 'АвПлатМесСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '320' THEN 'АвПлатУпл1Кв="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '330' THEN 'АвПлатУпл1КвФБ="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					WHEN @CODE = '340' THEN 'АвПлатУпл1КвСуб="' + LTRIM (STR (ISNULL (@COL3, 0), 20, 0)) + '"'
					ELSE ''
				END	
				
		IF LEN (@strINS_VALUE) > 0
			INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, @strINS_VALUE)

		FETCH NEXT FROM #DATA_CURSOR
			INTO @CODE,
				@COL1, 
				@COL3, 
				@COL4 
	END	--- WHILE @@FETCH_STATUS = 0

	CLOSE #DATA_CURSOR
	DEALLOCATE #DATA_CURSOR
	------------------------------
	------------------------------
	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, '</Файл>')

	DROP TABLE #TASK_PROP

	DROP TABLE #TEMP
	DROP TABLE #TABLE_R1_1

	SELECT * FROM @OUTPUT ORDER BY [ID]
END 


GO


GRANT EXECUTE ON dbo.[BK_EXPORT_F1151006_505] TO PUBLIC

GO




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

GO
CREATE PROCEDURE dbo.BK_EXPORT_F1152004 (@iLINK_FORM INT)
AS
BEGIN

--перенос формы из архивной базы
exec 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),
		@POST_GL_BUH	VARCHAR (254),
		@DEP_NAME VARCHAR (254),

		@DOC_ID		VARCHAR (36),

		@NAME_RUK	VARCHAR (60),
		@FAM_RUK	VARCHAR (60),
		@OT_RUK		VARCHAR (60),

		@NAME_GL_BUH	VARCHAR (60),
		@FAM_GL_BUH	VARCHAR (60),
		@OT_GL_BUH	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 (30),
		@OKATO VARCHAR (15),
		@OKATO_D VARCHAR (15),
		@SUMMA	NUMERIC (15,0),

		@SUM_AV NUMERIC (15,0),
		@SUM_PAY NUMERIC (15,0),
		@SUM_LOW NUMERIC (15,0),

		@LINK_COL_CODE INT,
		@NUM_KOR NUMERIC (20),

		--- Раздел 2 ---
		@LINK_COL_VIDTS	INT,
		@LINK_COL_VIN	INT,
		@LINK_COL_MARKA	INT,
		@LINK_COL_REGNO	INT,
		@LINK_COL_NALBAS INT,
		@LINK_COL_OKEI	INT,
		@LINK_COL_SROK	INT,
		@LINK_COL_K3623	INT,
		@LINK_COL_STAVKA INT,
		@LINK_COL_SUM_IS	INT,
		@LINK_COL_LGOTA	INT,
		@LINK_COL_SUM_LGOTA	INT,
		@LINK_COL_SUM_UPL	INT,

		@strEXEC	VARCHAR (8000)
	--- ---
	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

	SET @cPERIOD_NUM = CASE WHEN @PERIOD_NUM = 1 THEN '21'
							WHEN @PERIOD_NUM = 2 THEN '22'
							WHEN @PERIOD_NUM = 3 THEN '23'
		END

	EXEC dbo.GetRandStr 36, @DOC_ID OUTPUT

	SELECT @PART_NAME_NNN = @DOC_ID

	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],
			@OKATO_D = CONVERT (VARCHAR (11), REPLACE (OKATO, ' ', ''))
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @DEP_LINK

	SELECT @TLF_GL_BUH = A.PHONE,
		@POST_GL_BUH = B.POST_NAME,

		@NAME_GL_BUH = B.IM,
		@FAM_GL_BUH = B.FM,
		@OT_GL_BUH = B.OT

	FROM dbo.DICTIONARY_OTV_FACE A
	LEFT JOIN dbo.KU_EMPL_PLACING B ON (B.LINK = A.FACE_LINK)
	WHERE A.DEP_LINK = @DEP_LINK
		AND A.[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)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM
		AND ORDERS = 2

	CREATE TABLE #TABLE1 (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(100),	-- 
		FCOL2 VARCHAR (1000),
		COL3 NUMERIC (20), 	-- 
		FCOL3 VARCHAR (1000),
		COL4 NUMERIC(20), 	-- 
		FCOL4 varchar (1000),
		COL5 NUMERIC(20),	-- 
		FCOL5 VARCHAR (1000),
		COL6 NUMERIC (20), 	-- 
		FCOL6 VARCHAR (1000),
		COL7 VARCHAR(50),	-- 
		FCOL7 VARCHAR (1000),
		COL8 NUMERIC(20),	-- 
		FCOL8 VARCHAR (254),
		ITOG NUMERIC(20))
	
	IF @iLINK_TABLE > 0
	BEGIN
		SET @strEXEC = 'INSERT INTO #TABLE1 (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, 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)
	END

	SELECT @KBK = COL7,
		@OKATO = COL2,
		@SUMMA = COL3,
		@SUM_AV = COL4,
		@SUM_PAY = COL5,
		@SUM_LOW = COL6,
		@NUM_KOR = COL8
	FROM #TABLE1

	-- ДАННЫЕ РАЗДЕЛА 2 --
	-- !!!Расчет!!! --
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM 	(select *, CASE WHEN ORDERS = 1 THEN 2 WHEN ORDERS = 2 THEN 1 END AS REAL_ORD
		from report_tables
		where link_form = (select link_form
							from report_saved_forms
							where link_saved_form=@iLINK_FORM)) AS T
	WHERE REAL_ORD = 2

	CREATE TABLE #TEMP (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(100),	-- ВИД ТС
		FCOL2 VARCHAR,
		COL3 VARCHAR (100), 	-- ВИН
		FCOL3 VARCHAR,
		COL4 VARCHAR(100), 	-- МАРКА ТС
		FCOL4 varchar,
		COL5 VARCHAR(100),	-- РЕГ. НОМЕР
		FCOL5 VARCHAR,
		COL6 NUMERIC(20,2), 	-- НАЛ. БАЗА
		FCOL6 VARCHAR,
		COL7 VARCHAR(50),	-- ОКЕИ
		FCOL7 VARCHAR,
		COL8 NUMERIC(20,0),	-- СРОК
		FCOL8 VARCHAR,
		COL9 NUMERIC(20,2),	-- К3623
		FCOL9 VARCHAR,
		COL10 NUMERIC(20,2),	-- СТАВКА
		FCOL10 VARCHAR,
		COL11 NUMERIC(20,2),	-- СУМ. ИСЧИСЛ.
		FCOL11 VARCHAR,	
		COL12 VARCHAR(50),	-- КОД НАЛ. ЛЬГОТЫ 
		FCOL12 VARCHAR,
		COL13 NUMERIC(20,2),	-- СУМ. НАЛ. ЛЬГОТЫ 
		FCOL13 VARCHAR,
		COL14 NUMERIC(20,2),	-- СУМ. УПЛ.
		FCOL14 VARCHAR) 
	
	SET @strEXEC = 'INSERT INTO #TEMP (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, COL13, FCOL13, COL14, FCOL14)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)
	
	--- Формирование XML ---
	SELECT @FNAME_ID = 'NO_TRAND_' + 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" xsi:noNamespaceSchemaLocation="NO_TRAND_1_054_00_04_01_01.XSD"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИдФайл="' + RTRIM (@FNAME_ID) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсФорм="4.01"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ТипИнф="ТРАНД"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсПрог="' + RTRIM (LEFT (@NAME_PROG, 40)) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КолДок="1">')

-- Сведения об отправителе	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ИдОтпр ДолжОтв="'
		+ RTRIM (LEFT (ISNULL (@POST_GL_BUH, ''), 45)) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Тлф="' + RTRIM (ISNULL (@TLF_GL_BUH, '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'E-mail="">')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ФИООтв')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, ' Фамилия="' + RTRIM (ISNULL (@FAM_GL_BUH, '')) 
					+ '" Имя="' + RTRIM (ISNULL (@NAME_GL_BUH, '')) + '"'
					+ CASE WHEN ISNULL (@OT_GL_BUH, '') <> '' THEN ' Отчество="'
											+ RTRIM (ISNULL (@OT_GL_BUH, '')) + '"'
							ELSE '' END
					+ '/>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ИдОтпр>')

-- Документ
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Документ ИдДок="' + @DOC_ID + '">')

	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, 'ОКВЭД="' + 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, '<СвРукОрг')
	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, '<ОписПерСвед КНД="1152004"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВидДок="' + CONVERT (VARCHAR (10), ISNULL (@NUM_KOR, 0)) + '"')
--	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, 'ДатаДок="' + CONVERT (VARCHAR (10), GETDATE (), 104) + '"')
	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 (@OKATO, '') = '' 
											THEN ISNULL (@OKATO_D, '')
										ELSE @OKATO END + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Исчислено="' + LTRIM (STR (ISNULL (@SUMMA, 0))) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'СумУплАв="' + LTRIM (STR (ISNULL (@SUM_AV, 0))) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'СумУплНал="' + LTRIM (STR (ISNULL (@SUM_PAY, 0))) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'СумУмен="' + LTRIM (STR (ISNULL (@SUM_LOW, 0))) + '">')
	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT)
	SELECT @FNAME,
		'<РасчНалТС КодВидТС="' + CONVERT (VARCHAR (5), ISNULL (COL2, '')) + '"'
		+ ' ИдНомТС="' + CONVERT (VARCHAR (25), ISNULL (RTRIM (COL3), '')) + '"'
		+ ' МаркаТС="' + CONVERT (VARCHAR (120), ISNULL (RTRIM (COL4), '')) + '"'
		+ ' РегЗнакТС="' + CONVERT (VARCHAR (30), ISNULL (RTRIM (COL5), '')) + '"'
		+ ' НалБаза="' + LTRIM (STR (ISNULL (COL6, 0), 15, 2)) + '"'
		+ ' ОКЕИНалБаза="' + CONVERT (VARCHAR (30), ISNULL (RTRIM (COL7), '' )) + '"'
		+ ' СрокИспольз="' + LTRIM (STR (ISNULL (COL8, 0), 3)) + '"'
		+ ' Коэф3623="' + LTRIM (STR (ISNULL (COL9, 0), 3, 2)) + '"'
		+ ' НалСтавка="' + LTRIM (STR (ISNULL (COL10, 0), 8, 2)) + '"'
		+ ' СумИсчисл="' + LTRIM (STR (ISNULL (COL11, 0), 15)) + '"'
		+ CASE WHEN ISNULL (RTRIM (COL12), '' ) = ''
			THEN ''
			ELSE ' КодНалЛьг="' + CONVERT (VARCHAR (5), ISNULL (RTRIM (COL12), '' )) + '"'
		END	
		+ ' СумНалЛьг="' + LTRIM (STR (ISNULL (COL13, 0), 15)) + '"'
		+ ' СумИсчислУпл="' + LTRIM (STR (ISNULL (COL14, 0), 15)) + '"'
		+ '/>'
	FROM #TEMP 

	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 #TASK_PROP

	DROP TABLE #TEMP
	DROP TABLE #TABLE1
END 


GO


GRANT EXECUTE ON dbo.[BK_EXPORT_F1152004] 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,
	@varKSparCOMPENS	TINYINT,
	@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,COMPENS, period_begin, period_end, date_begin, date_end,reason_link, reason, reason_dop, empl_link, order_link, moved, vac_link)
			VALUES (@varKSparTYPE_LINK,@varKSparCOMPENS, @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, COMPENS = @varKSparCOMPENS, 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.[SA_EMPL_INCOM_VKR]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_EMPL_INCOM_VKR]

GO

CREATE  PROCEDURE dbo.SA_EMPL_INCOM_VKR

	@varKSnMode	smallint	= 0, 
	@varKSnMonth 	int		= 0,
	@varKSnYear	int		= 0,
	@DEP_LINK INT = NULL,
	@REF_PAY INT = NULL
AS

/*
&& Процедура выводит сотрудников имеющих доход в заданном периоде
&& nMode	smallint,  0 - в заданном периоде, 1 - с начала года до заданного периода
&& nMONTH	int,
&& nYEAR	int
*/

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


DECLARE @RESIDENT TINYINT

IF EXISTS (SELECT * FROM dbo.PAYS WHERE LINK = @REF_PAY AND WAY_CALC = 5)
	SET @RESIDENT = 1
ELSE
	IF EXISTS (SELECT * FROM dbo.PAYS WHERE LINK = @REF_PAY AND WAY_CALC = 4)
		SET @RESIDENT = 2
	ELSE
		SET @RESIDENT = NULL	

declare @date datetime
if coalesce(@varKSnMonth,0) = 0 or Coalesce(@varKSnYear,0) = 0
	set @date = dbo.salarycalcperiod()
else
	set @date = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@varKSnMonth,@varKSnYear))

select distinct 
	LINK= e.PERS_LINK,
	LINK_EMPL= e.link,
	TAB_NUM= e.tab,
	[NAME_EMPL]= LTRIM(RTRIM(e.FM)) + ' ' + SUBSTRING(LTRIM(RTRIM(e.IM)),1,1) + '.' + SUBSTRING(LTRIM(RTRIM(e.OT)),1,1),
	sj.LINK_VKR, SJ.NAME_VKR,
	sj.link_ekr, SJ.NAME_EKR,
	[Status]= e.status_empl		
from
	dbo.sd_empl_fn(default,@date,DEFAULT,@DEP_LINK) e
	INNER JOIN dbo.SCJ_NDFL_R SJ ON SJ.LINK_EMPL = e.link 
where
	(@RESIDENT IS NULL OR @RESIDENT = 2 AND E.RESIDENT = 2 OR @RESIDENT = 1 AND E.RESIDENT <> 2)
	and year_begin = @varKSnYear 
	and (
		(month_begin <= @varKSnMonth and @varKSnMode = 1) 
		or 
		(month_begin = @varKSnMonth and @varKSnMode = 0)
	)
	AND E.DEP_LINK = @DEP_LINK
ORDER BY
	NAME_EMPL, SJ.NAME_VKR, SJ.NAME_EKR


GO


GRANT EXECUTE ON dbo.[SA_EMPL_INCOM_VKR] TO PUBLIC

GO


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

GO

CREATE PROCEDURE dbo.BK_EXPORT_F1152004_501
	(@iLINK_FORM INT)
AS
BEGIN

--перенос формы из архивной базы
exec 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),
		@POST_GL_BUH	VARCHAR (254),
		@DEP_NAME VARCHAR (254),

		@DOC_ID		VARCHAR (36),

		@NAME_RUK	VARCHAR (60),
		@FAM_RUK	VARCHAR (60),
		@OT_RUK		VARCHAR (60),

		@NAME_GL_BUH	VARCHAR (60),
		@FAM_GL_BUH	VARCHAR (60),
		@OT_GL_BUH	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 (30),
		@OKATO VARCHAR (15),
		@OKATO_D VARCHAR (15),
		@SUMMA	NUMERIC (15,0),

		@SUM_AV NUMERIC (15,0),
		@SUM_PAY NUMERIC (15,0),
		@SUM_LOW NUMERIC (15,0),

		@LINK_COL_CODE INT,
		@NUM_KOR NUMERIC (20),
		
		@strNUM_COR	VARCHAR (3),
		@C_PLACE	VARCHAR (3),
		
		@cREORG_CODE	VARCHAR (1),
		@cREORG_INN	VARCHAR (12),
		@cREORG_KPP	VARCHAR (12),
		
		@SUM1	NUMERIC (15,0),
		@SUM11	NUMERIC (15,0),
		@SUM12	NUMERIC (15,0),
		@SUM13	NUMERIC (15,0),
		@SUM2	NUMERIC (15,0),

		--- Раздел 2 ---
		@LINK_COL_VIDTS	INT,
		@LINK_COL_VIN	INT,
		@LINK_COL_MARKA	INT,
		@LINK_COL_REGNO	INT,
		@LINK_COL_NALBAS INT,
		@LINK_COL_OKEI	INT,
		@LINK_COL_SROK	INT,
		@LINK_COL_K3623	INT,
		@LINK_COL_STAVKA INT,
		@LINK_COL_SUM_IS	INT,
		@LINK_COL_LGOTA	INT,
		@LINK_COL_SUM_LGOTA	INT,
		@LINK_COL_SUM_UPL	INT,

		@strEXEC	VARCHAR (8000)
	--- ---
	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

	SET @cPERIOD_NUM = CASE WHEN @PERIOD_NUM = 1 THEN '21'
							WHEN @PERIOD_NUM = 2 THEN '22'
							WHEN @PERIOD_NUM = 3 THEN '23'
		END

	EXEC dbo.GetRandStr 36, @DOC_ID OUTPUT

	SELECT @PART_NAME_NNN = @DOC_ID

	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],
			@OKATO_D = CONVERT (VARCHAR (11), REPLACE (OKATO, ' ', ''))
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @DEP_LINK

	SELECT
		@TLF_GL_BUH = A.PHONE,
		@POST_GL_BUH = B.POST_NAME,

		@NAME_GL_BUH = B.IM,
		@FAM_GL_BUH = B.FM,
		@OT_GL_BUH = B.OT
	FROM dbo.DICTIONARY_OTV_FACE A
	LEFT JOIN dbo.KU_EMPL_PLACING B ON (B.LINK = A.FACE_LINK)
	WHERE A.DEP_LINK = @DEP_LINK
		AND A.[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)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM
		AND ORDERS = 2

	CREATE TABLE #TAB1 (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(100),	-- 
		FCOL2 VARCHAR (1000),
		COL3 NUMERIC (20), 	-- 
		FCOL3 VARCHAR (1000),
		COL4 NUMERIC(20), 	-- 
		FCOL4 VARCHAR (1000),
		COL5 NUMERIC(20),	-- 
		FCOL5 VARCHAR (1000),
		COL6 NUMERIC (20), 	-- 
		FCOL6 VARCHAR (1000),
		COL7 NUMERIC (20), 	-- 
		FCOL7 VARCHAR (1000),
		COL8 NUMERIC(20),	-- 
		FCOL8 VARCHAR (1000),
		COL9 VARCHAR(100),	-- 
		FCOL9 VARCHAR (1000),
		COL10 VARCHAR (100),	-- 
		FCOL10 VARCHAR (1000),
		COL11 VARCHAR(100),	-- 
		FCOL11 VARCHAR (1000),
		COL12 VARCHAR(100),	-- 
		FCOL12 VARCHAR (1000),
		COL13 VARCHAR(100),	-- 
		FCOL13 VARCHAR (1000),
		COL14 VARCHAR(100),	-- 
		FCOL14 VARCHAR (1000),
		COL15 VARCHAR(100),	-- 
		FCOL15 VARCHAR (1000),
		ITOG NUMERIC(20))
	
	IF @iLINK_TABLE > 0
	BEGIN
		SET @strEXEC = 'INSERT INTO #TAB1 (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,
							COL13, FCOL13, COL14, FCOL14, COL15, FCOL15,
							ITOG)
				EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
					+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'
	
		EXECUTE (@strEXEC)
	END
	
	SELECT
		@OKATO = ISNULL (COL2, ''),
		@KBK = ISNULL (COL9, ''),
		@strNUM_COR = ISNULL (COL10, ''),
		@C_PLACE = ISNULL (COL11, ''),
		@cPERIOD_NUM = ISNULL (COL12, ''),
		@cREORG_CODE = ISNULL (COL13, ''),
		@cREORG_INN = ISNULL (COL14, ''),
		@cREORG_KPP = ISNULL (COL15, ''),
		
		@SUM1	= ISNULL (COL3, 0),
		@SUM11	= ISNULL (COL4, 0),
		@SUM12	= ISNULL (COL5, 0),
		@SUM13	= ISNULL (COL6, 0),
		@SUM2	= ISNULL (COL7, 0) - ISNULL (COL7, 0)
	FROM #TAB1

	-- Данные раздела 2 --
	SET @iLINK_TABLE = 0
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM
		AND ORDERS = 1
		
	CREATE TABLE #TAB2
		(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(100),	-- 
		FCOL2 VARCHAR (1000),
		COL3 VARCHAR(100),	-- 
		FCOL3 VARCHAR (1000),
		COL4 VARCHAR(100),	-- 
		FCOL4 VARCHAR (1000),
		COL5 VARCHAR(100),	-- 
		FCOL5 VARCHAR (1000),
		COL6 NUMERIC (20, 2), 	-- 
		FCOL6 VARCHAR (1000),
		COL7 VARCHAR(100), --
		FCOL7 VARCHAR (1000),
		COL8 VARCHAR(100), --
		FCOL8 VARCHAR (1000),
		COL9 NUMERIC (20), 	-- 
		FCOL9 VARCHAR (1000),
		COL10 NUMERIC (20), 	-- 
		FCOL10 VARCHAR (1000),
		COL11 NUMERIC (20, 4), -- 
		FCOL11 VARCHAR (1000),
		COL12 NUMERIC (20, 4), -- 
		FCOL12 VARCHAR (1000),
		COL13 NUMERIC (20), -- 
		FCOL13 VARCHAR (1000),
		COL14 NUMERIC (20),	-- 
		FCOL14 VARCHAR (1000),
		COL15 NUMERIC (20, 4), -- 
		FCOL15 VARCHAR (1000),
		
		COL16 VARCHAR(100), --
		FCOL16 VARCHAR (1000),
		COL17 NUMERIC (20), 	-- 
		FCOL17 VARCHAR (1000),
		COL18 VARCHAR(100), --
		FCOL18 VARCHAR (1000),
		COL19 NUMERIC (20), 	-- 
		FCOL19 VARCHAR (1000),
		COL20 VARCHAR(100), --
		FCOL20 VARCHAR (1000),
		COL21 NUMERIC (20), -- 
		FCOL21 VARCHAR (1000),
		COL22 NUMERIC (20), -- 
		FCOL22 VARCHAR (1000),
		
		ITOG NUMERIC(20) DEFAULT (0))

	IF @iLINK_TABLE > 0
	BEGIN
		SET @strEXEC = 'INSERT INTO #TAB2 (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,
							COL13, FCOL13, COL14, FCOL14, COL15, FCOL15,
							COL16, FCOL16, COL17, FCOL17, COL18, FCOL18,
							COL19, FCOL19, COL20, FCOL20, COL21, FCOL21,
							COL22, FCOL22
							)
				EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
					+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'
		EXECUTE (@strEXEC)
	END

	--- Формирование XML ---
	SELECT @FNAME_ID = 'NO_TRAND_' + 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.01">')
	
	-- Документ -- 
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Документ КНД="1152004"')
	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, '<СумНалПУ КБК="' + @KBK + '">')
	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СумПУ ОКАТО="' + @OKATO + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалИсчисл="' + CONVERT (VARCHAR (15), @SUM1) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'АвПУКв1="' + CONVERT (VARCHAR (15), @SUM11) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'АвПУКв2="' + CONVERT (VARCHAR (15), @SUM12) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'АвПУКв3="' + CONVERT (VARCHAR (15), @SUM13) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + CONVERT (VARCHAR (15), @SUM2) + '">')

	-- Расчет суммы транспортного налога по каждому транспортному средству (РасчНалТС) --
--	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасчНалТС>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT)
	SELECT
		@FNAME,
		'<РасчНалТС КодВидТС="' + LTRIM (ISNULL (COL2, '')) 
		+ '" ИдНомТС="' + LTRIM (ISNULL (COL3, '')) 
		+ '" МаркаТС="' + LTRIM (ISNULL (COL4, '')) 
		+ '" РегЗнакТС="' + LTRIM (ISNULL (COL5, '')) 
		+ '" НалБаза="' + LTRIM (STR (ISNULL (COL6, 0), 16, 2))  
		+ '" ОКЕИНалБаза="' + LTRIM (ISNULL (COL7, ''))
		+ '" ЭкологКл="' + LTRIM (ISNULL (COL8, ''))
		+ '" ВыпускТС="' + LTRIM (STR (ISNULL (COL9, 0)))
		+ '" ВладенТС="' + LTRIM (STR (ISNULL (COL10, 0)))
		+ '" КоэфКв="' + LTRIM (STR (ISNULL (COL11, 0), 6, 4))  
		+ '" НалСтавка="' + LTRIM (STR (ISNULL (COL12, 0), 10, 2))
		+ '" СумИсчисл="' + LTRIM (STR (ISNULL (COL13, 0)))
		+ '" ЛьготМесТС="' + LTRIM (STR (ISNULL (COL14, 0)))
		+ '" КоэфКл="' + LTRIM (STR (ISNULL (COL15, 0), 6, 4))  
		+ '" СумИсчислУпл="' + LTRIM (STR (ISNULL (COL22, 0))) + '">'
		+ '<ЛьготОсвНал КодОсвНал="' + LTRIM (ISNULL (COL16, ''))
		+ '" СумОсвНал="' + LTRIM (STR (ISNULL (COL17, 0))) + '"/>'
		+ '<ЛьготУменСум КодУменСум="' + LTRIM (ISNULL (COL18, ''))
		+ '" СумУменСум="' + LTRIM (STR (ISNULL (COL19, 0))) + '"/>'
		+ '<ЛьготСнижСтав КодСнижСтав="' + LTRIM (ISNULL (COL20, ''))
		+ '" СумУменСум="' + LTRIM (STR (ISNULL (COL21, 0))) + '"/>'
		+ '</РасчНалТС>'
	FROM #TAB2 

--	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, '</ТрНалНД>')

	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 #TAB1
	DROP TABLE #TAB2
	DROP TABLE #TASK_PROP

END 





GO


GRANT EXECUTE ON dbo.[BK_EXPORT_F1152004_501] TO PUBLIC

GO




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

GO
CREATE PROCEDURE dbo.BK_EXPORT_F1152004_502
	(@iLINK_FORM INT)
AS
BEGIN

--перенос формы из архивной базы
exec 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),
		@POST_GL_BUH	VARCHAR (254),
		@DEP_NAME VARCHAR (254),

		@DOC_ID		VARCHAR (36),

		@NAME_RUK	VARCHAR (60),
		@FAM_RUK	VARCHAR (60),
		@OT_RUK		VARCHAR (60),

		@NAME_GL_BUH	VARCHAR (60),
		@FAM_GL_BUH	VARCHAR (60),
		@OT_GL_BUH	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 (30),
		@OKTMO VARCHAR (15),
		@OKTMO_DIC VARCHAR (15),
		@SUMMA	NUMERIC (15,0),

		@SUM_AV NUMERIC (15,0),
		@SUM_PAY NUMERIC (15,0),
		@SUM_LOW NUMERIC (15,0),

		@LINK_COL_CODE INT,
		@NUM_KOR NUMERIC (20),
		
		@strNUM_COR	VARCHAR (3),
		@C_PLACE	VARCHAR (3),
		
		@cREORG_CODE	VARCHAR (1),
		@cREORG_INN	VARCHAR (12),
		@cREORG_KPP	VARCHAR (12),
		
		@SUM1	NUMERIC (15,0),
		@SUM11	NUMERIC (15,0),
		@SUM12	NUMERIC (15,0),
		@SUM13	NUMERIC (15,0),
		@SUM2	NUMERIC (15,0),

		--- Раздел 2 ---
		@LINK_COL_VIDTS	INT,
		@LINK_COL_VIN	INT,
		@LINK_COL_MARKA	INT,
		@LINK_COL_REGNO	INT,
		@LINK_COL_NALBAS INT,
		@LINK_COL_OKEI	INT,
		@LINK_COL_SROK	INT,
		@LINK_COL_K3623	INT,
		@LINK_COL_STAVKA INT,
		@LINK_COL_SUM_IS	INT,
		@LINK_COL_LGOTA	INT,
		@LINK_COL_SUM_LGOTA	INT,
		@LINK_COL_SUM_UPL	INT,

		@strEXEC	VARCHAR (8000)

	--- Данные организации ---
	SELECT
		@DEP_LINK = RSF.LINK_ORGANIZATION,
		@dDATE_FORM	= RSF.BEGIN_DATE,
		@PERIOD_TYPE = RSF.PERIOD_TYPE,
		@PERIOD_NUM	= RSF.PERIOD_NUMBER,
		
		@INN	= CONVERT (VARCHAR (10), DEP.INN_LONG),
		@KPP = CONVERT (VARCHAR (9), DEP.KPP),
		@IMNS = CONVERT (VARCHAR (4), DEP.IMNS),
		@OKVED = CONVERT (VARCHAR (8), DEP.OKVED),
		@DEP_NAME = DEP.[NAME],
		@OKTMO_DIC = CONVERT (VARCHAR (11), REPLACE (DEP.OKTMO, ' ', ''))
		
	FROM dbo.REPORT_SAVED_FORMS RSF
	INNER JOIN dbo.DICTIONARY_DEPARTMENT DEP ON (DEP.LINK = RSF.LINK_ORGANIZATION)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	SET @cPERIOD_NUM = CASE
							WHEN @PERIOD_NUM = 1 THEN '21'
							WHEN @PERIOD_NUM = 2 THEN '22'
							WHEN @PERIOD_NUM = 3 THEN '23'
						END

	EXEC dbo.GetRandStr
			36,
			@DOC_ID OUTPUT

	SELECT
		@PART_NAME_NNN = @DOC_ID

	SELECT
		@TLF_GL_BUH = A.PHONE,
		@POST_GL_BUH = B.POST_NAME,

		@NAME_GL_BUH = B.IM,
		@FAM_GL_BUH = B.FM,
		@OT_GL_BUH = B.OT
	FROM dbo.DICTIONARY_OTV_FACE A
	LEFT JOIN dbo.KU_EMPL_PLACING B ON (B.LINK = A.FACE_LINK)
	WHERE A.DEP_LINK = @DEP_LINK
		AND A.[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)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM
		AND ORDERS = 1

	CREATE TABLE #TAB1
		(
		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(100),	-- 
		FCOL2 VARCHAR (1000),
		COL3 NUMERIC (20), 	-- 
		FCOL3 VARCHAR (1000),
		COL4 NUMERIC(20), 	-- 
		FCOL4 VARCHAR (1000),
		COL5 NUMERIC(20),	-- 
		FCOL5 VARCHAR (1000),
		COL6 NUMERIC (20), 	-- 
		FCOL6 VARCHAR (1000),
		COL7 NUMERIC (20), 	-- 
		FCOL7 VARCHAR (1000),
		COL8 NUMERIC(20),	-- 
		FCOL8 VARCHAR (1000),
		COL9 VARCHAR(100),	-- 
		FCOL9 VARCHAR (1000),
		COL10 VARCHAR (100),	-- 
		FCOL10 VARCHAR (1000),
		COL11 VARCHAR(100),	-- 
		FCOL11 VARCHAR (1000),
		COL12 VARCHAR(100),	-- 
		FCOL12 VARCHAR (1000),
		COL13 VARCHAR(100),	-- 
		FCOL13 VARCHAR (1000),
		COL14 VARCHAR(100),	-- 
		FCOL14 VARCHAR (1000),
		COL15 VARCHAR(100),	-- 
		FCOL15 VARCHAR (1000),
		ITOG NUMERIC(20)
		)
	
	IF @iLINK_TABLE > 0
	BEGIN
	
		SET @strEXEC = 'INSERT INTO #TAB1 (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,
							COL13, FCOL13, COL14, FCOL14, COL15, FCOL15,
							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 #TAB1
		
	END
	
	SELECT
		@OKTMO = ISNULL (COL2, ''),
		@KBK = ISNULL (COL9, ''),
		@strNUM_COR = ISNULL (COL10, ''),
		@C_PLACE = ISNULL (COL11, ''),
		@cPERIOD_NUM = ISNULL (COL12, ''),
		@cREORG_CODE = ISNULL (COL13, ''),
		@cREORG_INN = ISNULL (COL14, ''),
		@cREORG_KPP = ISNULL (COL15, ''),
		
		@SUM1	= ISNULL (COL3, 0),
		@SUM11	= ISNULL (COL4, 0),
		@SUM12	= ISNULL (COL5, 0),
		@SUM13	= ISNULL (COL6, 0),
		@SUM2	= ISNULL (COL7, 0) - ISNULL (COL7, 0)
	FROM #TAB1

	-- Данные раздела 2 --
	SET @iLINK_TABLE = 0
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM
		AND ORDERS = 2
		
	CREATE TABLE #TAB2
		(
		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(100),	-- 
		FCOL2 VARCHAR (1000),
		COL3 VARCHAR(100),	-- 
		FCOL3 VARCHAR (1000),
		COL4 VARCHAR(100),	-- 
		FCOL4 VARCHAR (1000),
		COL5 VARCHAR(100),	-- 
		FCOL5 VARCHAR (1000),
		COL6 NUMERIC (20, 2), 	-- 
		FCOL6 VARCHAR (1000),
		COL7 VARCHAR(100), --
		FCOL7 VARCHAR (1000),
		COL8 VARCHAR(100), --
		FCOL8 VARCHAR (1000),
		COL9 NUMERIC (20), 	-- 
		FCOL9 VARCHAR (1000),
		COL10 NUMERIC (20), 	-- 
		FCOL10 VARCHAR (1000),
		COL11 NUMERIC (20, 4), -- 
		FCOL11 VARCHAR (1000),
		COL12 NUMERIC (20, 4), -- 
		FCOL12 VARCHAR (1000),
		COL13 NUMERIC (20), -- 
		FCOL13 VARCHAR (1000),
		COL14 NUMERIC (20),	-- 
		FCOL14 VARCHAR (1000),
		COL15 NUMERIC (20, 4), -- 
		FCOL15 VARCHAR (1000),
		
		COL16 VARCHAR(100), --
		FCOL16 VARCHAR (1000),
		COL17 NUMERIC (20), 	-- 
		FCOL17 VARCHAR (1000),
		COL18 VARCHAR(100), --
		FCOL18 VARCHAR (1000),
		COL19 NUMERIC (20), 	-- 
		FCOL19 VARCHAR (1000),
		COL20 VARCHAR(100), --
		FCOL20 VARCHAR (1000),
		COL21 NUMERIC (20), -- 
		FCOL21 VARCHAR (1000),
		COL22 NUMERIC (20), -- 
		FCOL22 VARCHAR (1000),
		
		ITOG NUMERIC(20) DEFAULT (0)
		)

	IF @iLINK_TABLE > 0
	BEGIN
		SET @strEXEC = 'INSERT INTO #TAB2 (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,
							COL13, FCOL13, COL14, FCOL14, COL15, FCOL15,
							COL16, FCOL16, COL17, FCOL17, COL18, FCOL18,
							COL19, FCOL19, COL20, FCOL20, COL21, FCOL21,
							COL22, FCOL22
							)
				EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
					+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'
		EXECUTE (@strEXEC)
	END

	--- Формирование XML ---
	SELECT @FNAME_ID = 'NO_TRAND_' + 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.02">')
	
	-- Документ -- 
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Документ КНД="1152004"')
	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, '<СумНалПУ КБК="' + @KBK + '">')
	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СумПУ ОКТМО="' + @OKTMO + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалИсчисл="' + CONVERT (VARCHAR (15), @SUM1) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'АвПУКв1="' + CONVERT (VARCHAR (15), @SUM11) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'АвПУКв2="' + CONVERT (VARCHAR (15), @SUM12) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'АвПУКв3="' + CONVERT (VARCHAR (15), @SUM13) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + CONVERT (VARCHAR (15), @SUM2) + '">')

	-- Расчет суммы транспортного налога по каждому транспортному средству (РасчНалТС) --
--	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасчНалТС>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT)
	SELECT
		@FNAME,
		'<РасчНалТС КодВидТС="' + LTRIM (ISNULL (COL2, '')) 
		+ '" ИдНомТС="' + LTRIM (ISNULL (COL3, '')) 
		+ '" МаркаТС="' + LTRIM (ISNULL (COL4, '')) 
		+ '" РегЗнакТС="' + LTRIM (ISNULL (COL5, '')) 
		+ '" НалБаза="' + LTRIM (STR (ISNULL (COL6, 0), 16, 2))  
		+ '" ОКЕИНалБаза="' + LTRIM (ISNULL (COL7, ''))
		+ '" ЭкологКл="' + LTRIM (ISNULL (COL8, ''))
		+ '" ВыпускТС="' + LTRIM (STR (ISNULL (COL9, 0)))
		+ '" ВладенТС="' + LTRIM (STR (ISNULL (COL10, 0)))
		+ '" КоэфКв="' + LTRIM (STR (ISNULL (COL11, 0), 6, 4))  
		+ '" НалСтавка="' + LTRIM (STR (ISNULL (COL12, 0), 10, 2))
		+ '" СумИсчисл="' + LTRIM (STR (ISNULL (COL13, 0)))
		+ '" ЛьготМесТС="' + LTRIM (STR (ISNULL (COL14, 0)))
		+ '" КоэфКл="' + LTRIM (STR (ISNULL (COL15, 0), 6, 4))  
		+ '" СумИсчислУпл="' + LTRIM (STR (ISNULL (COL22, 0))) + '">'
		+ '<ЛьготОсвНал КодОсвНал="' + LTRIM (ISNULL (COL16, ''))
		+ '" СумОсвНал="' + LTRIM (STR (ISNULL (COL17, 0))) + '"/>'
		+ '<ЛьготУменСум КодУменСум="' + LTRIM (ISNULL (COL18, ''))
		+ '" СумУменСум="' + LTRIM (STR (ISNULL (COL19, 0))) + '"/>'
		+ '<ЛьготСнижСтав КодСнижСтав="' + LTRIM (ISNULL (COL20, ''))
		+ '" СумУменСум="' + LTRIM (STR (ISNULL (COL21, 0))) + '"/>'
		+ '</РасчНалТС>'
	FROM #TAB2 

--	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, '</ТрНалНД>')

	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 #TAB1
	DROP TABLE #TAB2
	DROP TABLE #TASK_PROP

END 


GO


GRANT EXECUTE ON dbo.[BK_EXPORT_F1152004_502] TO PUBLIC

GO


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

GO

CREATE PROCEDURE [dbo].[RA_EXPORT_FORM_STANDART]
	@iLINK_SAVED_FORM  INT,	                   -- Линк выгружаемой формы
	@vcFILE_NAME	   VARCHAR(100)='' OUTPUT, -- Имя текстового файла
	@iMODE	           INT=1,                  -- Формат: 1-внутренний, 2-минфиновский	
    @vcFILE_NAME_ARH   VARCHAR(100)='' OUTPUT
	--@bSvodWEB         BIT = 0     -- 1 - выгрузка из Свода-WEB, 0 - из Свода-КС.
AS

SET NOCOUNT ON

CREATE TABLE #IMPORT_TABLE([TXT]   VARCHAR(8000), 
                           [ORDER] INT IDENTITY(1, 1))	   

CREATE TABLE #REPORT_DINAMICS([LINK_SF]   INT,
                              [LINK_COL]  INT,
                              [CODE_ROW]  VARCHAR(50),
                              [FLOAT_VAL] NUMERIC(20,4),
                              [STR_VAL]   VARCHAR(8000))

CREATE TABLE #REPORT_SUMMA([LINK_SAVED_FORM] INT,
                           [LINK_COL]        INT,
                           [LINK_ROW]        INT,
                           [SUMMA]           FLOAT(53))

CREATE TABLE #tabExportForms([LINK_SAVED_FORM] INT)

DECLARE @vcVersion       VARCHAR(50),
        @lbIsEmpty       BIT,
        @lcEXPORT_CODE   CHAR(10),
        @lcFORM_CODE     CHAR(20),
        @liFORM_LINK     INT, 
        @lvcPARAM_EXPORT VARCHAR(8000), 
        @ldBEGIN_DATE    DATETIME,
        @ldSTART_DATE    DATETIME,  
        @lvcOUTCODE      VARCHAR(10),
        @lvcDEP_BUDG     VARCHAR(10),
        @lvcDEP_NAME     VARCHAR(254),   
        @lsVERSION       SMALLINT,
        @lvcOKATO        VARCHAR(20),
           
        @liError           INT, 
        @lvcTXT            VARCHAR(8000), 
        @lvcExecTable      VARCHAR(8000), 
        @liORDERS          INT, 
		  @lvcORDERS			VARCHAR(50),
        @lvcTXTDataNotNull VARCHAR(4000),

        @liDEP_LINK	         INT,
        @liDEP_LINK_OWN       INT,
        @liTABLE_LINK	      INT,
        @liTABLE_ORDER	      INT,
        @liTABLE_VAL_TYPE	   INT,
        @liLINK_CODE_COL	   INT,
        @ltORDER_CODE_COL	   INT,
        @liCOL_LINK	         INT,
        @liCOL_TYPE	         INT,
        @liCOL_VAL_LEN        INT,
        @ltCOL_ISEDITED       TINYINT,
        @ltCOL_ISEXPORTED     TINYINT,
        @ltPERIOD_TYPE        TINYINT,
        @lvcDICTIONARY_COLUMNS_LIST VARCHAR(250),

        @lvcExec	            VARCHAR(8000),
        @lvcVersion           VARCHAR(50),

        @lvcATRIBUTS     VARCHAR(8000),
        @lvcATR          VARCHAR(8000),
        @liPosition      INT,
		  @lvcUpdateSelect VARCHAR(8000),
        @tVersionPlace   TINYINT,

        @bIsFormUnion    BIT,
        @vcBOSS          VARCHAR(1000),
          @vcBUH VARCHAR(1000),
          @vcISP VARCHAR(1000),
          @vcTel VARCHAR(1000)
        
IF OBJECT_ID('tempdb..#tabExportOutput') IS NOT NULL
BEGIN
   SELECT @vcVersion = [VERSION]
   FROM #tabExportOutput 
END


SET @bIsFormUnion = 0

IF @iLINK_SAVED_FORM = 0
BEGIN
	RETURN 2 -- Максимальное обрабатываемое Число способов выгрузки
END

-- Удалить запрещенные ячейки из формы.
DELETE [A]
FROM dbo.[REPORT_SUMMA]	  [A]
JOIN dbo.[REPORT_FORMULA] [B] ON [A].[LINK_COL]=[B].[LINK_COL] AND 
											[A].[LINK_ROW]=[B].[LINK_ROW]
WHERE [A].[LINK_SAVED_FORM] = @iLINK_SAVED_FORM AND
		[B].[FORMULA]='ЗАПРЕТ()'

SELECT @liFORM_LINK          = [B].[LINK_FORM],
       @ldSTART_DATE         = [B].[START_DATE],
       @lvcPARAM_EXPORT      = [B].[PARAM_EXPORT],
       @lcFORM_CODE          = [B].[CODE],
       @lcEXPORT_CODE        = [B].[ExportCode],
       @ltPERIOD_TYPE        = [A].[PERIOD_TYPE],
       @liDEP_LINK           = [A].[LINK_ORGANIZATION],
       @lvcDEP_BUDG          = [D].[BUDG],
       @lvcDEP_NAME          = [D].[NAME],
       @ldBEGIN_DATE         = [A].[BEGIN_DATE],
       @lvcOUTCODE            = ISNULL(CASE 
                                         WHEN [C].[OUTCODE] IS NULL THEN 
                                            (SELECT [OUTCODE]
                                             FROM dbo.[RA_VIEW_EMPTY_BUDGET])
                                         ELSE [C].[OUTCODE]
                                      END,'--'),
       @lvcATRIBUTS          = [ATRIBUTS],
       @lsVERSION            = [A].[VERSION] + 1
FROM dbo.[REPORT_SAVED_FORMS] [A]
JOIN dbo.[REPORT_FORMS]       [B] ON [A].[LINK_FORM] = [B].[LINK_FORM]
LEFT JOIN dbo.[KL_BUDG_TYPE]  [C] ON [A].[LINK_TYPE_SVOD] = [C].[LINK]
LEFT JOIN dbo.[DEPARTMENTS]   [D] ON [A].[LINK_ORGANIZATION] = [D].[LINK]
WHERE [A].[LINK_SAVED_FORM] = @iLINK_SAVED_FORM

IF @lcEXPORT_CODE IN ('624', '625')
BEGIN
   SET @tVersionPlace = 1
END
ELSE BEGIN
   SET @tVersionPlace = 2
END

IF @vcVersion IS NOT NULL
BEGIN
   IF dbo.[RA_ISNUMERIC](REPLACE(@vcVersion,'.','')) = 1
   BEGIN
      SET @lsVersion = CAST(@vcVersion AS INT)
   END
END

IF @lcEXPORT_CODE = '484' and @iMODE = 2
BEGIN
   INSERT #tabExportForms([LINK_SAVED_FORM])
   SELECT [LINK]
   FROM dbo.[BufferGetTableByID]('REPORT_ATR_EXPORT')

   IF @@ROWCOUNT = 0
   BEGIN
      INSERT #tabExportForms([LINK_SAVED_FORM]) VALUES (@iLINK_SAVED_FORM)
   END

   SET @bIsFormUnion = 1   

   INSERT #REPORT_DINAMICS([LINK_SF],
                           [LINK_COL],
                           [CODE_ROW],
                           [FLOAT_VAL],
                           [STR_VAL])

   SELECT @iLINK_SAVED_FORM,
          [A].[LINK_COL],
          [A].[CODE_ROW] + [B].[ADM],
          [A].[FLOAT_VAL],
          [A].[STR_VAL]
   FROM dbo.[REPORT_DINAMICS] [A]
   JOIN (SELECT [LINK_SAVED_FORM],
                [ADM] = RTRIM(dbo.[RN_GET_ATR_VALUE]([LINK_SAVED_FORM],'REPORTS_ATR_ADM'))
         FROM #tabExportForms) [B] ON [A].[LINK_SF] = [B].[LINK_SAVED_FORM]

   INSERT #REPORT_DINAMICS([LINK_SF],
                           [LINK_COL],
                           [CODE_ROW],
                           [FLOAT_VAL],
                           [STR_VAL])
   SELECT @iLINK_SAVED_FORM,
          [A].[LINK_COL],
          [A].[CODE_ROW] + '***',
          SUM([A].[FLOAT_VAL]),
          MAX([A].[STR_VAL])
   FROM dbo.[REPORT_DINAMICS] [A]
   JOIN #tabExportForms       [B] ON [A].[LINK_SF] = [B].[LINK_SAVED_FORM]
   WHERE [A].[CODE_ROW] IN ('85000000000000000','52001000000000000000')
   GROUP BY [A].[LINK_SF],
            [A].[LINK_COL],
            [A].[CODE_ROW]

   DELETE #REPORT_DINAMICS
   WHERE (LEFT([CODE_ROW],17) = '85000000000000000' AND SUBSTRING([CODE_ROW],18,3)<>'***') OR
         (LEFT([CODE_ROW],20) = '52001000000000000000' AND SUBSTRING([CODE_ROW],21,3)<>'***')

   INSERT #REPORT_SUMMA([LINK_SAVED_FORM],
                        [LINK_COL],
                        [LINK_ROW],
                        [SUMMA])
   SELECT @iLINK_SAVED_FORM,          
          [A].[LINK_COL],
          [A].[LINK_ROW],
          SUM([A].[SUMMA])
   FROM dbo.[REPORT_SUMMA] [A]
   JOIN #tabExportForms    [B] ON [A].[LINK_SAVED_FORM] = [B].[LINK_SAVED_FORM]
   GROUP BY [A].[LINK_COL],
            [A].[LINK_ROW]
END

SET @vcFILE_NAME = UPPER(CASE @iMODE
                      WHEN 2 THEN LTRIM(RTRIM(CASE 
                                                 WHEN @lcEXPORT_CODE = '' THEN @lcFORM_CODE
                                                 ELSE @lcEXPORT_CODE
                                              END)) + 
                                  CASE @ltPERIOD_TYPE
                                     WHEN 1 THEN 'Y' 
                                     WHEN 2 THEN 'M' --'Q' 
                                     ELSE 'M' 
                                  END + 
                                  REPLICATE('0',@tVersionPlace - LEN(RIGHT(RTRIM(CONVERT(CHAR(4), @lsVERSION)), @tVersionPlace))) + RIGHT(RTRIM(CONVERT(CHAR(4), @lsVERSION)), 2) 
                      ELSE RTRIM(ISNULL((SELECT [BUDG] 
                                         FROM dbo.[DEPARTMENTS] 
WHERE [LINK] = @liDEP_LINK),'00000')) + 
                           '_' +
                           RTRIM(@lvcOUTCODE) +
                           '_' +
                           LTRIM(RTRIM(@lcFORM_CODE)) 
                   END) +
                   '.txt'


IF @lcEXPORT_CODE IN ('624', '625')
BEGIN 
   SET @vcFILE_NAME_ARH = '4'+ 
                          ISNULL(RTRIM(REPLICATE('0',3 - LEN(ISNULL(dbo.[RA_GET_OPTION_STRING]('SUBJECT_CODE','EXPORT'),'')))),'') +  
                          LTRIM(RIGHT(RTRIM(ISNULL(dbo.[RA_GET_OPTION_STRING]('SUBJECT_CODE','EXPORT'),'')),3)) + 
                          RIGHT(CAST(YEAR(@ldBEGIN_DATE) AS VARCHAR(4)),1) +
                          RIGHT(RTRIM(CONVERT(CHAR(1), @lsVERSION)), 2) +
                          '.arj'
END
ELSE BEGIN   
   IF @lcEXPORT_CODE IN ('371','372','360')
   BEGIN
      SET @vcFILE_NAME_ARH = ISNULL(RTRIM(REPLICATE('0',CASE 
                                                           WHEN @lcEXPORT_CODE IN ('371', '372') THEN 3
                                                           ELSE 4
                                                        END - LEN(ISNULL(dbo.[RA_GET_OPTION_STRING]('SUBJECT_CODE','EXPORT'),'')))),'') +  
                             LTRIM(RIGHT(RTRIM(ISNULL(dbo.[RA_GET_OPTION_STRING]('SUBJECT_CODE','EXPORT'),'')),4)) + '_' +
                             RTRIM(REPLACE(CONVERT(VARCHAR(50),@ldBEGIN_DATE+1,4),'.','')) + '_' + 
                             RTRIM(RTRIM(CASE 
                                            WHEN @lcEXPORT_CODE = '' THEN @lcFORM_CODE
                                            ELSE @lcEXPORT_CODE
                                         END)) + '_' + 
                             CASE @ltPERIOD_TYPE
                                WHEN 1 THEN 'Y'
                                WHEN 2 THEN 'M' --'Q' 
                                ELSE 'M'
                             END + '_F_' + 
                             REPLICATE('0',@tVersionPlace - LEN(RIGHT(RTRIM(CONVERT(CHAR(4), @lsVERSION)), @tVersionPlace))) + RIGHT(RTRIM(CONVERT(CHAR(4), @lsVERSION)), 2) +
                             '.arj'
   END
   ELSE BEGIN
      SET @vcFILE_NAME_ARH = ISNULL(RTRIM(REPLICATE('0',4 - LEN(ISNULL(dbo.[RA_GET_OPTION_STRING]('SUBJECT_CODE','EXPORT'),'')))),'') +  
                             LTRIM(RIGHT(RTRIM(ISNULL(dbo.[RA_GET_OPTION_STRING]('SUBJECT_CODE','EXPORT'),'')),4)) + '_' +
                             RTRIM(REPLACE(CONVERT(VARCHAR(50),@ldBEGIN_DATE+1,4),'.','')) + '_' + 
                             RTRIM(RTRIM(CASE 
                                            WHEN @lcEXPORT_CODE = '' THEN @lcFORM_CODE
                                            ELSE @lcEXPORT_CODE
                                         END)) + '_' + 
                             CASE @ltPERIOD_TYPE
                                WHEN 1 THEN 'Y'
                                WHEN 2 THEN 'M' --'Q' 
                                ELSE 'M'
                             END + '_' + 
                             REPLICATE('0',@tVersionPlace - LEN(RIGHT(RTRIM(CONVERT(CHAR(4), @lsVERSION)), @tVersionPlace))) + RIGHT(RTRIM(CONVERT(CHAR(4), @lsVERSION)), 2) +
                             '.arj'
   END
END

EXEC dbo.[ВЕРСИЯ] @lvcVersion OUTPUT, 0

IF @lvcVersion IS NULL
BEGIN
   SET @lvcVersion = ''
END

-- Шапка внутреннего формата.
IF @iMode = 1
BEGIN
	INSERT #IMPORT_TABLE([TXT]) VALUES (@lvcDEP_NAME)
	
	INSERT #IMPORT_TABLE([TXT])
	SELECT 'ВФ=0'
	
   INSERT #IMPORT_TABLE([TXT])
	SELECT 'ПО=Свод-КС ' + REPLACE(REPLACE(@lvcVersion,'Версия',''),' ','')

	INSERT #IMPORT_TABLE([TXT])
	SELECT 'КБП=' + @lvcDEP_BUDG

	INSERT #IMPORT_TABLE([TXT])
	SELECT 'ВБ=' + RTRIM(@lvcOUTCODE)

	INSERT #IMPORT_TABLE([TXT])
	SELECT 'КФ=' + @lcFORM_CODE
	
	INSERT #IMPORT_TABLE([TXT])
	SELECT 'ПРД=' + LTRIM(STR(@ltPERIOD_TYPE))
	
	INSERT #IMPORT_TABLE([TXT])
	SELECT 'ДФ=' + CONVERT(CHAR(10), @ldSTART_DATE, 104) 
	
	INSERT #IMPORT_TABLE
	SELECT 'ДТ=' + CONVERT(CHAR(10), @ldBEGIN_DATE + 1, 104) 

	IF NULLIF(@lvcATRIBUTS,'') IS NOT NULL
	BEGIN
		INSERT #IMPORT_TABLE([TXT]) VALUES ('РА=0')

		WHILE @lvcATRIBUTS<>''
		BEGIN
			SET @liPosition = PATINDEX('%,%',@lvcATRIBUTS)

			IF @liPosition = 0
			BEGIN
			SET @liPosition = LEN(@lvcATRIBUTS) + 1
			END

			SET @lvcATR = LEFT(@lvcATRIBUTS,@liPosition-1)
			SET @lvcATRIBUTS = SUBSTRING(@lvcATRIBUTS,@liPosition+1,8000)
			SET @lvcTXT = @lvcATR + '=' + dbo.[RN_GET_ATR_VALUE](@iLINK_SAVED_FORM,@lvcATR)
			INSERT #IMPORT_TABLE([TXT]) VALUES (@lvcTXT)         
		END
	END
END

-- Шапка формата МФ.
IF @iMode = 2
BEGIN
   IF OBJECT_ID('tempdb..#tabPARAM_EXPORT') IS NULL
   BEGIN
      CREATE TABLE  #tabPARAM_EXPORT ([TXT]         VARCHAR(1000), 
                                      [TABLE_ORDER] INT IDENTITY(1,1))
	   WHILE LEN(@lvcPARAM_EXPORT) > 0
	   BEGIN
	   
			
		   EXEC dbo.[RO_FORMULA_FUNCTIONS] 1, 
										           @lvcPARAM_EXPORT OUTPUT, 
										           @lvcTXT OUTPUT, 
										           '#'
		   INSERT #tabPARAM_EXPORT([TXT]) VALUES (@lvcTXT)
		   
      END
   END

	INSERT #IMPORT_TABLE([TXT]) VALUES ('#%')

	INSERT #IMPORT_TABLE([TXT])
	SELECT 'КОДФ=' + CASE @lcEXPORT_CODE
					   WHEN '' THEN @lcFORM_CODE
					   ELSE @lcEXPORT_CODE
					END   

	INSERT #IMPORT_TABLE([TXT])
	SELECT 'ПРД=' + CASE @ltPERIOD_TYPE
					   WHEN 1 THEN '5' -- Год.
					   WHEN 2 THEN '3' -- '4' -- Квартал. 
					   ELSE '3'        -- Месяц.
				   END

	INSERT #IMPORT_TABLE([TXT])
	SELECT 'РДТ=' + CONVERT(CHAR(10), @ldBEGIN_DATE + 1, 104) 

	INSERT #IMPORT_TABLE([TXT])
	SELECT 'ВИД=' + RTRIM(@lvcOUTCODE)

   IF	(@lcFORM_CODE LIKE '05037%' OR 
       @lcFORM_CODE LIKE '05033%' OR 
       @lcFORM_CODE LIKE '425%' OR 
       @lcFORM_CODE LIKE '410G%') AND LEN(@lvcDEP_BUDG) = 2
   BEGIN
      SET @lvcDEP_BUDG = '0' + LTRIM(@lvcDEP_BUDG)
   END

	INSERT #IMPORT_TABLE([TXT])
	SELECT 'ИСТ=' + @lvcDEP_BUDG

	IF @lcFORM_CODE IN ('0503127M','0503127G','(72н)0503125','(72н)0503125М','(72н)425','425G','425M','(72н)425M','0503125G','0503125M','0503178G_Б','0503178M_Б', '0503725G', '0503725M')
	BEGIN	
	   IF	@lcFORM_CODE IN ('0503127M','0503127G','0503125G','0503125M','0503178G_Б','0503178M_Б')
	   BEGIN
     		INSERT #IMPORT_TABLE([TXT])
	   	SELECT 'ПРП=' + dbo.[RN_GET_ATR_VALUE](@iLINK_SAVED_FORM,'REPORTS_ATR_PRP')
	   END
	
	   IF	@lcFORM_CODE NOT IN ('0503127M','0503127G','0503178G_Б','0503178M_Б', '0503725G', '0503725M')
	   BEGIN
			if YEAR(@ldSTART_DATE) >=2011
			begin
   				INSERT #IMPORT_TABLE([TXT])
				SELECT 'КСБУ=' + dbo.[RN_GET_ATR_VALUE](@iLINK_SAVED_FORM,'REPORTS_ATR_ACC_2011')	
			end
			else begin
   				INSERT #IMPORT_TABLE([TXT])
				SELECT 'КСБУ=' + dbo.[RN_GET_ATR_VALUE](@iLINK_SAVED_FORM,'REPORTS_ATR_ACC')	
			end
		END

	   IF	@lcFORM_CODE IN ('0503725G','0503725M')
	   BEGIN
	      SET @lvcOKATO = ''
	   	
	   	SELECT @lvcOKATO = REPLACE(ISNULL(RTRIM([B].[OKATO]),''),' ','')
	      FROM dbo.[REPORT_SAVED_FORMS] [A]
	      JOIN dbo.[DEPARTMENTS]        [B] ON [B].[LINK] = [A].[LINK_ORGANIZATION] 	      
	      WHERE [A].[LINK_SAVED_FORM] = @iLINK_SAVED_FORM
	
     		INSERT #IMPORT_TABLE([TXT])
	   	SELECT 'ОКАТО=' + LEFT(@lvcOKATO,8)
	   END
      		
	   IF	@lcFORM_CODE IN ( '0503725G', '0503725M')
	   BEGIN
			INSERT #IMPORT_TABLE([TXT])
			SELECT 'КСБУ=' + dbo.[RN_GET_ATR_VALUE](@iLINK_SAVED_FORM,'REPORTS_ATR_ACC_725')	
		END

	   IF	@lcFORM_CODE IN ('0503125G','0503125M')
	   BEGIN
	      SET @lvcOKATO = ''
	   	
	   	SELECT @lvcOKATO = REPLACE(ISNULL(RTRIM([B].[OKATO]),''),' ','')
	      FROM dbo.[REPORT_SAVED_FORMS] [A]
	      JOIN dbo.[DEPARTMENTS]        [B] ON [B].[LINK] = [A].[LINK_ORGANIZATION] 	      
	      WHERE [A].[LINK_SAVED_FORM] = @iLINK_SAVED_FORM
	
     		INSERT #IMPORT_TABLE([TXT])
	   	SELECT 'ОКАТО=' + @lvcOKATO
	   END
	END	

	INSERT #IMPORT_TABLE ([TXT]) VALUES ('#')
END


CREATE TABLE #tabExcludeCodes([LINK_TABLE] INT,
                              [CODE]       VARCHAR(250))                  
INSERT #tabExcludeCodes([LINK_TABLE],
                        [CODE])                             
EXEC [RA_EXPORT_FORM_GET_EXCLUDE_CODES] @liFORM_LINK, @iLink_Saved_Form


-- Выгрузка части с данными.
DECLARE curTables CURSOR STATIC LOCAL FOR
	SELECT [A].[LINK_TABLE],
          [A].[ORDERS],
          [A].[VAL_TYPE],
          [A].[LINK_CODE_COL],
          [ORDER_CODE_COL] = [B].[ORDERS],
          [DICTIONARY_COLUMNS_LIST] = REPLACE(ISNULL([B].[DICTIONARY_COLUMNS_LIST] + ',',''),' ','') 
   FROM dbo.[REPORT_TABLES]   [A]
   JOIN dbo.[REPORT_COLOUMNS] [B] ON [A].[LINK_CODE_COL] = [B].[LINK_COL]
   WHERE [LINK_FORM] = @liFORM_LINK
   ORDER BY A.orders 

OPEN curTables

FETCH NEXT 
FROM curTables 
INTO @liTABLE_LINK, 
     @liTABLE_ORDER, 
     @liTABLE_VAL_TYPE, 
     @liLINK_CODE_COL,
     @ltORDER_CODE_COL,
     @lvcDICTIONARY_COLUMNS_LIST

SET @lbIsEmpty = 0
IF OBJECT_ID('tempdb..#tabPARAM_EXPORT') IS NOT NULL
BEGIN
   IF NOT EXISTS(SELECT *
                 FROM #tabPARAM_EXPORT)
   BEGIN
      SET @lbIsEmpty = 1
   END
END

WHILE @@FETCH_STATUS = 0
BEGIN
   --EXEC dbo.[I_REPORT_CREATE_PROC] @liTABLE_LINK,'#',3

	SET @lvcTXT = ''

   IF @iMode = 1 OR
      (@iMode = 2 AND @lbIsEmpty = 1)
   BEGIN
   		
   	  -- для формы 0503128 по внутреннему формату добавляются коды Администратора	
/*	  IF @lcFORM_CODE like '0503128%' AND  @liTABLE_ORDER IN (1,2,4) AND 1=0  
	  BEGIN
	  		  SELECT @lvcTXT = @lvcTXT + 
							   CASE WHEN @liTABLE_ORDER = 1 AND [ORDERS] = 2 
									   THEN 	(CASE [COL_TYPE] 
												   WHEN 0 THEN 'STR(COL'
												   ELSE 'RTRIM(COL' 
											   END + 
											   CAST([ORDERS] AS VARCHAR(3)) + 
											   ')+''|''+ case when RTRIM(COL16) = ''96000000000000000'' then ''000'' else '''+dbo.[RN_GET_ATR_VALUE](@iLINK_SAVED_FORM,@lvcATR)+ ''' end +''|''+') 
									 WHEN @liTABLE_ORDER = 2 AND [ORDERS] = 13 
									   THEN 	(CASE [COL_TYPE] 
												   WHEN 0 THEN 'case when RTRIM(COL13) = ''50090000000000000000'' then ''000'' else '''+ dbo.[RN_GET_ATR_VALUE](@iLINK_SAVED_FORM,@lvcATR)+'''end +''|''+'+'STR(COL'
												   ELSE 'case when RTRIM(COL13) = ''50090000000000000000'' then ''000'' else '''+ dbo.[RN_GET_ATR_VALUE](@iLINK_SAVED_FORM,@lvcATR)+'''end +''|''+'+'RTRIM(COL' 
											   END + 
											   CAST([ORDERS] AS VARCHAR(3)) + 
											   ')+''|''+') 	
									  WHEN @liTABLE_ORDER = 4 AND [ORDERS] = 2 
									   THEN 	(CASE [COL_TYPE] 
												   WHEN 0 THEN 'STR(COL'
												   ELSE 'RTRIM(COL' 
											   END + 
											   CAST([ORDERS] AS VARCHAR(3)) + 
											   ')+''|''+') 			   
									   
									   ELSE    (CASE [COL_TYPE] 
												   WHEN 0 THEN 'STR(COL'
												   ELSE 'RTRIM(COL' 
											   END + 
											   CAST([ORDERS] AS VARCHAR(3)) + 
											   ')+''|''+')
								END	   
			  FROM dbo.[REPORT_COLOUMNS]
			  WHERE [ISEXPORTED] = 1 AND
					[LINK_TABLE] = @liTABLE_LINK 
			  ORDER BY [EXPORT_ORDER]

	  
		--SELECT @lvcTXT
			  
	  END   	
	  ELSE BEGIN
*/	       	

			  SELECT @lvcTXT = @lvcTXT + 
							   CASE [COL_TYPE] 
								   WHEN 0 THEN 'STR(COL'
								   ELSE 'RTRIM(COL' 
							   END + 
							   CAST([ORDERS] AS VARCHAR(3)) + 
							   ')+''|''+'
			  FROM dbo.[REPORT_COLOUMNS]
			  WHERE [ISEXPORTED] = 1 AND
					[LINK_TABLE] = @liTABLE_LINK 
			  ORDER BY [EXPORT_ORDER]
/*	   END	*/	
      
      IF LEN(@lvcTXT)>0
      BEGIN
         SET @lvcTXT = LEFT(@lvcTXT,LEN(@lvcTXT)-1)
      END


    -- select @lvcTXT 
   END
   ELSE BEGIN

   	SELECT @lvcTXT = [TXT]
      FROM #tabPARAM_EXPORT 
      WHERE [TABLE_ORDER] = @liTABLE_ORDER
    END


	IF LEN(ISNULL(@lvcTXT, '')) > 0
	BEGIN
      IF @iMode = 1
      BEGIN
   		INSERT #IMPORT_TABLE 
        SELECT [TXT] = 'РД=' + LTRIM(CONVERT(VARCHAR(2),@liTABLE_ORDER)) 
      END
      ELSE BEGIN
   		INSERT #IMPORT_TABLE([TXT]) SELECT '#@'
   		INSERT #IMPORT_TABLE([TXT]) SELECT 'ТБ=' + RIGHT(RTRIM('0' + LTRIM(CONVERT(CHAR(2),@liTABLE_ORDER))),2)
   		INSERT #IMPORT_TABLE([TXT]) SELECT '#$'
      END


/*
		SELECT @liLINK_CODE_COL = [LINK_CODE_COL]
      FROM dbo.[REPORT_TABLES]
      WHERE [LINK_TABLE] = @liTABLE_LINK
*/

		SELECT @lvcExecTable = 'CREATE TABLE #tabRI_PROC_T ([CHECKED] INT, [UPD] INT, [DEL] INT, [LINK_SAVED_FORM] INT, [LINK_ROW] INT, [ORDERS] INT, [CALC_ORDERS] INT, [PRINT_NULL] INT, [CODE] ' + 
                             CASE 
                                WHEN [A].[COL_TYPE] = 1 THEN 'VARCHAR(50)' 
                                ELSE 'FLOAT' 
                             END,
				 @lvcUpdateSelect = 'SELECT [CHECKED], [UPD], [DEL], [LINK_SAVED_FORM], [LINK_ROW], [ORDERS], [CALC_ORDERS], [PRINT_NULL], [CODE] '
		FROM dbo.[REPORT_COLOUMNS]    [A]
      LEFT JOIN dbo.[REPORT_TABLES] [B] ON [B].[LINK_CODE_COL] = [A].[LINK_COL]
		WHERE [B].[LINK_TABLE] = @liTABLE_LINK


      SET @lvcTXTDataNotNull = '1=2'

   IF EXISTS(SELECT * FROM REPORT_FORMS A 
   INNER JOIN REPORT_TABLES B ON A.Link_Form = B.Link_Form
             WHERE B.Link_Table = @liTABLE_LINK AND A.Code = '0503317M' AND B.Orders IN (1,3))
      SET @lvcTXTDataNotNull = '1=1'
       
        

   	DECLARE tabColumns CURSOR LOCAL STATIC FOR 
         SELECT [LINK_COL],
                [COL_TYPE],
                [ORDERS],
                [VAL_LEN],
                [ISEDITED],
                [ISEXPORTED]
         FROM dbo.[REPORT_COLOUMNS]
         WHERE [LINK_TABLE] = @liTABLE_LINK 
         ORDER BY [ORDERS]

		OPEN tabColumns

		FETCH 
      NEXT FROM tabColumns
		INTO @liCOL_LINK, 
           @liCOL_TYPE, 
           @liORDERS, 
           @liCOL_VAL_LEN, 
           @ltCOL_ISEDITED,
           @ltCOL_ISEXPORTED
      
   
		WHILE @@FETCH_STATUS = 0
		BEGIN
			SELECT @lvcORDERS = LTRIM(STR(@liORDERS)),
					 @lvcExecTable = @lvcExecTable + ', COL' + @lvcORDERS + 
										  CASE 
	                                WHEN @liCOL_TYPE = 1 THEN ' VARCHAR(8000)' 
		                             ELSE ' NUMERIC(20,' + LTRIM(STR(@liCOL_VAL_LEN)) + ')' 
			                       END,
					 @lvcUpdateSelect = @lvcUpdateSelect + 
  											  ', COL' + @lvcORDERS + 
											  '=ISNULL(COL' + @lvcORDERS + ',' + 
											  CASE 
												  WHEN @liCOL_TYPE = 1 THEN '''''' 
												  ELSE '0'
											  END + ')'

			IF @ltCOL_ISEXPORTED = 1 AND 
			   @liORDERS <> @ltORDER_CODE_COL AND
			   @lvcDICTIONARY_COLUMNS_LIST not like '%COL' + @lvcORDERS + ',%'
			BEGIN			
			   IF @liCOL_TYPE = 0
			   BEGIN
				   SET @lvcTXTDataNotNull = @lvcTXTDataNotNull +                                       
                                        ' OR COL' + @lvcORDERS + ' <> 0'
			   END
			   ELSE BEGIN
				   SET @lvcTXTDataNotNull = @lvcTXTDataNotNull +                                       
                                        ' OR COL' + @lvcORDERS + ' <> '''''
			   END
			END

		   FETCH 
         NEXT FROM tabColumns
		   INTO @liCOL_LINK, 
              @liCOL_TYPE, 
              @liORDERS, 
              @liCOL_VAL_LEN, 
              @ltCOL_ISEDITED,
              @ltCOL_ISEXPORTED
		END

		CLOSE tabColumns
		DEALLOCATE tabColumns

		IF @liTABLE_VAL_TYPE = 0
      BEGIN
			SET @lvcExecTable = @lvcExecTable + ',[ITOG] TINYINT)'
      END
		ELSE BEGIN
			SET @lvcExecTable = @lvcExecTable + ')'
      END


		SET @lvcExec = @lvcExecTable + CHAR(13) +
                     ' INSERT #tabRI_PROC_T exec dbo.[RI_PROC_T' + 
                     CASE 
                        WHEN @bIsFormUnion = 1 THEN '#'
                        ELSE ''
                     END + 
                     LTRIM(STR(@liTABLE_LINK)) + 
     '] @DEL_FCOL=1, @varKSLSF=' + 
                     LTRIM(STR(@iLINK_SAVED_FORM)) 

      IF @iMode=2    
      BEGIN
 
         SET @lvcExec = @lvcExec + CHAR(13) +                        
                        ' EXEC dbo.[RA_EXPORT_FORM_UPDATE] ' + CAST(@liTABLE_LINK AS VARCHAR(50)) + ',DEFAULT,1' + CHAR(13) + 
								' INSERT #IMPORT_TABLE([TXT]) SELECT ' + REPLACE(REPLACE(REPLACE(@lvcTXT, 'STR(', 'CONVERT(VARCHAR(20), '),'$CODE4$','''+RIGHT(''0000''+CAST(ROW_NUMBER() OVER (ORDER BY [ORDERS],[CODE]) AS VARCHAR(50)),4)+'''),'$CODE3$','''+RIGHT(''000''+CAST(ROW_NUMBER() OVER (ORDER BY [ORDERS],[CODE]) AS VARCHAR(50)),3)+''') + CHAR(13) + 
								' FROM ('+@lvcUpdateSelect+' FROM #tabRI_PROC_T) [QQ] WHERE ' + @lvcTXTDataNotNull + CHAR(13) + 'ORDER BY [ORDERS],[CODE] ' + 
								' DROP TABLE #tabRI_PROC_T'
      END
		ELSE BEGIN
			SET @lvcExec = @lvcExec + CHAR(13) +
								' INSERT #IMPORT_TABLE([TXT]) SELECT ' + REPLACE(@lvcTXT, 'STR(', 'CONVERT(VARCHAR(20), ') + ' FROM #tabRI_PROC_T WHERE ' + @lvcTXTDataNotNull + CHAR(13) + 'ORDER BY [ORDERS],[CODE] ' + 
								' DROP TABLE #tabRI_PROC_T'

		END

    -- print @lvcDICTIONARY_COLUMNS_LIST
    --print @iLINK_SAVED_FORM
    -- print @lvcExec 

 		EXEC(@lvcExec)

		IF @iMODE = 2  
      BEGIN
   		INSERT #IMPORT_TABLE (Txt) SELECT '#'
      END
	END

	FETCH NEXT 
   FROM curTables 
   INTO @liTABLE_LINK, 
        @liTABLE_ORDER, 
        @liTABLE_VAL_TYPE, 
        @liLINK_CODE_COL,
        @ltORDER_CODE_COL,
        @lvcDICTIONARY_COLUMNS_LIST        
END

CLOSE curTables
DEALLOCATE curTables


IF @iMode = 2
BEGIN
-- Выгрузка подписей.

   SELECT @vcBOSS = r.[boss],
          @vcBUH = r.[buh],
          @vcISP = r.[isp],
          @vcTel = r.[isp_tel]
   FROM dbo.[RT_VIEW_WEB_BOSS] r
   WHERE r.[link] = @liDEP_LINK


	INSERT #IMPORT_TABLE([TXT]) SELECT '#&'

   SELECT @liDEP_LINK_OWN = [LINK]
   FROM dbo.[DEPARTMENTS]   
   WHERE [TYPE] = 4

   SET  @lvcExec = 'Руководитель='
	SELECT @lvcExec = @lvcExec + RTRIM(REPLACE(ISNULL([CHIEF],''),'. ','.'))
   FROM dbo.[PrintDoc_GetDepData2](@liDEP_LINK_OWN)
   
   INSERT #IMPORT_TABLE([TXT]) VALUES (@lvcExec)

   SET @lvcExec = 'Гл. бухгалтер='
	SELECT @lvcExec = @lvcExec + RTRIM(REPLACE(ISNULL([GLBUH],''),'. ','.'))
   FROM dbo.[PrintDoc_GetDepData2](@liDEP_LINK_OWN)

	INSERT #IMPORT_TABLE([TXT]) VALUES (@lvcExec)

   SET @lvcExec = 'Исполнитель='
	SELECT  @lvcExec = @lvcExec + RTRIM(ISNULL([FIO],''))
   FROM dbo.[RA_GET_USER_INFO](NULL)
   
   IF @lvcExec = 'Исполнитель='
   BEGIN
      SET @lvcExec = @lvcExec + ISNULL(@vcISP, '')
   END       

   INSERT #IMPORT_TABLE([TXT]) VALUES (@lvcExec)
   
	SET @lvcExec = 'Тел.=' 
	SELECT  @lvcExec = @lvcExec + RTRIM(ISNULL([PHONES],''))
   FROM dbo.[RA_GET_USER_INFO](NULL)
   
   IF @lvcExec = 'Тел.='
   BEGIN
      SET @lvcExec = @lvcExec + ISNULL(@vcTel, '')
   END        

	IF ISNULL(@lvcExec, '') <> ''
   BEGIN
		INSERT #IMPORT_TABLE([TXT]) VALUES (@lvcExec)
   END

	INSERT #IMPORT_TABLE([TXT]) SELECT '#'
	INSERT #IMPORT_TABLE([TXT]) SELECT '#~'

	INSERT #IMPORT_TABLE([TXT]) SELECT 'ППО=Свод-КС ' + RTRIM(@lvcVersion)
	FROM dbo.[REPORT_SAVED_FORMS]
	WHERE [LINK_SAVED_FORM] = @iLINK_SAVED_FORM	

	INSERT #IMPORT_TABLE (Txt) SELECT '#'
	INSERT #IMPORT_TABLE (Txt) SELECT '##'

   EXEC dbo.[RA_IMPORT_FORM_REPLACE_DATA] @tMode = 2,
                                          @cCODE_FORM = @lcFORM_CODE,
                                          @iLINK_SAVED_FORM = @iLINK_SAVED_FORM
                                                                 
   DROP TABLE #tabPARAM_EXPORT
END


INSERT #FileExportReport([TXT],
                         [NameFile],
                         [ORDERS],
                         [NameFileArh])
SELECT RTRIM(TXT), 
       @vcFILE_NAME, 
       [ORDER],
       @vcFILE_NAME_ARH
FROM #IMPORT_TABLE

--select * from #IMPORT_TABLE

DROP TABLE #IMPORT_TABLE 
DROP TABLE #REPORT_DINAMICS
DROP TABLE #REPORT_SUMMA
DROP TABLE #tabExportForms






GO


GRANT EXECUTE ON dbo.[RA_EXPORT_FORM_STANDART] TO PUBLIC

GO


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


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

GO
CREATE PROCEDURE dbo.BK_EXPORT_F1152004_503
	(@iLINK_FORM INT)
AS
BEGIN

--перенос формы из архивной базы
exec 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),
		@POST_GL_BUH	VARCHAR (254),
		@DEP_NAME VARCHAR (254),

		@DOC_ID		VARCHAR (36),

		@NAME_RUK	VARCHAR (60),
		@FAM_RUK	VARCHAR (60),
		@OT_RUK		VARCHAR (60),

		@NAME_GL_BUH	VARCHAR (60),
		@FAM_GL_BUH	VARCHAR (60),
		@OT_GL_BUH	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 (30),
		@OKTMO VARCHAR (15),
		@OKTMO_DIC VARCHAR (15),
		@SUMMA	NUMERIC (15,0),

		@SUM_AV NUMERIC (15,0),
		@SUM_PAY NUMERIC (15,0),
		@SUM_LOW NUMERIC (15,0),

		@LINK_COL_CODE INT,
		@NUM_KOR NUMERIC (20),
		
		@strNUM_COR	VARCHAR (3),
		@C_PLACE	VARCHAR (3),
		
		@cREORG_CODE	VARCHAR (1),
		@cREORG_INN	VARCHAR (12),
		@cREORG_KPP	VARCHAR (12),
		
		@SUM1	NUMERIC (15,0),
		@SUM11	NUMERIC (15,0),
		@SUM12	NUMERIC (15,0),
		@SUM13	NUMERIC (15,0),
		@SUM2	NUMERIC (15,0),

		--- Раздел 2 ---
		@LINK_COL_VIDTS	INT,
		@LINK_COL_VIN	INT,
		@LINK_COL_MARKA	INT,
		@LINK_COL_REGNO	INT,
		@LINK_COL_NALBAS INT,
		@LINK_COL_OKEI	INT,
		@LINK_COL_SROK	INT,
		@LINK_COL_K3623	INT,
		@LINK_COL_STAVKA INT,
		@LINK_COL_SUM_IS	INT,
		@LINK_COL_LGOTA	INT,
		@LINK_COL_SUM_LGOTA	INT,
		@LINK_COL_SUM_UPL	INT,

		@strEXEC	VARCHAR (8000)

	--- Данные организации ---
	SELECT
		@DEP_LINK = RSF.LINK_ORGANIZATION,
		@dDATE_FORM	= RSF.BEGIN_DATE,
		@PERIOD_TYPE = RSF.PERIOD_TYPE,
		@PERIOD_NUM	= RSF.PERIOD_NUMBER,
		
		@INN	= CONVERT (VARCHAR (10), DEP.INN_LONG),
		@KPP = CONVERT (VARCHAR (9), DEP.KPP),
		@IMNS = CONVERT (VARCHAR (4), DEP.IMNS),
		@OKVED = CONVERT (VARCHAR (8), DEP.OKVED),
		@DEP_NAME = DEP.[NAME],
		@OKTMO_DIC = CONVERT (VARCHAR (11), REPLACE (DEP.OKTMO, ' ', ''))
		
	FROM dbo.REPORT_SAVED_FORMS RSF
	INNER JOIN dbo.DICTIONARY_DEPARTMENT DEP ON (DEP.LINK = RSF.LINK_ORGANIZATION)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM

	SET @cPERIOD_NUM = CASE
							WHEN @PERIOD_NUM = 1 THEN '21'
							WHEN @PERIOD_NUM = 2 THEN '22'
							WHEN @PERIOD_NUM = 3 THEN '23'
						END

	EXEC dbo.GetRandStr
			36,
			@DOC_ID OUTPUT

	SELECT
		@PART_NAME_NNN = @DOC_ID

	SELECT
		@TLF_GL_BUH = A.PHONE,
		@POST_GL_BUH = B.POST_NAME,

		@NAME_GL_BUH = B.IM,
		@FAM_GL_BUH = B.FM,
		@OT_GL_BUH = B.OT
	FROM dbo.DICTIONARY_OTV_FACE A
	LEFT JOIN dbo.KU_EMPL_PLACING B ON (B.LINK = A.FACE_LINK)
	WHERE A.DEP_LINK = @DEP_LINK
		AND A.[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)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM
		AND ORDERS = 1

	CREATE TABLE #TAB1
		(
		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(100),	-- 
		FCOL2 VARCHAR (1000),
		COL3 NUMERIC (20), 	-- 
		FCOL3 VARCHAR (1000),
		COL4 NUMERIC(20), 	-- 
		FCOL4 VARCHAR (1000),
		COL5 NUMERIC(20),	-- 
		FCOL5 VARCHAR (1000),
		COL6 NUMERIC (20), 	-- 
		FCOL6 VARCHAR (1000),
		COL7 NUMERIC (20), 	-- 
		FCOL7 VARCHAR (1000),
		COL8 NUMERIC(20),	-- 
		FCOL8 VARCHAR (1000),
		COL9 VARCHAR(100),	-- 
		FCOL9 VARCHAR (1000),
		COL10 VARCHAR (100),	-- 
		FCOL10 VARCHAR (1000),
		COL11 VARCHAR(100),	-- 
		FCOL11 VARCHAR (1000),
		COL12 VARCHAR(100),	-- 
		FCOL12 VARCHAR (1000),
		COL13 VARCHAR(100),	-- 
		FCOL13 VARCHAR (1000),
		COL14 VARCHAR(100),	-- 
		FCOL14 VARCHAR (1000),
		COL15 VARCHAR(100),	-- 
		FCOL15 VARCHAR (1000),
		ITOG NUMERIC(20)
		)
	
	IF @iLINK_TABLE > 0
	BEGIN
	
		SET @strEXEC = 'INSERT INTO #TAB1 (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,
							COL13, FCOL13, COL14, FCOL14, COL15, FCOL15,
							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 #TAB1
		
	END
	
	SELECT
		@OKTMO = ISNULL (COL2, ''),
		@KBK = ISNULL (COL9, ''),
		@strNUM_COR = ISNULL (COL10, ''),
		@C_PLACE = ISNULL (COL11, ''),
		@cPERIOD_NUM = ISNULL (COL12, ''),
		@cREORG_CODE = ISNULL (COL13, ''),
		@cREORG_INN = ISNULL (COL14, ''),
		@cREORG_KPP = ISNULL (COL15, ''),
		
		@SUM1	= ISNULL (COL3, 0),
		@SUM11	= ISNULL (COL4, 0),
		@SUM12	= ISNULL (COL5, 0),
		@SUM13	= ISNULL (COL6, 0),
		@SUM2	= ISNULL (COL7, 0) - ISNULL (COL7, 0)
	FROM #TAB1

	-- Данные раздела 2 --
	SET @iLINK_TABLE = 0
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM dbo.REPORT_SAVED_FORMS RSF 
	INNER JOIN dbo.REPORT_TABLES RT ON (RT.LINK_FORM = RSF.LINK_FORM)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM
		AND ORDERS = 2
		
	CREATE TABLE #TAB2
		(
		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(100),	-- 
		FCOL2 VARCHAR (1000),
		COL3 VARCHAR(100),	-- 
		FCOL3 VARCHAR (1000),
		COL4 VARCHAR(100),	-- 
		FCOL4 VARCHAR (1000),
		COL5 VARCHAR(100),	-- 
		FCOL5 VARCHAR (1000),
		COL6 NUMERIC (20, 2), 	-- 
		FCOL6 VARCHAR (1000),
		COL7 VARCHAR(100), --
		FCOL7 VARCHAR (1000),
		COL8 VARCHAR(100), --
		FCOL8 VARCHAR (1000),
		COL9 NUMERIC (20), 	-- 
		FCOL9 VARCHAR (1000),
		COL10 NUMERIC (20), 	-- 
		FCOL10 VARCHAR (1000),
		
		COL11 VARCHAR (100), -- 
		FCOL11 VARCHAR (1000),
		
		COL12 NUMERIC (20, 4), -- 
		FCOL12 VARCHAR (1000),
		COL13 NUMERIC (20, 4), -- 
		FCOL13 VARCHAR (1000),
		
		COL14 NUMERIC (20, 1), -- 
		FCOL14 VARCHAR (1000),
				
		COL15 NUMERIC (20), -- 
		FCOL15 VARCHAR (1000),
		COL16 NUMERIC (20),	-- 
		FCOL16 VARCHAR (1000),
		COL17 NUMERIC (20, 4), -- 
		FCOL17 VARCHAR (1000),
		
		COL18 VARCHAR(100), --
		FCOL18 VARCHAR (1000),
		COL19 NUMERIC (20), 	-- 
		FCOL19 VARCHAR (1000),
		COL20 VARCHAR(100), --
		FCOL20 VARCHAR (1000),
		COL21 NUMERIC (20), 	-- 
		FCOL21 VARCHAR (1000),
		COL22 VARCHAR(100), --
		FCOL22 VARCHAR (1000),
		COL23 NUMERIC (20), -- 
		FCOL23 VARCHAR (1000),
		COL24 NUMERIC (20), -- 
		FCOL24 VARCHAR (1000),
		
		ITOG NUMERIC(20) DEFAULT (0)
		)

	IF @iLINK_TABLE > 0
	BEGIN
		SET @strEXEC = 'INSERT INTO #TAB2 (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,
							COL13, FCOL13, COL14, FCOL14, COL15, FCOL15,
							COL16, FCOL16, COL17, FCOL17, COL18, FCOL18,
							COL19, FCOL19, COL20, FCOL20, COL21, FCOL21,
							COL22, FCOL22, COL23, FCOL23, COL24, FCOL24
							)
				EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
					+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'
		EXECUTE (@strEXEC)
	END

	--- Формирование XML ---
	SELECT @FNAME_ID = 'NO_TRAND_' + 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, '<Документ КНД="1152004"')
	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, '<СумНалПУ КБК="' + @KBK + '">')
	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СумПУ ОКТМО="' + @OKTMO + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалИсчисл="' + CONVERT (VARCHAR (15), @SUM1) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'АвПУКв1="' + CONVERT (VARCHAR (15), @SUM11) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'АвПУКв2="' + CONVERT (VARCHAR (15), @SUM12) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'АвПУКв3="' + CONVERT (VARCHAR (15), @SUM13) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НалПУ="' + CONVERT (VARCHAR (15), @SUM2) + '">')

	-- Расчет суммы транспортного налога по каждому транспортному средству (РасчНалТС) --
--	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<РасчНалТС>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT)
	SELECT
		@FNAME,
		'<РасчНалТС КодВидТС="' + LTRIM (ISNULL (COL2, '')) 
		+ '" ИдНомТС="' + LTRIM (ISNULL (COL3, '')) 
		+ '" МаркаТС="' + LTRIM (ISNULL (COL4, '')) 
		+ '" РегЗнакТС="' + LTRIM (ISNULL (COL5, '')) 
		+ '" НалБаза="' + LTRIM (STR (ISNULL (COL6, 0), 16, 2))  
		+ '" ОКЕИНалБаза="' + LTRIM (ISNULL (COL7, ''))
		+ '" ЭкологКл="' + LTRIM (ISNULL (COL8, ''))
		+ '" ВыпускТС="' + LTRIM (STR (ISNULL (COL9, 0)))
		+ '" ВладенТС="' + LTRIM (STR (ISNULL (COL10, 0)))
		+ '" ДоляТС="' + LTRIM (ISNULL (COL11, ''))
		
		+ '" КоэфКв="' + LTRIM (STR (ISNULL (COL12, 0), 6, 4))  
		+ '" НалСтавка="' + LTRIM (STR (ISNULL (COL13, 0), 10, 2))

		+ CASE  WHEN ISNULL (COL14, 0) = 1 THEN '' ELSE  ('" КоэфКп="' + LTRIM (STR (ISNULL (COL14, 0), 3, 1)) ) END 

		+ '" СумИсчисл="' + LTRIM (STR (ISNULL (COL15, 0)))
		+ '" ЛьготМесТС="' + LTRIM (STR (ISNULL (COL16, 0)))
		+ '" КоэфКл="' + LTRIM (STR (ISNULL (COL17, 0), 6, 4))  
		+ '" СумИсчислУпл="' + LTRIM (STR (ISNULL (COL24, 0))) + '">'
		+ '<ЛьготОсвНал КодОсвНал="' + LTRIM (ISNULL (COL18, ''))
		+ '" СумОсвНал="' + LTRIM (STR (ISNULL (COL19, 0))) + '"/>'
		+ '<ЛьготУменСум КодУменСум="' + LTRIM (ISNULL (COL20, ''))
		+ '" СумУменСум="' + LTRIM (STR (ISNULL (COL21, 0))) + '"/>'
		+ '<ЛьготСнижСтав КодСнижСтав="' + LTRIM (ISNULL (COL22, ''))
		+ '" СумСнижСтав="' + LTRIM (STR (ISNULL (COL23, 0))) + '"/>'
		+ '</РасчНалТС>'
	FROM #TAB2 

--	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, '</ТрНалНД>')

	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 #TAB1
	DROP TABLE #TAB2
	DROP TABLE #TASK_PROP

END 




GO


GRANT EXECUTE ON dbo.[BK_EXPORT_F1152004_503] TO PUBLIC

GO




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

GO


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

	справка к балансу по заключению счетов
*/
CREATE PROCEDURE [dbo].[RB_CALC_72n_0503110] 
	 		@EDate	 datetime = '20050101', 
			@depLink int,
			@iTab	 int = 1
		
as

declare @dDate1 	datetime

set @dDate1 = dateadd(day, 1, @EDate)

declare @tRest table (D_SUMMA numeric(20, 2), K_SUMMA numeric(20, 2),  CODE varchar(10), ACC_CODE varchar(30), SOURCE char(1))
declare @tOborot table (D_SUMMA numeric(20, 2), K_SUMMA numeric(20, 2), CODE varchar(10), ACC_CODE varchar(30), SOURCE char(1), DB_KR tinyint)

EXEC dbo.BufferClear 'DT_ACC'
EXEC dbo.BufferClear 'KT_ACC'

insert into dbo.BUFFER(ID,LINK)
select 'DT_ACC', SA.LINK
from dbo.S_ACCOUNTS SA
where 	SA.cSinth = '401' and (SA.cAnalit = '01' or SA.cAnalit = '02') or
	SA.cSinth = '210' and SA.cAnalit = '02' or
	SA.cSinth = '304' and (SA.cAnalit = '04' or SA.cAnalit = '05') and
	not exists(select * from dbo.S_ACCOUNTS SA1 where SA1.LINK_SELF = SA.LINK)	
		
insert into dbo.BUFFER(ID,LINK)
select 'KT_ACC', SA.LINK
from dbo.S_ACCOUNTS SA
where 	SA.cSinth = '401' and SA.cAnalit = '03' and
	not exists(select * from dbo.S_ACCOUNTS SA1 where SA1.LINK_SELF = SA.LINK)

insert @tOborot
select sum(SY.D_SUMMA), sum(SY.K_SUMMA), SY.CODE, rtrim(SY.ACC_CODE), SY.SOURCE, case when SY.DB_KR  = 2 and sum(SY.D_SUMMA) < sum(SY.K_SUMMA) then 1 when SY.DB_KR  = 2 and sum(SY.D_SUMMA) >= sum(SY.K_SUMMA) then 2 else SY.DB_KR end
from(	select D_SUMMA, K_SUMMA, left(S.ACC_CODE,1) as SOURCE, substring(S.ACC_CODE,2,5) as CODE, ACC_CODE = case when S.ACC_CODE like '_40101%' and KBK.TYPE > 1 then left(rtrim(REPLACE(isnull(KBK.CODE,'0000000000000'), '.', '')),13) + S.ACC_CODE + isnull(SGU.CODE,'000') 
												 																when S.ACC_CODE like '_40101%' and KBK.TYPE = 1 then left(rtrim(REPLACE(isnull(KBK.CODE,'0000000'), '.', '')),7) + '0000000' + S.ACC_CODE + isnull(SGU.CODE,'000') 
												 															--	when S.ACC_CODE like '_40101%' and KBK.TYPE = 1 then left(rtrim(REPLACE(isnull(KBK.CODE,'00000000000000'), '.', '')),14) + S.ACC_CODE + isnull(SGU.CODE,'000') 
												 																when S.ACC_CODE like '_30404%' and KBK.TYPE > 1 then '0000000000000' + substring(S.ACC_CODE,2,5) + isnull(SGU.CODE,'000') 
												 																when S.ACC_CODE like '_30404%' and KBK.TYPE = 1 then '00000000000000' + substring(S.ACC_CODE,2,5) + isnull(SGU.CODE,'000') 
												 																when (S.ACC_CODE like '_21002%' or ACC_CODE like '_30405%') and KBK.TYPE > 1 then '0000000000000' + S.ACC_CODE + isnull(SGU.CODE,'000') 
												 																when (S.ACC_CODE like '_21002%' or ACC_CODE like '_30405%') and KBK.TYPE = 1 then '00000000000000' + S.ACC_CODE + isnull(SGU.CODE,'000') 
												 																else '' end , DB_KR = case when S.ACC_CODE like '_40101%' then SGU.DB_KR
																																			when S.ACC_CODE like '_21002%'then 0
																																			when S.ACC_CODE like '_30405%'then 1
																																			when S.ACC_CODE like '_30404%'then 2
																																			else 1 end
	from (select LINK, SUMMA as D_SUMMA, 0 as K_SUMMA, left(REPLACE(CODE_DT, '.', ''),6) as ACC_CODE, DT_VKR as KBK, DT_SGU as SGU from dbo.AProvByBufferConditionsShort(@EDate, @EDate, 'DT_ACC', 'KT_ACC') where DEP_LINK = @depLink union all
	      select LINK, 0, SUMMA, left(REPLACE(CODE_KT, '.', ''),6), KT_VKR, KT_SGU from dbo.AProvByBufferConditionsShort(@EDate, @EDate, 'KT_ACC', 'DT_ACC') where DEP_LINK = @depLink) S
	inner join dbo.KOSGU  SGU on S.SGU = SGU.LINK
	inner join dbo.KL_KBK KBK on S.KBK = KBK.LINK and (@iTab = 1 and KBK.TYPE = 2 or @iTab = 2 and KBK.TYPE = 1 or @iTab = 3 and (KBK.TYPE = 4 or KBK.TYPE = 8))
	left join dbo.G_PROV G   on S.LINK = G.LINK
	left join dbo.S_OBJECTS SO on G.OBJECT = SO.LINK AND SO.cODE = 'BK_DOCUMENT_CLOSE_YEAR') SY
group by SY.ACC_CODE, SY.SOURCE, SY.CODE, SY.DB_KR

insert into @tRest
select sum(S.D_SUMMA), sum(S.K_SUMMA), CODE, rtrim(S.ACC_CODE), S.SOURCE
from(	select R.D_SUMMA, R.K_SUMMA, substring(SA.CODE,2,5) as CODE, left(SA.CODE,1) as SOURCE, ACC_CODE = case when SA.CODE like '_40101%' and KBK.TYPE > 1 then left(rtrim(REPLACE(isnull(KBK.CODE,'0000000000000'), '.', '')),13) + SA.CODE + isnull(SGU.CODE,'000') 
												 																when SA.CODE like '_40101%' and KBK.TYPE = 1 then left(rtrim(REPLACE(isnull(KBK.CODE,'0000000'), '.', '')),7) + '0000000' + SA.CODE + isnull(SGU.CODE,'000') 
												 																--when SA.CODE like '_40101%' and KBK.TYPE = 1 then left(rtrim(REPLACE(isnull(KBK.CODE,'00000000000000'), '.', '')),14) + SA.CODE + isnull(SGU.CODE,'000') 
												 																when SA.CODE like '_30404%' and KBK.TYPE > 1 then '0000000000000' + substring(SA.CODE,2,5) + isnull(SGU.CODE,'000') 
												 																when SA.CODE like '_30404%' and KBK.TYPE = 1 then '00000000000000' + substring(SA.CODE,2,5) + isnull(SGU.CODE,'000') 
												 																when (SA.CODE like '_21002%' or SA.CODE like '_30405%') and KBK.TYPE > 1 then '0000000000000' + SA.CODE + isnull(SGU.CODE,'000') 
												 																when (SA.CODE like '_21002%' or SA.CODE like '_30405%') and KBK.TYPE = 1 then '00000000000000' + SA.CODE + isnull(SGU.CODE,'000') 
												 																else '' end  
	from dbo.ARestTableByDateAccounts(@dDate1,'DT_ACC') R
	inner join (select link, left(replace(CODE,'.',''),6) as CODE from dbo.S_ACCOUNTS) SA ON SA.LINK = R.ACCOUNT
	inner join dbo.KOSGU SGU ON SGU.LINK = R.SGU
	left join dbo.KL_KBK KBK on R.KBK = KBK.LINK  and (@iTab = 1 and KBK.TYPE = 2 or @iTab = 2 and KBK.TYPE = 1 or @iTab = 3 and (KBK.TYPE = 4 or KBK.TYPE = 8))
	where R.DEP_LINK = @depLink) S
group by S.ACC_CODE, S.SOURCE, S.CODE

EXEC dbo.BufferClear 'DT_ACC'
EXEC dbo.BufferClear 'KT_ACC'

--select * from @tRest
--select * from @tOborot

if @iTab = 2
	SELECT	[CODE] = rtrim(SC.ACC_CODE),
		--[CODE] = case when len(SC.ACC_CODE) > 15 then SC.ACC_CODE else '00000000000000000' + SC.ACC_CODE end,
		[COL1] = left(SC.ACC_CODE,3),
		[COL2] = substring(SC.ACC_CODE,4,4),
		[COL3] = substring(SC.ACC_CODE,8,7),
		[COL4] = substring(SC.ACC_CODE,15,9),
		[COL5] = substring(SC.ACC_CODE,24,3),
		[COL6] = case when (SC.CODE = '40101') and O1.DB_KR = 0 or 
				   (SC.CODE <> '40101' and substring(SC.ACC_CODE,19,5) <> '30404' and SA.S_PASSIVE = 1) or  
				   (SC.CODE = '30404' and isnull(R1.D_SUMMA,0) - isnull(R1.K_SUMMA,0) - isnull(O1.D_SUMMA,0) + isnull(O1.K_SUMMA,0) < 0)then 0
				else isnull(R1.D_SUMMA,0) - isnull(R1.K_SUMMA,0) - isnull(O1.D_SUMMA,0) + isnull(O1.K_SUMMA,0) end,
		[COL7] = case when (SC.CODE = '40101') and O1.DB_KR = 1 or 
				   (SC.CODE <> '40101' and substring(SC.ACC_CODE,19,5) <> '30404' and SA.S_PASSIVE = 0) or 
				   (SC.CODE = '30404' and isnull(R1.K_SUMMA,0) - isnull(R1.D_SUMMA,0) - isnull(O1.K_SUMMA,0) + isnull(O1.D_SUMMA,0) < 0) then 0
				else isnull(R1.K_SUMMA,0) - isnull(R1.D_SUMMA,0) - isnull(O1.K_SUMMA,0) + isnull(O1.D_SUMMA,0) end,
		[COL8] = case when (SC.CODE = '40101') and O2.DB_KR = 0 or 
				   (SC.CODE <> '40101' and substring(SC.ACC_CODE,19,5) <> '30404' and SA.S_PASSIVE = 1) or 
				   (SC.CODE = '30404' and isnull(R2.D_SUMMA,0) - isnull(R2.K_SUMMA,0) - isnull(O2.D_SUMMA,0) + isnull(O2.K_SUMMA,0) < 0) then 0
				else isnull(R2.D_SUMMA,0) - isnull(R2.K_SUMMA,0) - isnull(O2.D_SUMMA,0) + isnull(O2.K_SUMMA,0) end,
		[COL9] = case when (SC.CODE = '40101') and O2.DB_KR = 1 or 
				   (SC.CODE <> '40101' and substring(SC.ACC_CODE,19,5) <> '30404' and SA.S_PASSIVE = 0) or 
				   (SC.CODE = '30404' and isnull(R2.K_SUMMA,0) - isnull(R2.D_SUMMA,0) - isnull(O2.K_SUMMA,0) + isnull(O2.D_SUMMA,0) < 0) then 0
				else isnull(R2.K_SUMMA,0) - isnull(R2.D_SUMMA,0) - isnull(O2.K_SUMMA,0) + isnull(O2.D_SUMMA,0) end,
		[COL10] = isnull(O1.D_SUMMA,0),
		[COL11] = isnull(O1.K_SUMMA,0),
		[COL12] = isnull(O2.D_SUMMA,0),
		[COL13] = isnull(O2.K_SUMMA,0),
		[COL14] = isnull(O1.K_SUMMA,0),
		[COL15] = isnull(O1.D_SUMMA,0),
		[COL16] = isnull(O2.K_SUMMA,0),
		[COL17] = isnull(O2.D_SUMMA,0),
		[COL18] = 0,
		[COL19] = 0,
		[COL20] = 0,
		[COL21] = 0,
		[COL22] = rtrim(SC.ACC_CODE)

	FROM (select distinct ACC_CODE, CODE from @tOborot) SC
	left join dbo.S_ACCOUNTS SA on SC.CODE = SA.cSinth + SA.cAnalit and SA.cSource = ''
	left join @tOborot O1 on O1.SOURCE = '1' and O1.ACC_CODE = SC.ACC_CODE 
	left join @tOborot O2 on O2.SOURCE <> '1' and O2.ACC_CODE = SC.ACC_CODE 
	left join @tRest R1 on R1.SOURCE = '1' and R1.ACC_CODE = SC.ACC_CODE 
	left join @tRest R2 on R2.SOURCE <> '1' and R2.ACC_CODE = SC.ACC_CODE 
	order by SC.ACC_CODE
else
	SELECT	[CODE] = rtrim(SC.ACC_CODE),
		--[CODE] = case when len(SC.ACC_CODE) > 15 then SC.ACC_CODE else '00000000000000000' + SC.ACC_CODE end,
		[COL1] = left(SC.ACC_CODE,3),
		[COL2] = substring(SC.ACC_CODE,4,10),
		[COL3] = substring(SC.ACC_CODE,14,9),
		[COL4] = case when (SC.CODE = '40101') and O1.DB_KR = 0 or 
				   (SC.CODE <> '40101' and substring(SC.ACC_CODE,19,5) <> '30404' and SA.S_PASSIVE = 1) or  
				   (SC.CODE = '30404' and isnull(R1.D_SUMMA,0) - isnull(R1.K_SUMMA,0) - isnull(O1.D_SUMMA,0) + isnull(O1.K_SUMMA,0) < 0)then 0
				else isnull(R1.D_SUMMA,0) - isnull(R1.K_SUMMA,0) - isnull(O1.D_SUMMA,0) + isnull(O1.K_SUMMA,0) end,
		[COL5] = case when (SC.CODE = '40101') and O1.DB_KR = 1 or 
				   (SC.CODE <> '40101' and substring(SC.ACC_CODE,19,5) <> '30404' and SA.S_PASSIVE = 0) or 
				   (SC.CODE = '30404' and isnull(R1.K_SUMMA,0) - isnull(R1.D_SUMMA,0) - isnull(O1.K_SUMMA,0) + isnull(O1.D_SUMMA,0) < 0) then 0
				else isnull(R1.K_SUMMA,0) - isnull(R1.D_SUMMA,0) - isnull(O1.K_SUMMA,0) + isnull(O1.D_SUMMA,0) end,
		[COL6] = case when (SC.CODE = '40101') and O2.DB_KR = 0 or 
				   (SC.CODE <> '40101' and substring(SC.ACC_CODE,19,5) <> '30404' and SA.S_PASSIVE = 1) or 
				   (SC.CODE = '30404' and isnull(R2.D_SUMMA,0) - isnull(R2.K_SUMMA,0) - isnull(O2.D_SUMMA,0) + isnull(O2.K_SUMMA,0) < 0) then 0
				else isnull(R2.D_SUMMA,0) - isnull(R2.K_SUMMA,0) - isnull(O2.D_SUMMA,0) + isnull(O2.K_SUMMA,0) end,
		[COL7] = case when (SC.CODE = '40101') and O2.DB_KR = 1 or 
				   (SC.CODE <> '40101' and substring(SC.ACC_CODE,19,5) <> '30404' and SA.S_PASSIVE = 0) or 
				   (SC.CODE = '30404' and isnull(R2.K_SUMMA,0) - isnull(R2.D_SUMMA,0) - isnull(O2.K_SUMMA,0) + isnull(O2.D_SUMMA,0) < 0) then 0
				else isnull(R2.K_SUMMA,0) - isnull(R2.D_SUMMA,0) - isnull(O2.K_SUMMA,0) + isnull(O2.D_SUMMA,0) end,
		[COL8] = isnull(O1.D_SUMMA,0),
		[COL9] = isnull(O1.K_SUMMA,0),
		[COL10] = isnull(O2.D_SUMMA,0),
		[COL11] = isnull(O2.K_SUMMA,0),
		[COL12] = isnull(O1.K_SUMMA,0),
		[COL13] = isnull(O1.D_SUMMA,0),
		[COL14] = isnull(O2.K_SUMMA,0),
		[COL15] = isnull(O2.D_SUMMA,0),
		[COL16] = 0,
		[COL17] = 0,
		[COL18] = 0,
		[COL19] = 0,
		[COL20] = rtrim(SC.ACC_CODE)

	FROM (select distinct ACC_CODE, CODE from @tOborot) SC
	left join dbo.S_ACCOUNTS SA on SC.CODE = SA.cSinth + SA.cAnalit and SA.cSource = ''
	left join @tOborot O1 on O1.SOURCE = '1' and O1.ACC_CODE = SC.ACC_CODE 
	left join @tOborot O2 on O2.SOURCE <> '1' and O2.ACC_CODE = SC.ACC_CODE 
	left join @tRest R1 on R1.SOURCE = '1' and R1.ACC_CODE = SC.ACC_CODE 
	left join @tRest R2 on R2.SOURCE <> '1' and R2.ACC_CODE = SC.ACC_CODE 
	order by SC.ACC_CODE


	


GO


GRANT EXECUTE ON dbo.[RB_CALC_72n_0503110] TO PUBLIC

GO


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


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

GO

CREATE PROCEDURE dbo.BK_EXPORT_F1152026 (@iLINK_FORM INT)
AS
BEGIN

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

	DECLARE @FNAME VARCHAR (254),
		@FNAME_ID VARCHAR (254),
-- exec BK_EXPORT_F1152026 15238

			@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),

			@LINK_COL_CODE	INT,
			@LINK_COL_SUM	INT,
			@LINK_COL_STAVKA	INT,
			@LINK_COL_LGOT	INT,
			@LINK_COL_PLACE	INT,

			--- Раздел 1 ---
			@KBK VARCHAR (30),
			@OKATO VARCHAR (15),
			@OKATO_D VARCHAR (15),
			@SUMMA	NUMERIC (15,0),

			--- Раздел 2 ---
			@ST_IMUSH	NUMERIC (15,0),
			@CODE_NL	VARCHAR (7),
			@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),

			@LINK_COL1	INT,
			@LINK_COL3	INT,
			@LINK_COL4	INT

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

	SET @cPERIOD_NUM = '34'

	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],
			@OKATO_D = CONVERT (VARCHAR (11), REPLACE (OKATO, ' ', ''))
	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 	(select *, CASE WHEN ORDERS = 1 THEN 2 WHEN ORDERS = 2 THEN 3
		WHEN ORDERS = 3 THEN 1 END AS REAL_ORD
		from report_tables
		where link_form = (select link_form
							from report_saved_forms
							where link_saved_form=@iLINK_FORM)) AS T
	WHERE REAL_ORD = 1

	SELECT @KBK = KBK,
		@OKATO = OKATO,
		@SUMMA = SUMMA - ISNULL (SUMMA1, 0),
		@C_PLACE = C_PLACE,
		@C_TYPE = C_TYPE
	FROM
	(SELECT (SELECT CONVERT (VARCHAR (20), Str_Val) FROM dbo.REPORT_STRING
				WHERE LINK_SAVED_FORM = @iLINK_FORM
				AND LINK_COL = (SELECT RC1.LINK_COL FROM dbo.REPORT_COLOUMNS RC1 WHERE RC1.LINK_TABLE = @iLINK_TABLE
									AND UPPER (RC1.[NAME]) = 'КОД БК')
				) AS KBK,
		(SELECT CONVERT (VARCHAR (20), Str_Val) FROM dbo.REPORT_STRING
					WHERE LINK_SAVED_FORM = @iLINK_FORM
					AND LINK_COL = (SELECT RC1.LINK_COL FROM dbo.REPORT_COLOUMNS RC1 WHERE RC1.LINK_TABLE = @iLINK_TABLE
										AND UPPER (RC1.[NAME]) = 'КОД ПО ОКАТО')
					) AS OKATO,
		(SELECT CONVERT (NUMERIC (15), SUMMA) FROM dbo.REPORT_SUMMA
					WHERE LINK_SAVED_FORM = @iLINK_FORM
					AND LINK_COL = (SELECT RC1.LINK_COL FROM dbo.REPORT_COLOUMNS RC1 WHERE RC1.LINK_TABLE = @iLINK_TABLE
										AND UPPER (RC1.[NAME]) = 'ПОДЛЕЖИТ УПЛАТЕ')
					) AS SUMMA,
		(SELECT CONVERT (NUMERIC (15), SUMMA) FROM dbo.REPORT_SUMMA
					WHERE LINK_SAVED_FORM = @iLINK_FORM
					AND LINK_COL = (SELECT RC1.LINK_COL FROM dbo.REPORT_COLOUMNS RC1 WHERE RC1.LINK_TABLE = @iLINK_TABLE
										AND UPPER (RC1.[NAME]) = 'К УМЕНЬШЕНИЮ')
					) AS SUMMA1,
		(SELECT CONVERT (VARCHAR (3), Str_Val) FROM dbo.REPORT_STRING
					WHERE LINK_SAVED_FORM = @iLINK_FORM
					AND LINK_COL = (SELECT RC1.LINK_COL FROM dbo.REPORT_COLOUMNS RC1 WHERE RC1.LINK_TABLE = @iLINK_TABLE
										AND UPPER (RC1.[NAME]) = 'КОД ПО МЕСТУ НАХОЖДЕНИЯ (УЧЕТА)')
					) AS C_PLACE,
		(SELECT CONVERT (VARCHAR (1), Str_Val) FROM dbo.REPORT_STRING
					WHERE LINK_SAVED_FORM = @iLINK_FORM
					AND LINK_COL = (SELECT RC1.LINK_COL FROM dbo.REPORT_COLOUMNS RC1 WHERE RC1.LINK_TABLE = @iLINK_TABLE
										AND UPPER (RC1.[NAME]) = 'КОД ВИДА ИМУЩЕСТВА')
					) AS C_TYPE
	FROM dbo.REPORT_ROWS RR
	WHERE RR.LINK_TABLE = @iLINK_TABLE) AS T

/*SELECT * FROM dbo.REPORT_ROWS RR where RR.LINK_TABLE = @iLINK_TABLE

SELECT * FROM dbo.REPORT_STRING
WHERE LINK_SAVED_FORM = @iLINK_FORM

SELECT * FROM dbo.REPORT_SUMMA 
WHERE LINK_SAVED_FORM = @iLINK_FORM
*/
--SELECT @KBK, @OKATO, @SUMMA, @C_PLACE, @C_TYPE

	-- ДАННЫЕ РАЗДЕЛА 2 --
	-- !!!Расчет!!! --
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM 	(select *, CASE WHEN ORDERS = 1 THEN 2 WHEN ORDERS = 2 THEN 3
		WHEN ORDERS = 3 THEN 1 END AS REAL_ORD
		from report_tables
		where link_form = (select link_form
							from report_saved_forms
							where link_saved_form=@iLINK_FORM)) AS T
	WHERE REAL_ORD = 3

	SELECT @LINK_COL_CODE = RC1.LINK_COL
	FROM dbo.REPORT_COLOUMNS RC1
	WHERE RC1.LINK_TABLE = @iLINK_TABLE
		AND UPPER (RC1.[NAME]) = 'КОД СТРОКИ' 

	SELECT @LINK_COL_SUM = RC1.LINK_COL
	FROM dbo.REPORT_COLOUMNS RC1
	WHERE RC1.LINK_TABLE = @iLINK_TABLE
		AND UPPER (RC1.[NAME]) = 'ЗНАЧЕНИЕ ПОКАЗАТЕЛЕЙ' 

	SELECT @LINK_COL_STAVKA = RC1.LINK_COL
	FROM dbo.REPORT_COLOUMNS RC1
	WHERE RC1.LINK_TABLE = @iLINK_TABLE
		AND UPPER (RC1.[NAME]) = 'НАЛОГОВАЯ СТАВКА(%)' 

	SELECT @LINK_COL_LGOT = RC1.LINK_COL
	FROM dbo.REPORT_COLOUMNS RC1
	WHERE RC1.LINK_TABLE = @iLINK_TABLE
		AND UPPER (RC1.[NAME]) = 'КОД ЛЬГОТЫ/КОД ОКАТО' 

--	SELECT @KBK = KBK, @OKATO = OKATO, @SUMMA = SUMMA
	
	SELECT @ST_IMUSH = CONVERT (NUMERIC (15), SUMMA) FROM dbo.REPORT_SUMMA
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_SUM
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '150')

	SELECT @CODE_NL = CONVERT (VARCHAR (7), Str_Val) FROM dbo.REPORT_STRING
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_LGOT
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '160')

	SELECT @ST_IMUSH_NO = CONVERT (NUMERIC (15), SUMMA) FROM dbo.REPORT_SUMMA
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_SUM
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '170')

	SELECT @Dol_ST = CONVERT (VARCHAR (21), Str_Val) FROM dbo.REPORT_STRING
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_LGOT
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '180')

	SELECT @NAL_BASE = CONVERT (NUMERIC (15), SUMMA) FROM dbo.REPORT_SUMMA
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_SUM
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '190')

	SELECT @CODE_LG_PNS = CONVERT (VARCHAR (7), Str_Val) FROM dbo.REPORT_STRING
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_LGOT
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '200')

	SELECT @NAL_STAV = CONVERT (NUMERIC (3,2), SUMMA) FROM dbo.REPORT_SUMMA
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_STAVKA
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '210')

	SELECT @SUM_NAL_PER = CONVERT (NUMERIC (15), SUMMA) FROM dbo.REPORT_SUMMA
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_SUM
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '220')

	SELECT @SumAV = CONVERT (NUMERIC (15,0), SUMMA) FROM dbo.REPORT_SUMMA
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_SUM
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '230')

	SELECT @CODE_LG_UM = CONVERT (VARCHAR (7), Str_Val) FROM dbo.REPORT_STRING
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_LGOT
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '240')

	SELECT @SUM_LG_UM = CONVERT (NUMERIC (15,0), SUMMA) FROM dbo.REPORT_SUMMA
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_SUM
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '250')

	--- Остаточная стоимость имущества по месяцам ---
	DECLARE @TABLE_R21 TABLE (COL1 VARCHAR (6), CODE VARCHAR (3),
				SUM_ALL NUMERIC (15,0), SUM_LG NUMERIC (15,0))

	SELECT @iLINK_TABLE = LINK_TABLE
	FROM 	(select *, CASE WHEN ORDERS = 1 THEN 2 WHEN ORDERS = 2 THEN 3
		WHEN ORDERS = 3 THEN 1 END AS REAL_ORD
		from report_tables
		where link_form = (select link_form
							from report_saved_forms
							where link_saved_form=@iLINK_FORM)) AS T
	WHERE REAL_ORD = 2

	SELECT @LINK_COL1 = RC1.LINK_COL
	FROM dbo.REPORT_COLOUMNS RC1
	WHERE RC1.LINK_TABLE = @iLINK_TABLE
		AND UPPER (RC1.[NAME]) = 'ПО СОСТОЯНИЮ НА' 

	SELECT @LINK_COL_CODE = RC1.LINK_COL
	FROM dbo.REPORT_COLOUMNS RC1
	WHERE RC1.LINK_TABLE = @iLINK_TABLE
		AND UPPER (RC1.[NAME]) = 'КОД СТРОКИ' 

	SELECT @LINK_COL3 = RC1.LINK_COL
	FROM dbo.REPORT_COLOUMNS RC1
	WHERE RC1.LINK_TABLE = @iLINK_TABLE
		AND UPPER (RC1.[NAME]) = 'ВСЕГО' 

	SELECT @LINK_COL4 = RC1.LINK_COL
	FROM dbo.REPORT_COLOUMNS RC1
	WHERE RC1.LINK_TABLE = @iLINK_TABLE
		AND UPPER (RC1.[NAME]) = 'В Т.Ч. СТОИМОСТЬ ЛЬГОТИРУЕМОГО ИМУЩЕСТВА' 

	INSERT INTO @TABLE_R21
	SELECT (SELECT CONVERT (VARCHAR (6), FORMULA)
					FROM dbo.REPORT_FORMULA RS
					WHERE RS.LINK_COL = @LINK_COL1
						AND RS.LINK_ROW = RF.LINK_ROW) AS COL1,
			CONVERT (VARCHAR (3), RF.FORMULA) AS CODE,
			(SELECT CONVERT (NUMERIC (15), SUMMA)
					FROM dbo.REPORT_SUMMA RS
					WHERE RS.LINK_SAVED_FORM = @iLINK_FORM
						AND RS.LINK_COL = @LINK_COL3
						AND RS.LINK_ROW = RF.LINK_ROW) AS SUM_ALL,
			(SELECT CONVERT (NUMERIC (15), SUMMA)
					FROM dbo.REPORT_SUMMA RS
					WHERE RS.LINK_SAVED_FORM = @iLINK_FORM
						AND RS.LINK_COL = @LINK_COL4
						AND RS.LINK_ROW = RF.LINK_ROW) AS SUM_LG
	FROM dbo.REPORT_FORMULA RF
	WHERE RF.LINK_COL = @LINK_COL_CODE

-- SELECT * FROM @TABLE_R21
--SELECT @ST_IMUSH, @CODE_NL, @ST_IMUSH_NO, @Dol_ST, @CODE_LG_PNS, @NAL_STAV 
-- BK_EXPORT_F1152028  12533
--	FROM dbo.REPORT_ROWS RR
--	WHERE RR.LINK_TABLE = @iLINK_TABLE) AS T

--	select @iLINK_TABLE, @LINK_COL_CODE, @LINK_COL_SUM, @LINK_COL_STAVKA, @LINK_COL_LGOT	

	--- Формирование 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'
-- SELECT @FNAME 
	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.01">')

-- Документ
	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, 'НомКорр="0"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ПоМесту="' + ISNULL (@C_PLACE, '') + '">')

-- exec BK_EXPORT_F1152026 11433

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

	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 (@OKATO, '') = ''
											THEN ISNULL (@OKATO_D, '')
											ELSE @OKATO 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, '<СтоимМес>')
/*
SELECT SUM_ALL,
	CASE WHEN ISNULL (SUM_ALL, 0) = 0 THEN ''
		ELSE STR (SUM_ALL, 0) -- ' СтОст="' + LTRIM (STR (SUM_ALL, 0)) +'"'
	END
FROM @TABLE_R21
*/
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) 
	SELECT @FNAME,
		'<ОстСтом' + REPLACE (RTRIM (COL1), '.', '')
				+ CASE WHEN ISNULL (SUM_ALL, 0) = 0 THEN ''
						ELSE ' СтОст="' + LTRIM (STR (SUM_ALL)) +'"'
					END
				+ CASE WHEN ISNULL (SUM_LG, 0) = 0 THEN ''
						ELSE ' СтЛьгИмущ="' + LTRIM (STR (SUM_LG)) +'"'
					END
				+ '/>'
	FROM @TABLE_R21

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СтоимМес>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ДанРас>')
--SELECT @ST_IMUSH, @CODE_NL, @ST_IMUSH_NO, @Dol_ST, @CODE_LG_PNS, @NAL_STAV 
--                         НалБаза

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

	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, '</ИмущНД>')

	
	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 #TASK_PROP
END 

GO


GRANT EXECUTE ON dbo.[BK_EXPORT_F1152026] TO PUBLIC

GO


GO

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

GO


create    procedure dbo.BB_GZ_REESTR_REPORT_OKPD @iLSF int 

as

declare @dDateBeg	datetime,
		@cDepCode	varchar(20),
		@iDepLink int, 
		@dDateEnd datetime


select @iDepLink = Link_Organization, 
		@dDateEnd    = Begin_Date + 1, 
		@dDateBeg  = dbo.DateBeginOfYear(Begin_Date)
from dbo.REPORT_SAVED_FORMS
where Link_Saved_Form = @iLSF


select @cDepCode = isnull(rtrim(ltrim(BUDG)),'')
from dbo.DEPARTMENTS 
where LINK = @iDepLink 

--set @dDateBeg = dbo.DateBeginOfYear(@dDateEnd)
declare @cTableReestr table (	LINK_GC		int,
			 	LINK_OKPD	int,
			 	TYPE		tinyint,
				QUANTITY	numeric(19,4),
				--COST		numeric(19,4),
				SUMMA		numeric(19,4))

declare @cTemp table(LINK_OKPD	int,
			NAME_DOC	varchar(100),
			LINK_DEP	INT,
			NUMBER		varchar(30),
			[DATE]		datetime,
			COMMENT		varchar(1000),		
			C_TYPE		int,
			CON_END		datetime,
			C_QUANTITY	numeric(19,4),
			C_COST		numeric(19,4),
			C_SUMMA		numeric(19,4),
			GZ_QUANTITY	numeric(19,4),
			GZ_COST		numeric(19,4),
			GZ_SUMMA	numeric(19,4),
			OPL_SUMMA	numeric(19,4),
			OPL_SUMMA_B	numeric(19,4),
			OPL_SUMMA_V	numeric(19,4))

declare @cTemp1 table(LINK_GC	int,  
						LINK_OKPD	int,  
						NAME_DOC	varchar(100), 
						LINK_DEP	int, 
						NUMBER	varchar(30), 
						[DATE]	datetime,
						COMMENT	varchar(1000), 
						C_TYPE	int, 
						CON_DATE	datetime,
						[TYPE]	int, 
						QUANTITY numeric(19,4),
						COST numeric(19,4), 
						SUMMA numeric(19,4))
			



-- Выбираем строки реестра госзакупок
insert into @cTableReestr(LINK_GC, LINK_OKPD, QUANTITY,/* COST, */SUMMA, TYPE)
select GR.LINK_CONTRACT, OKPD.LINK, SUM(GRT.QUANTITY * N.COEFF)/*, (case when N.COEFF = 0 then 0 else GRT.COST / N.COEFF end)*/, SUM(GRT.SUMMA) / 1000, GRT.TYPE
from dbo.G_PROV G
inner join dbo.GZ_REESTR GR on GR.LINK = G.LINK
inner join dbo.GZ_REESTR_DOP GRT on GRT.LINK_UP = G.LINK
inner join dbo.NOMENCLATURE N on GRT.NOMENCLATURE = N.LINK 
inner join dbo.OKPD OKPD on N.LINK_OKPD = OKPD.LINK --and not exists (select * from OKPD OKPD1 where OKPD1.LINK_SELF = OKPD.LINK)
where  G.DATE_PROV is not NULL and 
	G.DATE_PROV between @dDateBeg and @dDateEnd and 
	G.DEP = @iDepLink
group by GR.LINK_CONTRACT, OKPD.LINK, GRT.TYPE --, case when N.COEFF = 0 then 0 else GRT.COST / N.COEFF end

--select * from @cTableReestr

insert into @cTemp1
select distinct LINK_GC 	= G.LINK, 
		     LINK_OKPD	= CT.OKPD,  
		     NAME_DOC	= case when CH.GZ_LINK is not null or (rtrim(CH.GZ_NUM) <> '' or CH.GZ_DATE is not null) then 'Госконтракт' else /*rtrim(SO.NAME)*/'Договор' end, 
		     LINK_DEP	= CH.DEP_LINK_P, 
		     NUMBER	= case when CH.GZ_LINK is not null then GZ.NUMBER else case when rtrim(CH.GZ_NUM) <> '' or CH.GZ_DATE is not null then CH.GZ_NUM else case when CH.DOG_LINK is not null then GPD.NUMBER else G.NUMBER end end end, 
		     DATE	= case when CH.GZ_LINK is not null then GZ.DATE else case when rtrim(CH.GZ_NUM) <> ''  or CH.GZ_DATE is not null then CH.GZ_DATE else case when CH.DOG_LINK is not null then GPD.DATE else G.DATE end end end,
		     COMMENT	= case when CH.GZ_LINK is not null and GZ.COMMENT <> '' then GZ.COMMENT else CH.MAINTENANCE end, 
		     C_TYPE	= CH.TYPE, 
		     CON_DATE	= DATE_END,
		     TYPE	= 3, 
		     CT.QUANTITY, 
		     CT.COST, 
		     SUMMA      = CT.SUMMA / 1000
		from dbo.G_PROV G
		inner join dbo.FINANSE_CONTRACT_HEAD CH on CH.Link_G_Prov = G.LINK and CH.GZ = 1 and
							   (CH.DATE_BEGIN between @dDateBeg and @dDateEnd or
								CH.DATE_END between @dDateBeg and @dDateEnd or
								@dDateBeg between CH.DATE_BEGIN and CH.DATE_END or
								@dDateEnd between CH.DATE_BEGIN and CH.DATE_END)
		inner join (	select LINK_UP, OKPD, sum(SUMMA) as SUMMA, sum(QUANTITY) as QUANTITY, case sum(QUANTITY) when 0 then 0 else sum(SUMMA)/sum(QUANTITY) end  as cost
				from dbo.FINANSE_CONTRACT 
				group by LINK_UP, OKPD) CT on CT.LINK_UP = G.LINK
		left  join dbo.G_PROV GZ on GZ.LINK = CH.GZ_LINK
		left  join dbo.S_OBJECTS SO on isnull(GZ.OBJECT, G.OBJECT) = SO.LINK
		left  join dbo.G_PROV GPD on GPD.LINK = CH.DOG_LINK
		where G.DEP = @iDepLink and G.DATE_PROV is not null  
		union all
		select LINK_GC 	= G.LINK, 
		     LINK_OKPD	= NULL,  
		     NAME_DOC	= rtrim(DT.NAME), 
		     LINK_DEP	= CH.DEP_LINK_P, 
		     NUMBER	= G.NUMBER, 
		     DATE	= G.DATE, 
		     COMMENT	= G.COMMENT, 
		     C_TYPE	= CH.TYPE, 
		     CON_DATE	= NULL, 
		     TYPE	= 4, 
		     QUANTITY	= 0, 
		     COST	= 0, 
		     SUMMA	= G.SUMMA / 1000
		from dbo.G_PROV G
		inner join dbo.GZ_NOT_CONTRACT_HEAD CH on CH.LINK = G.LINK
		inner join dbo.BB_NOT_CONTRACT_DOC_TYPE DT on DT.LINK = CH.TYPE_DOC 
		where G.DEP = @iDepLink and 
 			G.[DATE] between @dDateBeg and @dDateEnd and
			G.LINK in (select LINK_GC from @cTableReestr)

insert into  @cTemp(NAME_DOC, LINK_DEP, NUMBER, [DATE], CON_END, COMMENT, C_TYPE, LINK_OKPD, 
			C_QUANTITY, C_COST, C_SUMMA, GZ_QUANTITY, GZ_COST, GZ_SUMMA, OPL_SUMMA, OPL_SUMMA_B, OPL_SUMMA_V)

select distinct TC.NAME_DOC, TC.LINK_DEP, TC.NUMBER, TC.DATE, TC.CON_DATE,  TC.COMMENT, TC.C_TYPE, 
	LINK_OKPD	= O.LINK,  
	C_QUANTITY	= isnull(case TC.TYPE when 4 then TR.QUANTITY else TC.QUANTITY end,0),
	C_COST		= isnull(case TC.TYPE when 4 then TR.COST else TC.COST end,0),
	C_SUMMA		= isnull(case TC.TYPE when 4 then TR.SUMMA else TC.SUMMA end,0),
	GZ_QUANTITY 	= isnull(TR.QUANTITY,0), 
	GZ_COST		= isnull(TR.COST,0), 
	GZ_SUMMA	= isnull(TR.SUMMA,0),
	OPL_SUMMA	= isnull(TR.SUMMA1,0),
	OPL_SUMMA_B	= isnull(TR.SUMMA1,0),
	OPL_SUMMA_V	= 0
from @cTemp1 TC
full outer join (select LINK_GC = isnull(TR2.LINK_GC,TR1.LINK_GC),
			LINK_OKPD = isnull(TR2.LINK_OKPD,TR1.LINK_OKPD),
			TR2.QUANTITY, 
		     	COST = case TR2.QUANTITY when 0 then 0 else TR2.SUMMA/TR2.QUANTITY * 1000 end, 
		     	TR2.SUMMA, 
		     	SUMMA1 = TR1.SUMMA 
		 from @cTableReestr TR2 
		 full outer join @cTableReestr TR1 on TR1.LINK_GC = TR2.LINK_GC and TR2.LINK_OKPD = TR1.LINK_OKPD
		 where TR2.TYPE = 2 and TR1.TYPE = 1
		 
		 ) TR 
	on TR.LINK_GC = TC.LINK_GC and (TC.LINK_OKPD = TR.LINK_OKPD or TC.TYPE = 4) 
inner join dbo.OKPD O on O.LINK = ISNULL(TC.LINK_OKPD, TR.LINK_OKPD) --and not exists (select * from OKPD OKPD1 where OKPD1.LINK_SELF = O.LINK)


select 	CODE/*OKPD_CODE*/	= cast(rtrim(cast(O.CODE as char(10))) + '$' + isnull(@cDepCode,'') + '$' + isnull(rtrim(T.NAME_DOC),'') + '$' + isnull(ltrim(rtrim(T.[NUMBER])),'') + '$' + isnull(ltrim(rtrim(ISNULL(CONVERT(VARCHAR(30),T.[DATE],104),''))) ,'') as varchar(50)),
	---CODE/*OKPD_CODE*/	= O.CODE, 
	COL1/*OKPD_CODE*/	= rtrim(O.CODE), 
	COL2/*DOC_NAME*/ 	= rtrim(isnull(cast(T.NAME_DOC + ' № '  + rtrim(T.[NUMBER]) + ' от ' + ISNULL(CONVERT(VARCHAR(30),T.[DATE],104),'') as varchar(254)),'')),
	COL3/*DOC_COMMENT*/	= rtrim(isnull(replace(T.COMMENT,'
',' '),'')),
	COL4/*CON_TYPE_NAME*/	= rtrim(isnull(cast(ZT.NAME as char(100)),'')),
	COL5/*OKPD_NAME*/	= rtrim(O.NAME),
	COL6/*DEP_NAME*/	= cast(isnull(rtrim(D.NAME) + case when D.INN = '' then '' else ' ИНН ' + RTRIM(D.INN) + CASE WHEN D.INN_DOP = '' THEN '' ELSE '/' + D.INN_DOP END end + ' ' + rtrim(isnull(dbo.GetAddressByKladr(D.KLADR_LINK),'')) + CASE when D.HOUSE is null or D.HOUSE = '' then '' else  ' ,' + D.HOUSE end,'') as varchar(250)),
	COL7/*OKPD_UM*/		= isnull(UM.NAME,''),
	COL8/*C_QUANTITY*/	= case when UM.NAME like '%руб%' then 0 else C_QUANTITY end,
	COL9/*GZ_QUANTITY*/	= case when UM.NAME like '%руб%' then 0 else GZ_QUANTITY end,
	COL10/*C_COST*/		= case when UM.NAME like '%руб%' then 0 else C_COST end,
	COL11/*GZ_COST*/	= case when UM.NAME like '%руб%' then 0 else GZ_COST end,
	COL12/*C_SUMMA*/	= C_SUMMA,
	COL13/*GZ_SUMMA*/	= GZ_SUMMA,
	COL14/*OPL_SUMMA*/	= OPL_SUMMA,
	COL15/*OPL_SUMMA_B*/	= OPL_SUMMA,
	COL16/*OPL_SUMMA_V*/	= 0,
	COL17/*CON_END*/	= ISNULL(CONVERT(VARCHAR(30),T.[CON_END],104),''),
	COL18/*OPL_SUMMA_V*/	= case when C_SUMMA = GZ_SUMMA and C_SUMMA = OPL_SUMMA then 'выполнен' else '' end,
	COL19/*CON_END*/	= ISNULL(case D.DEP_TYPE2 when 1 then 'МП' else '' end ,''),
	COL20/*OKPD_CODE*/	= cast(rtrim(cast(O.CODE as char(10))) + '$' + isnull(@cDepCode,'') + '$' + isnull(rtrim(T.NAME_DOC),'') + '$' + isnull(ltrim(rtrim(T.[NUMBER])),'') + '$' + isnull(ltrim(rtrim(ISNULL(CONVERT(VARCHAR(30),T.[DATE],104),''))) ,'') as varchar(50)),
	COL21/*CON_NUM*/	= '',
	COL22/*CON_DATE*/	= '20060101',
	COL23/*NAME_DOC*/	= rtrim(T.[NAME_DOC]),
	COL24/*DOC_NUM*/	= rtrim(T.[NUMBER]),
	COL25/*DOC_DATE*/	= ISNULL(CONVERT(VARCHAR(30),T.[DATE],104),''),
	COL26/*PDEP_NAME*/	= cast(isnull(rtrim(D.NAME),'') as varchar(250)),
	COL27/*PDEP_ADR*/	= isnull(rtrim(cast(dbo.GetAddressByKladr(D.KLADR_LINK) + CASE when D.HOUSE is null or D.HOUSE = '' then '' else ' ,' + D.HOUSE end   as varchar(250))),''),
	COL28/*PDEP_ADR*/	= @cDepCode
/*	OKPD_CODE1		= case LEVEL_OKPD when 2 then O.CODE else '' end,
	OKPD_CODE2		= case LEVEL_OKPD when 3 then O.CODE  else '' end,
	OKPD_CODE3		= case LEVEL_OKPD when 4 then O.CODE  else '' end,
	OKPD_CODE4		= case LEVEL_OKPD when 5 then O.CODE  else '' end,
	OKPD_CODE5		= case LEVEL_OKPD when 6 then O.CODE  else '' end*/

		

from @cTemp T
inner join dbo.OKPD O on O.LINK = T.LINK_OKPD
left join dbo.DICTIONARY_DIGIT UM on O.UM = UM.LINK 
left join dbo.FB_GZ_TYPE ZT on T.C_TYPE = ZT.TYPE
left join dbo.DEPARTMENTS D on T.LINK_DEP = D.LINK 
order by CODE


GO


grant all on BB_GZ_REESTR_REPORT_OKPD to public
GO
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.[RN_PRINT_RSV1_2015]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RN_PRINT_RSV1_2015]

GO

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

CREATE PROCEDURE dbo.[RN_PRINT_RSV1_2015]
	@namesTables varchar(8000),        -- имена глобальных временных таблиц через запятую, где хранятся таблицы
									-- нужно самим сделать select, первый select отностится к c_data2
									-- после работы, нужно удалить!
	@LSF int
AS
/*
*/

	create table #all (COL1 varchar(8000), COL2 varchar(8000), COL3 float, COL4 float, COL5 float, COL6 varchar(8000),  CODE varchar(50), DEL bit, ITOG int, orders int IDENTITY(1,1))
	declare @table varchar(100), @RunStr varchar(8000),@table1 varchar(100),@table2 varchar(100),@table3 varchar(100) ,@table4 varchar(100),@table5 varchar(100),@table6 varchar(100), 
	@table7 varchar(100),@table8 varchar(100),@table9 varchar(100) ,@table10 varchar(100),@table11 varchar(100),@table12 varchar(100), 
	@table13 varchar(100),@table14 varchar(100),@table15 varchar(100) ,@table16 varchar(100),@table17 varchar(100),@table18 varchar(100), 
	@table19 varchar(100),@table20 varchar(100),@table21 varchar(100) 


	
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table1 output, ','



	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table2 output, ','


	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table3 output, ','
	--set @RunStr = 'DELETE A 
	--               FROM  ' + @table3 +' A 
	--               WHERE EXISTS(SELECT * FROM '+@table3 +' B WHERE SUBSTRING(A.CODE,18,9) = SUBSTRING(B.CODE,18,9) AND SUBSTRING(B.CODE,1,17) <> ''00000000000000000'')  
	--               AND SUBSTRING(A.CODE,1,17) = ''00000000000000000'''  
 --  PRINT @RunStr
	--execute(@RunStr)

--	set @RunStr = 'SELECT * FROM ' + @table3 
--	execute(@RunStr)

--	set @RunStr = 'drop table ' + @table3
--	execute(@RunStr)

	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table4 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table5 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table6 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table7 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table8 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table9 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table10 output, ','
	--exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table11 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table12 output, ','
	--exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table13 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table14 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table15 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table16 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table17 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table18 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table19 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table20 output, ','
	exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table21 output, ','

set @RunStr = 'SELECT * FROM ' + @table1 +' ' 
execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table2 +' ' 
execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table3 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT * FROM ' + @table4 +' ' 
execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table5 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT * FROM ' + @table6 +' ' 
execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table7 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT * FROM ' + @table8 +' ' 
execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table9 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT * FROM ' + @table10 +' ' 
execute(@RunStr)

--set @RunStr = 'SELECT * FROM ' + @table11 +' ' 
--execute(@RunStr)


set @RunStr = 'SELECT * FROM ' + @table12 +' ' 
execute(@RunStr)
--set @RunStr = 'SELECT * FROM ' + @table13 +' ' 
--execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table14 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT * FROM ' + @table15 +' ' 
execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table16 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT * FROM ' + @table17 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT * FROM ' + @table18 +' ' 
execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table19 +' ' 
execute(@RunStr)
set @RunStr = 'SELECT UPD,del,link_saved_form,link_row,orders,Calc_orders,Print_Null,
				code,col1,col2,col3,col4,col5,col6,col7,col8,col9,
				col10 = (SELECT TOP 1 CASE WHEN LEN(''''+ col10 + '','' + col11+ '','' +col12+ '','' +col13+ '','' +col14+ '','' +col15+ '','' +col16+ '',''+col17+'','') >10 
													THEN ''''+ col10 + '','' + col11+ '','' +col12+ '','' +col13+ '','' +col14+ '','' +col15+ '','' +col16+ '',''+col17+'',''
													ELSE '' '' END FROM ' + @table20 +'  where COL7 = a.COL7 and COL3=''700'')  ,
				col18 = (SELECT TOP 1 CASE WHEN LEN( ''''+ col18+ '','' +col19+ '','' +col20+ '','' +col21+ '','' +col22+ '','' +col23+ '','' +col24+ '','' +col25+'','' ) >10 
													THEN ''''+ col18+ '','' +col19+ '','' +col20+ '','' +col21+ '','' +col22+ '','' +col23+ '','' +col24+ '','' +col25+'','' 
													ELSE '' '' END FROM ' + @table20 +'  where COL7 = a.COL7 and COL3=''700''),
				col26 = (SELECT TOP 1 CASE WHEN LEN(''''+col26+ '','' +col27+ '','' +col28+ '','' +col29+ '','' +col30+ '','' +col31+ '','' +col32+ '','' +col33+'','') >10 
													THEN ''''+col26+ '','' +col27+ '','' +col28+ '','' +col29+ '','' +col30+ '','' +col31+ '','' +col32+ '','' +col33+'',''					
													ELSE '' '' END  FROM ' + @table20 +'  where COL7 = a.COL7 and COL3=''700''),
				col34 = (SELECT TOP 1 CASE WHEN LEN(''''+col34+ '','' +col35+ '','' +col36+ '','' +col37+ '','' +col38+ '','' +col39+ '','' +col40+ '','' +col41+'','') >10 
													THEN ''''+col34+ '','' +col35+ '','' +col36+ '','' +col37+ '','' +col38+ '','' +col39+ '','' +col40+ '','' +col41+'',''
													ELSE '' '' END FROM ' + @table20 +'  where COL7 = a.COL7 and COL3=''700''),
				col42,col43,col44,
				col45 = (SELECT TOP 1 CASE WHEN LEN(''''+col45+ '''') >10 
													THEN ''''+col45+ ''''	ELSE '' '' END FROM ' + @table20 +'  where COL7 = a.COL7 and COL3=''700''),
				col46 = (SELECT TOP 1 CASE WHEN LEN(''''+col46+ '''') >10 
													THEN ''''+col46+ ''''	ELSE '' '' END FROM ' + @table20 +'  where COL7 = a.COL7 and COL3=''700'')								
				
               FROM ' + @table20 +' a ' 

execute(@RunStr)

set @RunStr = 'SELECT * FROM ' + @table21 +' ' 
execute(@RunStr)


/*exec dbo.RO_FORMULA_FUNCTIONS 1, @namesTables output, @table output, ','
set @RunStr = 'SELECT * FROM ' + @table 
PRINT @RunStr
execute(@RunStr)

set @RunStr = 'drop table ' + @table
execute(@RunStr)
*/


GO


GRANT EXECUTE ON dbo.[RN_PRINT_RSV1_2015] TO PUBLIC

GO



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

GO
CREATE PROCEDURE dbo.BK_EXPORT_F1152026_502 (@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 (30),
		@OKATO VARCHAR (15),
		@OKATO_D 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),

		@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],
			@OKATO_D = CONVERT (VARCHAR (11), REPLACE (OKATO, ' ', ''))
	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 = 3)
	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, ''),
		@OKATO = 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 --
	-- Данные раздела 1.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_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 = 2)
	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 @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'

	--- Формирование 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.02">')

-- Документ

	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 (@OKATO, '') = ''
											THEN ISNULL (@OKATO_D, '')
											ELSE @OKATO 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, '</СтоимМес>')

	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, '</РасОбДеятРФ>')

	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 #TASK_PROP
END 




GO


GRANT EXECUTE ON dbo.[BK_EXPORT_F1152026_502] TO PUBLIC

GO



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

GO

CREATE  PROCEDURE [dbo].[SA_CREATE_PROV_O] @nMONTH INT, @nYear INT, @LINK_DEP INT
/*
Процедура формирует проводки по отчислениям
EXEC dbo.[SA_CREATE_PROV_O] @nMONTH = 1, @nYear = 2016, @LINK_DEP = 74578
*/
AS BEGIN

SET NOCOUNT OFF

DECLARE @LINK_DOC_SAL as INT,
	@NUM_DOC_SAL as VARCHAR(25),
	@DATE_DOC_SAL as datetime,
	@SUM_DOC_SAL as NUMERIC(18,2),
	@ACC_CODE VARCHAR(30),
	@KD_FULL_CODE_ACC VARCHAR(13)

DECLARE @varKStrancount int, @varKSERROR as INT

DECLARE @LinkEKR213 int, @LINK_EKR212 INT, @SALARY_PROV_OPT4 TINYINT, @LinkEKR211 int, @LinkEKR_R211 int

SELECT @LinkEKR211 = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '211'
SELECT @LinkEKR213 = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = '213'
SET @LINK_EKR212 = (SELECT TOP 1 LINK FROM DBO.KOSGU WHERE CODE = '212')
SELECT @LinkEKR_R211 = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = 'R211'

SET @SALARY_PROV_OPT4 = dbo.sa_get_option_by_code('SALARY_PROV_OPT4')

DECLARE @SALARY_OPTIONS_OPT14 VARCHAR(254)
SET @SALARY_OPTIONS_OPT14 = ISNULL(
									(SELECT TOP 1 VALUE
										FROM dbo.S_OPTIONS WHERE OBJECT = 	
										(SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = RTRIM(LTRIM('SALARY_OPTIONS_OPT14'))) 
									AND SID IS NULL)
								,'')	

DECLARE @SALARY_OPTIONS_OPT5 VARCHAR(254)
SET @SALARY_OPTIONS_OPT5 = ISNULL(
									(SELECT TOP 1 VALUE
										FROM dbo.S_OPTIONS WHERE OBJECT = 	
										(SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = RTRIM(LTRIM('SALARY_OPTIONS_OPT5'))) 
									AND SID IS NULL)
								,'')

IF 
ISNULL((SELECT TOP 1 RESERV FROM dbo.MINROT WHERE PERIOD<=dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@nMONTH,@nYear)) ORDER BY PERIOD DESC),0) > 0
AND
REPLACE(LTRIM(RTRIM(ISNULL(@SALARY_OPTIONS_OPT14,''))),'.','') = '' 
BEGIN

	INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
	select 'Не сформированы проводки для отчислений',
		'Не указан счет ДТ для формирования проводок по начисленю страховых взносов за счет резерва (401.60)',
		'Укажите в меню навигатора \НАСТРОЙКИ\Настройки всех режимов задачи; Далее: Настройки счетов для проводок по зарплате\Счет ДТ для формирования проводок по начисленю страховых взносов за счет резерва счет (401.60).',
		'SALARY'
	Return 0

END	


DECLARE @Cur CURSOR, @SRC VARCHAR(30), @LINK_EKR INT, @SUM_PROV numeric(18,2), @order int, @Account1 INT, @Account2 INT,	
	@HOZ_OPER int, @P1 float, @P2 float, @SGU INT, 	@OSNOVANIE VARCHAR(254), @KD_CODE_ACC VARCHAR(6),
	@LINK_PAYS int, @CODE_PAYS VARCHAR(10), @LINK_KBK int, @LINK_KAU int, @LINK_DOP_KL int, @USER_ACC varchar(4), @CODE_SFIN VARCHAR(30), @Fin_Source CHAR(1) ,
	@LINK_ORG INT, @LINK_ORG_ACC INT, @LINK_ORG_DOH INT

Set @order = 0

--SELECT TOP 1 @SRC = RTRIM(LTRIM(VALUE)) FROM dbo.S_OPTIONS WHERE OBJECT = (SELECT LINK FROM S_OBJECTS WHERE CODE = RTRIM(LTRIM('SALARY_OPTIONS_OPT5'))) AND SID IS NULL
---

SET @Cur = CURSOR FORWARD_ONLY
FOR 
-- Данные для проводок
SELECT 	[DATE] = dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@nMONTH,@nYear)),
	CASE WHEN @SALARY_PROV_OPT4 = 0 THEN 
			CASE WHEN (CASE WHEN ISNULL(JC.link_ekr,@LinkEKR213) = @LinkEKR_R211 THEN @LinkEKR211 ELSE ISNULL(JC.link_ekr,@LinkEKR213) END) = @LinkEKR211 THEN @LinkEKR213 ELSE (CASE WHEN ISNULL(JC.link_ekr,@LinkEKR213) = @LinkEKR_R211 THEN @LinkEKR211 ELSE ISNULL(JC.link_ekr,@LinkEKR213) END) END
		ELSE 
			CASE WHEN (CASE WHEN ISNULL(JC.link_ekr,@LinkEKR213) = @LinkEKR_R211 THEN @LinkEKR211 ELSE ISNULL(JC.link_ekr,@LinkEKR213) END) IN (@LinkEKR211, @LINK_EKR212) THEN @LinkEKR213 ELSE (CASE WHEN ISNULL(JC.link_ekr,@LinkEKR213) = @LinkEKR_R211 THEN @LinkEKR211 ELSE ISNULL(JC.link_ekr,@LinkEKR213) END) END
	END, 
	LINK_PAYS = JC.LINK_PAYS,
	CODE_PAYS = P.CODE,
	OSNOVANIE = RTRIM(P.[NAME]), 
	LINK_KBK = F.KBK,
	LINK_KAU = ISNULL(F.KAU,P.LINK_KAU), 
	LINK_DOP_KL = F.DOP_KL,
	USER_ACC = F.USER_ACC,
	CODE_SFIN = F.CODE,
	ISNULL(CAST (F.SOURCE as CHAR(1)),''),
	P.CODE_ACC,
	SUMMA= SUM(JC.SUMMA),
	TA.LINK_ORG,
	TA.LINK_ACC,
	(CASE WHEN JC.link_ekr = @LinkEKR_R211 THEN @SALARY_OPTIONS_OPT14 ELSE 
		CASE WHEN ISNULL(LTRIM(RTRIM(F.ACC_ESN)),'') = '' THEN @SALARY_OPTIONS_OPT5 ELSE F.ACC_ESN END
	END)
FROM	
	dbo.SDOC D INNER JOIN dbo.CALCULATE_JURNAL JC ON JC.LINK_DOC = D.LINK
			INNER JOIN dbo.PAYS P ON JC.LINK_PAYS = P.LINK
			INNER JOIN dbo.SAL_SFIN F ON F.LINK = JC.LINK_VKR
			LEFT JOIN dbo.TAX2_APP TA ON P.LINK = TA.LINK_UP
WHERE   
	P.OBJECT = 3
	AND NOT JC.LINK_PAYS IS NULL AND JC.LINK_PAYS<>0  
	AND MONTH(JC.PERIOD_BEGIN) = @nMONTH AND YEAR(JC.PERIOD_BEGIN) = @nYEAR
	AND JC.LINK_DEP = @LINK_DEP
GROUP BY 
	JC.LINK_EKR, JC.LINK_PAYS, P.CODE, P.[NAME], F.KBK, F.KAU, F.DOP_KL, F.USER_ACC, F.CODE, F.SOURCE, P.CODE_ACC, P.LINK_KAU, TA.LINK_ORG, TA.LINK_ACC, F.ACC_ESN
ORDER BY
	P.[NAME], F.SOURCE

-------------------
OPEN @Cur
FETCH NEXT FROM @Cur INTO @DATE_DOC_SAL, @LINK_EKR, @LINK_PAYS, @CODE_PAYS, @OSNOVANIE, @LINK_KBK, @LINK_KAU, @LINK_DOP_KL, @USER_ACC, @CODE_SFIN, @Fin_Source, @KD_CODE_ACC, @SUM_PROV, @LINK_ORG, @LINK_ORG_ACC, @SRC
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN
		IF ISNULL(@SUM_PROV,0) <> 0 BEGIN

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

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

			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 'Не сформированы проводки для отчисления ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),''),
					'Не указан счет кредита в настройках этого вида отчисления.',
					'Укажите в настройках отчисления '+ISNULL(LTRIM(RTRIM(@CODE_PAYS)),'')+' счет кредита.',
					'SALARY'
				GOTO DO_NEXT
			END	
			
			-- Сохраняем документ
			SELECT @LINK_DOC_SAL = 0, @NUM_DOC_SAL = NULL
			-- определим максимальный номер
			exec dbo.X_DOCUMENT_GET_NEXT_NUMBER 'DOCUMENTS_SALARY', @NUM_DOC_SAL output, @LINK_DEP

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

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

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

			Set @Account1 = (SELECT TOP 1 link FROM dbo.S_ACCOUNTS WHERE cSource = RTRIM(LTRIM(@Fin_Source)) and cSinth = dbo.SA_GET_WORD_NUM(RTRIM(LTRIM(@SRC)),1,'.') and cAnalit = dbo.SA_GET_WORD_NUM(RTRIM(LTRIM(@SRC)),2,'.') AND cUser = RTRIM(LTRIM(ISNULL(@USER_ACC,''))) )
			IF ISNULL(@Account1,0) = 0
				Set @Account1 = (SELECT TOP 1 link FROM dbo.S_ACCOUNTS WHERE cSource = RTRIM(LTRIM(@Fin_Source)) and cSinth = dbo.SA_GET_WORD_NUM(RTRIM(LTRIM(@SRC)),1,'.') and cAnalit = dbo.SA_GET_WORD_NUM(RTRIM(LTRIM(@SRC)),2,'.') )

			IF ISNULL(@Account1,0) = 0 BEGIN
				ROLLBACK
				SET IMPLICIT_TRANSACTIONS OFF
				INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
				select 'Не сформированы проводки для отчисления ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),'')+ ' по источнику финансирования зарплаты "' + RTRIM(LTRIM(@CODE_SFIN)) + '" с видом деятельности "' + ISNULL((SELECT TOP 1 FS.CODE + '.' + FS.NAME FROM dbo.BB_FIN_SOURCE FS WHERE FS.CODE = CONVERT(VARCHAR(1),@Fin_Source)),'') +  '"',
					'Не найден счет ' + RTRIM(LTRIM(@Fin_Source)) + RTRIM(LTRIM(@SRC)),
					'Добавьте в план счетов счет ' + RTRIM(LTRIM(@Fin_Source)) + RTRIM(LTRIM(@SRC)), 
					'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(ISNULL(@ACC_CODE,''))) <> '' AND RTRIM(LTRIM(ISNULL(@USER_ACC,''))) = '' BEGIN
				ROLLBACK
				SET IMPLICIT_TRANSACTIONS OFF
				INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
				select 'Не сформированы проводки для отчисления ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),''), 
					'У источника финансирования ' + RTRIM(LTRIM(@CODE_SFIN)) + ' не указан пользовательский субсчет, однако у счета ' + RTRIM(LTRIM(ISNULL(@ACC_CODE,''))) + ' есть субсчета',
					'Укажите пользовательский субсчет, либо уберите в плане счетов субсчет у счета ' + RTRIM(LTRIM(ISNULL(@ACC_CODE,''))) + ' с помощью слияния',
					'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 'Не сформированы проводки для отчисления ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),'')+ ' по источнику финансирования зарплаты "' + RTRIM(LTRIM(@CODE_SFIN)) + '" с видом деятельности "' + ISNULL((SELECT TOP 1 FS.CODE + '.' + FS.NAME FROM dbo.BB_FIN_SOURCE FS WHERE FS.CODE = CONVERT(VARCHAR(1),@Fin_Source)),'') +  '"',
					'В плане счетов не найден счет ' + @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 'Не сформированы проводки для отчисления: ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),''),
					'У источника финансирования ' + RTRIM(LTRIM(@CODE_SFIN)) + ' не указан пользовательский субсчет, однако у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' есть субсчета',
					'Укажите пользовательский субсчет, либо уберите в плане счетов субсчет у счета ' + RTRIM(LTRIM(COALESCE(@ACC_CODE,''))) + ' с помощью слияния',
					'SALARY'
				GOTO DO_NEXT
			END

			IF ISNULL(@Account1,0) > 0 AND ISNULL(@Account2,0) > 0 BEGIN

				SET @HOZ_OPER = (SELECT TOP 1 LINK FROM dbo.BX_BPROV_VIBOR_ECON_OPER(@Account1,@Account2))
	
				IF ISNULL(@HOZ_OPER,0) = 0 BEGIN
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформированы проводки для отчисления: ' + ISNULL(LTRIM(RTRIM(@CODE_PAYS)),''),
						'Не найдено подходящей хоз. операции для проводки ' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account1) + '-' + (select top 1 CODE from S_ACCOUNTS where LINK = @Account2),
						'Вероятно в настройках удержания ' + ISNULL(LTRIM(RTRIM(@CODE_PAYS)),'') + ' указан некорректный счет кредита или в общих настройках по зарплате указан неправильно счет для начисления на оплату труда.',
						'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 ISNULL(@SGU,0) = 0 BEGIN
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформированы проводки для отчисления ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),''),
						'У счета ' + (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 ISNULL(@SGU,0) = 0 BEGIN
					ROLLBACK
					SET IMPLICIT_TRANSACTIONS OFF
					INSERT INTO SAL_WORNINGS (msg_before, msg, msg_after, TASK)
					select 'Не сформированы проводки для отчисления ' + COALESCE(LTRIM(RTRIM(@CODE_PAYS)),''),
						'У счета ' + (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_ORG_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 @DATE_DOC_SAL, @LINK_EKR, @LINK_PAYS, @CODE_PAYS, @OSNOVANIE, @LINK_KBK, @LINK_KAU, @LINK_DOP_KL, @USER_ACC, @CODE_SFIN, @Fin_Source, @KD_CODE_ACC, @SUM_PROV, @LINK_ORG, @LINK_ORG_ACC, @SRC
END

CLOSE @Cur
DEALLOCATE @Cur

exec X_SALDO_CommitChanges

SET NOCOUNT OFF
Return 0
END

GO


GRANT EXECUTE ON dbo.[SA_CREATE_PROV_O] 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 (30),
		@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.[RSA_RSV_1_PERS_UCH_SZV]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[RSA_RSV_1_PERS_UCH_SZV]

GO

-- Пример вызова exec [dbo].RSA_RSV_1_PERS_UCH_SZV '20150401', '20150630', 74578 ,1,  20017
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 @nYEAR INT, @nMONTH1 INT, @nMONTH2 INT, @nMONTH3 INT
	
	SELECT 
		@nYEAR = YEAR(@dDATE1),
		@nMONTH1 = MONTH(@dDATE1),
		@nMONTH2 = MONTH(@dDATE1)+1,
		@nMONTH3 = MONTH(@dDATE1)+2

	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


	--Округление каждой строчки таблицы
	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] = CASE WHEN K.CODE = 'ООИ' then 'НР' else K.CODE end ,
		[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),
		[NGROUP] = S.pachka,
		[PFNUMBER] = PF_NUM,
		[T_DOG] = s.forma,
		LINK_FACE,
		NUM = ROW_NUMBER() OVER (PARTITION BY LINK_FACE ORDER BY s.forma),
		[FM],
		[IM],
		[OT],
		[ADDRESS] = [ADDRESS],
		[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,
		dper_vn_m = coalesce(s.dper_vn_m,0),
		dper_vn_d = coalesce(s.dper_vn_d,0),
		dper_oz_m = coalesce(s.dper_oz_m,0),
		dper_oz_d = coalesce(s.dper_oz_d,0),
		[TU_CODE] = f_ter_usl,
		[OS_CODE] = f_osob_usl,
		osob_usl,
		OSOB_SPO = LTRIM(RTRIM(ST.OSOB_SPO)),
		[EX_CODE] = is_osnov,
		f_is_dop,
		[P_CODE] = ud_osnov,
		f_ud_dop,
		DATE_DOC = [date],
		dep_PFNUM = d.PFNUMBER,
		FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),year_begin) + '-ORG-' + LTRIM(RTRIM(d.PFNUMBER)) + '-DCK-' + REPLACE(str(S.pachka,5),' ','0') + '-DPT-000000-DCK-00000.XML',	
		link_doc =p.link
	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.forma, S.pachka, S.orders, ST.orders
	


	UPDATE T
		SET	FNAME = REPLACE( FNAME, REPLACE(str(((SELECT MAX(nGROUP) FROM #SZV_ALL  where link_face =t.link_face )),5)+'-',' ','0'),REPLACE(str(((SELECT MIN(nGROUP) FROM #SZV_ALL  where link_face =t.link_face )),5)+'-',' ','0')), 
		nGROUP = (SELECT MIN(nGROUP) FROM #SZV_ALL  where link_face =t.link_face )
	FROM  #SZV_ALL t 
	where link_face in (select  a.link_face   
						from #SZV_ALL a 
						where link_face in ( select link_face from #SZV_ALL where link_face = a.link_face and  link_doc = a.link_doc and code <> a.code and [TYPE] = 1 ) and [TYPE] = 1 ) 
				and [TYPE] = 1
			
--- нумирация пачек исходных и корректирующих сведений
declare @MAX_PACHKA_ISHOD  int,@MIN_PACHKA_ISHOD int,  @MIN_PACHKA_KORR int,  
		@ID int

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

IF @MIN_PACHKA_ISHOD = @MIN_PACHKA_KORR

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

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

CLOSE @Cur
DEALLOCATE @Cur

END 

UPDATE t
	SET  FNAME=  'PFR-700-Y-' + CONVERT(VARCHAR(4),[year]) + '-ORG-' + LTRIM(RTRIM(dep_PFNUM)) + '-DCK-' + REPLACE(str(NGROUP,5),' ','0') + '-DPT-000000-DCK-00000.XML'	
	from #SZV_ALL t  WHERE TYPE <> 1

----------------------------
SELECT * INTO #SZV_SUM FROM
(SELECT 
	RN = ROW_NUMBER() OVER (PARTITION BY LINK_FACE, CODE, T_DOG, [TYPE], PER_EDT, NGROUP/*, ID_EX*/ ORDER BY T_DOG),
	CODE,
	LINK_FACE,
	[PFNUMBER],
	T_DOG,
	sum(INC_M1) AS INC_M1,
	sum(B_BEF_M1) AS B_BEF_M1,
	sum(B_AFT_M1) AS B_AFT_M1,
	sum(INC_M2) AS INC_M2,
	sum(B_BEF_M2) AS B_BEF_M2,
	sum(B_AFT_M2) AS B_AFT_M2,
	sum(INC_M3) AS INC_M3,
	sum(B_BEF_M3) AS B_BEF_M3,
	sum(B_AFT_M3) AS B_AFT_M3,		
	per,
	[year],
	[TYPE],
	per_edt,
	year_edt,
	sum(INSUR) AS INSUR	
FROM 
	#SZV_ALL 
	GROUP BY CODE ,LINK_FACE,[PFNUMBER],T_DOG,per,[year],[TYPE],per_edt,year_edt,NGROUP,ID_EX
) T WHERE RN = 1	

-- exec [dbo].RSA_RSV_1_PERS_UCH_SZV '20150401', '20150630', 13488 ,1,  269	
-----------
DECLARE @PREDEL NUMERIC(18,2)
SET @PREDEL = ISNULL((SELECT MIN(PREDEL) FROM dbo.DICTIONARY_RANGE_PF WHERE WAY_CALC = 6 AND TARIF = 1 AND [DATE] >= dbo.ConvertDMY2Date(1,1,YEAR(@dDate1))),0)
-----------
SELECT 
	LINK_FACE, [PFNUMBER], CODE, per, [year], [TYPE], per_edt, year_edt, INSUR = SUM(INSUR)
INTO 
	#SZV_PC 		
FROM 
	(
	SELECT 
		A.LINK_FACE, A.[PFNUMBER], A.CODE, A.T_DOG, A.per, A.[year], A.[TYPE], A.per_edt, A.year_edt, 
		INSUR = CASE WHEN MIN(B_AFT_M1) + MIN(B_AFT_M2) + MIN(B_AFT_M3) <> 0 THEN
					MIN(B_BEF_M1 * PERCENT1 / 100) + MIN(B_BEF_M2 * PERCENT1 / 100) + MIN(B_BEF_M3 * PERCENT1 / 100)
				ELSE
					MIN(INSUR)
				END				
	FROM 
		#SZV_SUM A INNER JOIN dbo.SA_PFR_KATEG B ON A.CODE = B.CODE AND [year] BETWEEN YBEG AND YEND
			INNER JOIN 
			(
				SELECT 
					TARIF, PERCENT1
				FROM 
					dbo.DICTIONARY_RANGE_PF D
				WHERE
					WAY_CALC = 6 AND PREDEL = @PREDEL
					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 WAY_CALC = 6 AND DATE <= @dDate1 ORDER BY [DATE] DESC) 
			) C ON C.TARIF = B.LINK2 
	GROUP BY
		A.LINK_FACE, A.[PFNUMBER], A.CODE, A.T_DOG, A.per, A.[year], A.[TYPE], A.per_edt, A.year_edt
	) T
GROUP BY
	LINK_FACE, [PFNUMBER], CODE, per, [year], [TYPE], per_edt, year_edt


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

	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),
			col10 = per_EDT
		FROM
			#SZV_ALL
		GROUP BY [TYPE],[T_DOG],[FM],[IM],[OT],[PFNUMBER], [NGROUP], [FNAME],DATE_DOC,per_EDT
		ORDER BY
			[TYPE],[T_DOG],[FM],[IM],[OT],per_EDT
		
	END

-- exec [dbo].RSA_RSV_1_PERS_UCH_SZV '20150401', '20150630', 13488 ,0,  269	
	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), COL45 char(1) DEFAULT '' )
		
		
		/***************************************/
		-- для подсчета суммы с начала года по конец отчетного периода  
			
			
			------
	
			--- Обьявляем даты
			DECLARE @BYearDate	datetime
			SET @BYearDate = dbo.DateBeginOfYear (@dDate1)

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

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


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

			DECLARE @ESN_213 INT --Начислять страховые взносы на доходы с 213 ЭКР                                                    
			SET @ESN_213 = dbo.SA_GET_OPTION_BY_CODE('ESN_OPTIONS_5')
			
				
			------	у кого была инвалидность в заданном периоде
			SELECT DISTINCT PERS_LINK 
			INTO #PERS_INV
			FROM dbo.PERS_INVALID I
			WHERE COALESCE(I.DATE_BEGIN,@BYearDate) <= @EndYear AND COALESCE(I.DATE_END,@EndYear) >= @BYearDate
			
			delete from #PERS_INV
			
			
			------	у кого есть расчеты по доп тарифам со спец оценками в заданном периоде 
			SELECT DISTINCT sd.LINK, DOP = (CASE when S.COD_POS_SPISOK is NOT NULL then 1 else 2 end) , SPO = isnull(s4.code,'')
			INTO #EMPL_DT
			FROM DBO.KU_EMPL_PLACING SD
				left JOIN (select * from STAFF WHERE dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@nMONTH_3,@nYEAR1)) BETWEEN DATE_BEGIN AND DATE_END  ) S ON S.LINK_up = SD.STAFF_HEAD AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@nMONTH_3,@nYEAR1 )) BETWEEN S.DATE_BEGIN AND S.DATE_END
				LEFT JOIN SA_SZV4_SPR  s4 ON  s4.link = s.COD_SPO_USL_TRUD AND s4.spr_code = 'SPO_USL_TRUDA'
				WHERE 
					(S.COD_POS_SPISOK is NOT NULL OR S.COD_POS_SPISOK2 is NOT NULL) 

			--Заготовка для #SALARY_SUM2
			CREATE TABLE #SALARY_SUM_DATA (PERS_LINK INT,t_dog TINYINT, PERIOD_BEGIN DATETIME, SUMMA_ALL NUMERIC(18,2), SUMMA_NO NUMERIC(18,2), SUMMA_ALL_I NUMERIC(18,2), SUMMA_NO_I NUMERIC(18,2), SUMMA_ALL_E NUMERIC(18,2), SUMMA_NO_E NUMERIC(18,2), INV TINYINT 
					, SUMMA_NO_D1 NUMERIC(18,2), SUMMA_NO_D2 NUMERIC(18,2),    
				SUM_NO_D1_O4 NUMERIC(18,2) ,SUM_NO_D1_B34 NUMERIC(18,2) ,SUM_NO_D1_B33 NUMERIC(18,2),SUM_NO_D1_B32 NUMERIC(18,2), SUM_NO_D1_B31 NUMERIC(18,2),
					SUM_NO_D2_O4 NUMERIC(18,2) ,SUM_NO_D2_B34 NUMERIC(18,2) ,SUM_NO_D2_B33 NUMERIC(18,2),SUM_NO_D2_B32 NUMERIC(18,2), SUM_NO_D2_B31 NUMERIC(18,2) , sack CHAR(1) DEFAULT ''
					)

			--Сотрудники
			INSERT INTO #SALARY_SUM_DATA (PERS_LINK, t_dog, PERIOD_BEGIN, SUMMA_ALL, SUMMA_NO, SUMMA_ALL_I, SUMMA_NO_I, SUMMA_ALL_E, SUMMA_NO_E, INV 
					, SUMMA_NO_D1, SUMMA_NO_D2,SUM_NO_D1_O4,SUM_NO_D1_B34,SUM_NO_D1_B33, SUM_NO_D1_B32, SUM_NO_D1_B31,
					SUM_NO_D2_O4,SUM_NO_D2_B34,SUM_NO_D2_B33, SUM_NO_D2_B32, SUM_NO_D2_B31 , sack 
					)
			select
				E.PERS_LINK, 
				TDOG = 1,
				CJ.PERIOD_BEGIN,
				SUMMA_ALL = SUM(SUMMA),
				SUMMA_NO = SUM(CASE WHEN B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0 THEN SUMMA ELSE 0 END), --на которые не начисляются страховые взносы
				SUMMA_ALL_I = 0,
				SUMMA_NO_I = 0,
				SUMMA_ALL_E = SUM(CASE WHEN F.ENVD = 1 THEN SUMMA ELSE 0 END),
				SUMMA_NO_E = SUM(CASE WHEN F.ENVD = 1 AND (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) THEN SUMMA ELSE 0 END),
				INV = 1, --dbo.is_invalid(e.PERS_LINK,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) ,
				SUMMA_NO_D1 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and ED.DOP = 1 AND isnull(SPO,'') ='' THEN SUMMA ELSE 0 END),
				SUMMA_NO_D2 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and ED.DOP = 2 and  isnull(SPO,'') ='' THEN SUMMA ELSE 0 END),
				SUM_NO_D1_O4 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='О4'  THEN SUMMA ELSE 0 END),
				SUM_NO_D1_B34 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.4' THEN SUMMA ELSE 0 END),
				SUM_NO_D1_B33 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.3' THEN SUMMA ELSE 0 END), 
				SUM_NO_D1_B32 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.2' THEN SUMMA ELSE 0 END), 
				SUM_NO_D1_B31 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.1' THEN SUMMA ELSE 0 END),	
				SUM_NO_D2_O4 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='О4' THEN SUMMA ELSE 0 END),
				SUM_NO_D2_B34 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.4' THEN SUMMA ELSE 0 END),
				SUM_NO_D2_B33 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.3' THEN SUMMA ELSE 0 END), 
				SUM_NO_D2_B32 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.2' THEN SUMMA ELSE 0 END), 
				SUM_NO_D2_B31 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.1' THEN SUMMA ELSE 0 END),
				sack = CASE WHEN isnull(e.DATE_END,'') BETWEEN @dDate1 AND @dDate2 THEN (case when isnull(e.sack,0) = 0 THEN '' ELSE CONVERT( char(1),e.sack ) end ) ELSE '' 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.sd_EMPL E ON E.LINK = CJ.LINK_EMPL
			LEFT JOIN @StBase2 B ON B.LINK = cj.LINK_PAYS
			/*LEFT JOIN #PERS_INV I ON I.PERS_LINK = E.PERS_LINK*/
			LEFT JOIN #EMPL_DT ED ON ED.link = CJ.LINK_EMPL 
			where 	
				P.[OBJECT] = 1
				AND EXISTS(SELECT LINK_FACE FROM #SZV_all WHERE link_face = E.PERS_LINK )
			GROUP BY
				E.PERS_LINK/*, I.PERS_LINK*/, CJ.PERIOD_BEGIN, e.DATE_END, e.sack

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

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

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


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

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

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


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

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

		--Данные о начисленной зарплате
		SELECT 
			PERS_LINK,
			T_DOG = MIN(T_DOG),
			SUMMA_ALL = SUM(SUMMA_ALL), SUMMA_NO = SUM(SUMMA_NO), 
			SUMMA_ALL_I = SUM(SUMMA_ALL_I), SUMMA_NO_I = SUM(SUMMA_NO_I),
			SUMMA_ALL_E = SUM(SUMMA_ALL_E), SUMMA_NO_E = SUM(SUMMA_NO_E),
			SUMMA_ALL_DO_I = (CASE WHEN SUM(SUMMA_ALL_I) > @PREDEL THEN  @PREDEL ELSE (SUM(SUMMA_ALL_I) - SUM(SUMMA_NO_I)) END ),
			SUMMA_ALL_DO = (CASE WHEN SUM(SUMMA_ALL) > @PREDEL THEN  @PREDEL ELSE (SUM(SUMMA_ALL) - SUM(SUMMA_NO)) END ),
			SUMMA_ALL_AFTER = (CASE WHEN SUM(SUMMA_ALL - SUMMA_ALL_I - SUMMA_NO - SUMMA_NO_I)  > @PREDEL THEN  SUM(SUMMA_ALL) - @PREDEL ELSE 0 END ),
			SUMMA_ALL_AFTER_I = (CASE WHEN SUM(SUMMA_ALL_I) > @PREDEL THEN  SUM(SUMMA_ALL) - @PREDEL ELSE 0 END )
			,BASE_DOG = SUM(CASE WHEN T_DOG = 2 THEN SUMMA_ALL - SUMMA_NO ELSE 0 END),
			SACK = MAX(SACK)
		INTO #SALARY_SUM2
		FROM #SALARY_SUM_DATA s 
		GROUP BY
			PERS_LINK/*,SACK*/



-----------<<<<<<<<</*СВЕДЕНИЯ ЗА ПЕРИОД , ПО КОРРЕКТИРУЮЩИМ*/
		
		DECLARE @nYEAR1_K INT, @nMONTH_1_K INT, @nMONTH_2_K INT, @nMONTH_3_K INT	
		select 
   		@nYEAR1_K = YEAR_EDT,
   		@nMONTH_1_K = /*case when YEAR_EDT  between '2011' and '2013' then (*/case  PER_EDT when 1 then  1 when 2 then  4 when 3 then  7 when 4 then  10 else 10 end/*)
					when  YEAR_EDT >= '2014'  then (case  PER_EDT when 3 then  1 when 6 then  4 when 9 then  7 else  10 end)
					else null end */
		from #SZV_ALL	
		where [TYPE] = 2
		and YEAR_EDT >=2014
							 
		select @nMONTH_2_K = @nMONTH_1_K+1,
				@nMONTH_3_K = @nMONTH_1_K +2	

		DECLARE @BYearDate_K	datetime , @EndYear_K datetime
		SET @BYearDate_K = dbo.DateBeginOfYear (@nYEAR1_K+'0101')
		Set @EndYear_K = dbo.DateEndOfYear(@BYearDate_K)

		--Фактическая база для договорников
		SELECT 
			GT.PERS_LINK, MONTH(G.[DATE]) AS MONTH_BASE, F.ENVD, SUMMA_BASE = sum(GT.SUMMA_BASE)
		INTO #DGH_FAKT_BASE_K
		FROM 
			dbo.DOCUMENTS_DGH G INNER JOIN dbo.DOCUMENTS_DGH_T3 GT ON G.LINK = GT.LINK
			INNER JOIN dbo.SAL_SFIN F on F.LINK = GT.LINK_VKR
		WHERE 
			FLAG_JC = 1
			AND GT.WAY_CALC  = 6
			AND YEAR(G.[DATE]) = @nYEAR1_K
			AND MONTH(G.[DATE]) <= @nMONTH_3_K
			--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_K
			FROM #DGH_FAKT_BASE_K
			GROUP BY PERS_LINK, MONTH_BASE


			-- Журнал операций 
			CREATE TABLE #CALCULATE_JURNAL_K (LINK_PAYS INT, PERIOD_BEGIN DATETIME, LINK_DOC INT, PERS_LINK INT, LINK_VKR INT, LINK_EKR INT, LINK_EMPL INT, SUMMA NUMERIC(18,2), WAY_CALC TINYINT , SPECO int)
			INSERT INTO #CALCULATE_JURNAL_K (LINK_PAYS, PERIOD_BEGIN, LINK_DOC, PERS_LINK, LINK_VKR, LINK_EKR, LINK_EMPL, SUMMA,way_calc , SPECO)
			SELECT CJ.LINK_PAYS, CJ.PERIOD_BEGIN, CJ.LINK_DOC, CJ.PERS_LINK, CJ.LINK_VKR, cj.LINK_EKR, CJ.LINK_EMPL, SUMMA = SUM(CJ.SUMMA), p.way_calc , SPECO
			FROM dbo.CALCULATE_JURNAL CJ INNER JOIN dbo.PAYS P ON  CJ.LINK_PAYS = p.link
			WHERE
				Year(period_begin) = @nYEAR1_K 
				and Month(period_begin) <= @nMONTH_3_K
				and CJ.LINK_DEP = @DEP_LINK
			GROUP BY
				cj.LINK_PAYS, cj.PERIOD_BEGIN, cj.LINK_DOC, cj.PERS_LINK, cj.LINK_VKR, cj.LINK_EKR, cj.LINK_EMPL, P.WAY_CALC,cj.SPECO
						
						
			------	у кого была инвалидность в заданном периоде
			SELECT DISTINCT PERS_LINK 
			INTO #PERS_INV_K
			FROM dbo.PERS_INVALID I
			WHERE COALESCE(I.DATE_BEGIN,@BYearDate_K) <= @EndYear_K AND COALESCE(I.DATE_END,@EndYear_K) >= @BYearDate_K

			------	у кого есть расчеты по доп тарифам со спец оценками в заданном периоде 
			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_K
			FROM DBO.KU_EMPL_PLACING SD
				left JOIN (select * from STAFF WHERE dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@nMONTH_3_K,@nYEAR1_K)) BETWEEN DATE_BEGIN AND DATE_END  ) S ON S.LINK_up = SD.STAFF_HEAD AND dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@nMONTH_3_K,@nYEAR1_K )) 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_K (PERS_LINK INT,t_dog TINYINT, PERIOD_BEGIN DATETIME , Per_Q TINYINT, SUMMA_ALL NUMERIC(18,2), SUMMA_NO NUMERIC(18,2), SUMMA_ALL_I NUMERIC(18,2), SUMMA_NO_I NUMERIC(18,2), SUMMA_ALL_E NUMERIC(18,2), SUMMA_NO_E NUMERIC(18,2), INV TINYINT 
					, SUMMA_NO_D1 NUMERIC(18,2), SUMMA_NO_D2 NUMERIC(18,2),    
				SUM_NO_D1_O4 NUMERIC(18,2) ,SUM_NO_D1_B34 NUMERIC(18,2) ,SUM_NO_D1_B33 NUMERIC(18,2),SUM_NO_D1_B32 NUMERIC(18,2), SUM_NO_D1_B31 NUMERIC(18,2),
					SUM_NO_D2_O4 NUMERIC(18,2) ,SUM_NO_D2_B34 NUMERIC(18,2) ,SUM_NO_D2_B33 NUMERIC(18,2),SUM_NO_D2_B32 NUMERIC(18,2), SUM_NO_D2_B31 NUMERIC(18,2) , sack CHAR(1) DEFAULT '' 
					)

			--Сотрудники
			INSERT INTO #SALARY_SUM_DATA_K (PERS_LINK, t_dog, PERIOD_BEGIN,Per_Q, SUMMA_ALL, SUMMA_NO, SUMMA_ALL_I, SUMMA_NO_I, SUMMA_ALL_E, SUMMA_NO_E, INV 
					, SUMMA_NO_D1, SUMMA_NO_D2,SUM_NO_D1_O4,SUM_NO_D1_B34,SUM_NO_D1_B33, SUM_NO_D1_B32, SUM_NO_D1_B31,
					SUM_NO_D2_O4,SUM_NO_D2_B34,SUM_NO_D2_B33, SUM_NO_D2_B32, SUM_NO_D2_B31,sack
					)
			select
				E.PERS_LINK, 
				TDOG = 1,
				CJ.PERIOD_BEGIN,
				CASE  WHEN month(CJ.PERIOD_BEGIN) BETWEEN 1 AND 3 THEN 1 WHEN  month(CJ.PERIOD_BEGIN) BETWEEN 4 AND 6 THEN 2 WHEN month(CJ.PERIOD_BEGIN) BETWEEN 7 AND 9 THEN 3 ELSE 4 END ,
				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 =  dbo.is_invalid(e.PERS_LINK,dbo.DateEndOfMonth(CJ.PERIOD_BEGIN)) ,
				SUMMA_NO_D1 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and ED.DOP = 1 AND isnull(SPO,'') ='' THEN SUMMA ELSE 0 END),
				SUMMA_NO_D2 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and ED.DOP = 2 and  isnull(SPO,'') ='' THEN SUMMA ELSE 0 END),
				SUM_NO_D1_O4 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='О4'  THEN SUMMA ELSE 0 END),
				SUM_NO_D1_B34 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.4' THEN SUMMA ELSE 0 END),
				SUM_NO_D1_B33 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.3' THEN SUMMA ELSE 0 END), 
				SUM_NO_D1_B32 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.2' THEN SUMMA ELSE 0 END), 
				SUM_NO_D1_B31 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =1 AND SPO ='В3.1' THEN SUMMA ELSE 0 END),	
				SUM_NO_D2_O4 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='О4' THEN SUMMA ELSE 0 END),
				SUM_NO_D2_B34 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.4' THEN SUMMA ELSE 0 END),
				SUM_NO_D2_B33 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.3' THEN SUMMA ELSE 0 END), 
				SUM_NO_D2_B32 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.2' THEN SUMMA ELSE 0 END), 
				SUM_NO_D2_B31 = SUM(CASE WHEN (B.LINK IS NULL OR CJ.LINK_EKR = @LINK_EKR213 AND @ESN_213 = 0) and CJ.LINK_EMPL = ED.link and DOP =2 AND SPO ='В3.1' THEN SUMMA ELSE 0 END),
				sack = CASE WHEN isnull(e.DATE_END,'') BETWEEN @dDate1 AND @dDate2 THEN (case when isnull(e.sack,0) = 0 THEN '' ELSE CONVERT( char(1),e.sack ) end ) ELSE '' END 
			from 
			#CALCULATE_JURNAL_K 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.SD_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_K ED ON ED.link = CJ.LINK_EMPL
			
			where 	
				P.[OBJECT] = 1
				AND EXISTS(SELECT LINK_FACE FROM #SZV_all WHERE link_face = E.PERS_LINK )
			GROUP BY
				E.PERS_LINK/*, I.PERS_LINK*/, CJ.PERIOD_BEGIN,e.DATE_END,e.sack

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

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

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

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

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

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


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

		DECLARE @PREDEL_K NUMERIC(18,2)
		SET @PREDEL_K = (SELECT TOP 1 PREDEL FROM DICTIONARY_RANGE WHERE TARIF = 1 AND YEAR([DATE]) =  @nYEAR1_K)
		
		--Данные о начисленной зарплате
		SELECT 
			PERS_LINK,
			T_DOG = MIN(T_DOG),
			/*MON = Month(PERIOD_BEGIN),*/ 
			SUMMA_ALL = SUM(SUMMA_ALL), SUMMA_NO = SUM(SUMMA_NO), 
			SUMMA_ALL_I = SUM(SUMMA_ALL_I), SUMMA_NO_I = SUM(SUMMA_NO_I),
			SUMMA_ALL_E = SUM(SUMMA_ALL_E), SUMMA_NO_E = SUM(SUMMA_NO_E),
			SUMMA_ALL_D =  ISNULL((select SUM(SUMMA_ALL) FROM  #SALARY_SUM_DATA WHERE PERS_LINK = s.PERS_LINK AND t_dog=2 ),0) ,
			SUMMA_ALL_DO_I = (CASE WHEN SUM(SUMMA_ALL_I) > @PREDEL THEN  @PREDEL ELSE (SUM(SUMMA_ALL_I) - SUM(SUMMA_NO_I)) END ),
			SUMMA_ALL_DO = (CASE WHEN SUM(SUMMA_ALL) > @PREDEL THEN  @PREDEL ELSE (SUM(SUMMA_ALL) - SUM(SUMMA_NO)) END ),
			SUMMA_ALL_AFTER = (CASE WHEN SUM(SUMMA_ALL - SUMMA_ALL_I)  > @PREDEL THEN  SUM(SUMMA_ALL) - @PREDEL ELSE 0 END ),
			SUMMA_ALL_AFTER_I = (CASE WHEN SUM(SUMMA_ALL_I)  > @PREDEL THEN  SUM(SUMMA_ALL) - @PREDEL ELSE 0 END )
			,BASE_DOG = SUM(CASE WHEN T_DOG = 2 THEN SUMMA_ALL - SUMMA_NO ELSE 0 END),					
			SACK = MAX(SACK)								
		INTO #SALARY_SUM2_K
		FROM #SALARY_SUM_DATA_K s 
		GROUP BY
			pers_link--,SACK--, T_DOG--,Month(PERIOD_BEGIN)
		
		--Данные о начисленной зарплате с периодами (по кварталам)
		SELECT 
			PERS_LINK,
			T_DOG = MIN(T_DOG),
			PER_Q = PER_Q,
			SUMMA_ALL = SUM(SUMMA_ALL), SUMMA_NO = SUM(SUMMA_NO), 
			SUMMA_ALL_I = SUM(SUMMA_ALL_I), SUMMA_NO_I = SUM(SUMMA_NO_I),
			SUMMA_ALL_E = SUM(SUMMA_ALL_E), SUMMA_NO_E = SUM(SUMMA_NO_E),
			SUMMA_ALL_D =  ISNULL((select SUM(SUMMA_ALL) FROM  #SALARY_SUM_DATA WHERE PERS_LINK = s.PERS_LINK AND t_dog=2 ),0) ,
			SUMMA_ALL_DO_I = (CASE WHEN SUM(SUMMA_ALL_I) > @PREDEL THEN  @PREDEL ELSE (SUM(SUMMA_ALL_I) - SUM(SUMMA_NO_I)) END ),
			SUMMA_ALL_DO = (CASE WHEN SUM(SUMMA_ALL) > @PREDEL THEN  @PREDEL ELSE (SUM(SUMMA_ALL) - SUM(SUMMA_NO)) END ),
			SUMMA_ALL_AFTER = (CASE WHEN SUM(SUMMA_ALL - SUMMA_ALL_I)  > @PREDEL THEN  SUM(SUMMA_ALL) - @PREDEL ELSE 0 END ),
			SUMMA_ALL_AFTER_I = (CASE WHEN SUM(SUMMA_ALL_I)  > @PREDEL THEN  SUM(SUMMA_ALL) - @PREDEL ELSE 0 END )
			,BASE_DOG = SUM(CASE WHEN T_DOG = 2 THEN SUMMA_ALL - SUMMA_NO ELSE 0 END)					
											
		INTO #SALARY_SUM_PER_K
		FROM #SALARY_SUM_DATA_K s 
		GROUP BY
			pers_link , per_q--, T_DOG--,Month(PERIOD_BEGIN)	
			


		DROP TABLE #SALARY_SUM_DATA	
		DROP TABLE #DGH_FAKT_BASE
		DROP TABLE #DGH_FAKT_BASE1
		DROP TABLE #PERS_INV
		DROP TABLE #CALCULATE_JURNAL
		DROP TABLE #EMPL_DT		

		DROP TABLE #SALARY_SUM_DATA_K	
		DROP TABLE #DGH_FAKT_BASE_K
		DROP TABLE #DGH_FAKT_BASE1_K
		DROP TABLE #PERS_INV_K
		DROP TABLE #CALCULATE_JURNAL_K
		DROP TABLE #EMPL_DT_K				

		
		/*Корректирующие сведения по физ лицам для печати раздела 6.6*/
		SELECT year_edt = p.YEAR_EDT, 
				PER_EDT = p.PER_EDT, 
				link_dep = p.link_dep,
				link_pers = s.link_pers,
				Link_kateg = S.Link_kateg,
				pachka = s.pachka
		INTO #tmp_pers_r1
		FROM 	dbo.SA_SZV4_PACHKA P 
				INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up 															
		where
			P.link in (select link from #DOCS WHERE vid_kor = 2)
			and P.proverka = 1
			and P.vid_kor > 1
			and p.link_dep = @DEP_LINK


		CREATE TABLE #tmp_pers_kor_sum_R1 (link INT  , [date] DATETIME, YEAR_degin INT , per INT , vid_kor int, link_dep INT , proverka INT  , CODE VARCHAR(5), link_pers INT , 
										sum_doh NUMERIC(18,2), sum_str NUMERIC(18,2), sum_nak NUMERIC(18,2),sum_dop NUMERIC(18,2) , pachka int) 
	
		DECLARE @Cur_R1 CURSOR, @link_R1 int ,@LINK_pers_R1 INT, @year_edt_R1 INT , @per_edt_R1 INT , @Link_kateg_R1 INT ,@pachka_R1 int
		SET @Cur_R1 = CURSOR FORWARD_ONLY

		FOR SELECT LINK_pers, year_edt, per_edt, Link_kateg ,pachka FROM #tmp_pers_r1 ORDER by link_pers

		OPEN @Cur_R1
		FETCH NEXT FROM @Cur_R1 INTO @LINK_pers_R1, @year_edt_R1, @per_edt_R1 , @link_kateg_R1, @pachka_R1
		WHILE (@@fetch_status <> -1)
		BEGIN

			IF (@@fetch_status <> -2)
			BEGIN
				
				
					SET @link_R1 = 0
					
					SELECT @link_R1 =max(pp.link)
					FROM SA_SZV4_PACHKA pp 
					INNER JOIN dbo.SZV4_SVEDENIA Ss ON ss.link_up = pp.link  
					WHERE  pp.proverka = 1 AND pp.vid_kor = 1 
										  AND pp.link_dep = @DEP_LINK 
										  AND pp.year_begin =@year_edt_R1  
										  AND pp.PER =@per_edt_R1 
										  AND @LINK_pers_R1 = ss.link_pers
										 /* AND @link_kateg_R1 = ss.link_kateg  */
										  AND pp.date = (SELECT MAX(p1.[date]) FROM SA_SZV4_PACHKA p1 
																INNER JOIN dbo.SZV4_SVEDENIA S1 ON s1.link_up = p1.link  
																WHERE  pp.proverka = 1 AND p1.vid_kor = 1 
																					  AND p1.link_dep = @DEP_LINK 
																					  AND p1.year_begin =@year_edt_R1  
																					  AND p1.PER =@per_edt_R1 
																					  AND @LINK_pers_R1 = s1.link_pers
																					  /*AND @link_kateg_R1 = s1.link_kateg*/ )
					
					INSERT INTO #tmp_pers_kor_sum_R1  (link, [date], YEAR_degin, per, vid_kor, link_dep, proverka , CODE, link_pers, 
										sum_doh, sum_str, sum_nak,sum_dop, pachka) 
					SELECT pp.link, pp.[date], pp.YEAR_begin, pp.per, pp.vid_kor, pp.link_dep, pp.proverka, CODE = k.code, ss.link_pers, 
										ss.sum_doh, ss.sum_str, ss.sum_nak,ss.sum_dop , pachka = @pachka_R1
					FROM SA_SZV4_PACHKA pp 
					INNER JOIN dbo.SZV4_SVEDENIA Ss ON ss.link_up = pp.link  
					INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = ss.LINK_KATEG AND pp.YEAR_begin BETWEEN YBEG AND YEND		
					WHERE pp.link = @link_R1 and pp.proverka = 1 
										 AND pp.vid_kor = 1 
										 AND pp.link_dep = @DEP_LINK 
										 AND pp.year_begin =@year_edt_R1  
										 AND pp.PER =@per_edt_R1 
										 AND ss.link_pers = @LINK_pers_R1
										 /*AND ss.link_kateg = @link_kateg_R1*/
										  

			END

			FETCH NEXT FROM @Cur_R1 INTO @LINK_pers_R1, @year_edt_R1, @per_edt_R1, @link_kateg_R1, @pachka_R1
		END

		CLOSE @Cur_R1
		DEALLOCATE @Cur_R1


		/******************* ИСХОДНЫЕ СВЕДЕНИЯ ********************/
		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, @DATE DATETIME
		set @pf_num1 = ''
		set @CODE_old = '' 
		set @TYPE_OLD = 0
		set @nom_pp = 1

		SET @Cur1 = CURSOR FORWARD_ONLY
		FOR SELECT  [CODE],[TYPE],[PFNUMBER], [FM],[IM],[OT], MIN(DATE_BEGIN) AS DATE_BEGIN  
			FROM #SZV_ALL where [TYPE] = 1 
			GROUP BY [FM],[IM],[OT],[PFNUMBER],[TYPE],CODE
			ORDER BY [FM],[IM],[OT],[PFNUMBER],DATE_BEGIN
		OPEN @Cur1
		FETCH NEXT FROM @Cur1 INTO  @CODE,@TYPE/*,@T_DOG*/,@PFNUMBER,@FM,@IM,@OT, @DATE
		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, COL45)
					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 = CASE WHEN @CODE = 'ООИ' THEN ISNULL(SS.SUMMA_ALL_I,0) ELSE ISNULL(SS.SUMMA_ALL - SS.SUMMA_ALL_I ,0) END,
						   COL7 = 
								CASE WHEN @CODE = 'ООИ' THEN
										(CASE WHEN
											(ISNULL(SS.SUMMA_ALL_I - SS.SUMMA_NO_I,0) 
											- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face) ,0) ))
											) > @PREDEL 
										THEN @PREDEL
										ELSE 
											(ISNULL(SS.SUMMA_ALL_I - SS.SUMMA_NO_I,0) 
											- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face) ,0) ))
											)
										END)	
									ELSE
										(CASE WHEN 
											( ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0) - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
											- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))
											) > @PREDEL 
										THEN @PREDEL
										ELSE 
											( ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0)  - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
											- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))
											) 
										END) 
								 END,
						   COL8 = ISNULL(SS.BASE_DOG,0),
						   COL9 = CASE WHEN @CODE = 'ООИ' THEN
										(CASE WHEN
											(ISNULL(SS.SUMMA_ALL_I,0) - ISNULL(SS.SUMMA_NO_I,0) 
											- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face) ,0) ))
											) > @PREDEL 
										THEN 
											(ISNULL(SS.SUMMA_ALL_I,0) - ISNULL(SS.SUMMA_NO_I,0) 
											- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face) ,0) ))
											) - @PREDEL 
										ELSE 
											0
										END)	
									ELSE
										(CASE WHEN 
											(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0) - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
											- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))
											) > @PREDEL
										THEN 
											(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0) - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
											- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))
											) - @PREDEL
										ELSE 
											0
										END) 
								 END,
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = ISNULL(CONVERT(VARCHAR(1),[per_edt]), ''), 
						   COL14 = ISNULL(CONVERT(VARCHAR(4),[year_edt]), ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT), 
						   COL44 = isnull([INSUR],0),
						   COL45 = ISNULL([sack],'')
					FROM #SZV_PC s LEFT JOIN #SALARY_SUM2 ss ON ss.pers_link = s.link_face
					WHERE 
						code = @CODE and [TYPE] = @TYPE AND PFNUMBER = @PFNUMBER
					
					select row_number() over (order by PER_EDT) as ID , 
							[PER_EDT] as k_PER_EDT, 
							YEAR_EDT as k_YEAR_EDT, 
							INSUR - (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum_r1 WHERE CODE = 'НР' AND LINK_pers = s.link_face AND  per = s.[PER_EDT]  )  as k_INSUR, 
							GAIN - (SELECT SUM(SUM_NAK) FROM #tmp_pers_kor_sum_r1 WHERE CODE = 'НР' AND LINK_pers = s.link_face AND  per = s.[PER_EDT] ) as k_GAIN, 
							PFNUMBER as k_PFNUMBER , 
							FM as k_FM 
					INTO #TMP01
					from  #SZV_ALL s
					WHERE  [TYPE] = 2 AND id_ex =1 and FM = @FM AND PFNUMBER = @PFNUMBER

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


					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 = SUM([INC_M1]),
						   COL7 = SUM([B_BEF_M1]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M1] ELSE 0 END),
						   COL9 = SUM([B_AFT_M1]),
						   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_SUM WHERE code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0),	
						   COL3 = CONVERT(VARCHAR(100), '2 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'402'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = SUM([INC_M2]),
						   COL7 = SUM([B_BEF_M2]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M2] ELSE 0 END),
						   COL9 = SUM([B_AFT_M2]),
						   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_SUM WHERE code = @CODE and [TYPE] = @TYPE AND PFNUMBER = @PFNUMBER
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]
					
					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 = SUM([INC_M3]),
						   COL7 = SUM([B_BEF_M3]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M3] ELSE 0 END),
						   COL9 = SUM([B_AFT_M3]),
						   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_SUM WHERE code = @CODE and [TYPE] = @TYPE AND PFNUMBER = @PFNUMBER
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]
					
					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,COL45)
					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 = CASE WHEN @CODE = 'ООИ' then ISNULL(SS.SUMMA_ALL_I,0) ELSE ISNULL(SS.SUMMA_ALL- SS.SUMMA_ALL_I,0) end,
						   COL7 = 
								CASE WHEN @CODE = 'ООИ' THEN
									--база по ООИ
									(ISNULL(SS.SUMMA_ALL_I - SS.SUMMA_NO_I,0) 
									- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face) ,0) ))
									)
								ELSE
									--база по НР
									( (ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0)) - (ISNULL(SS.SUMMA_NO,0) -  ISNULL(SS.SUMMA_NO_I,0))
									- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))
									)
								END
								- --сумма превышения
								CASE WHEN 
									(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_NO,0) 
									- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND ref_phys_pers = s.link_face) ,0) ))
									) > @PREDEL
								THEN
									(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_NO,0) 
									- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND ref_phys_pers = s.link_face) ,0) ))
									) - @PREDEL
								ELSE
									0
								END,	
														
						   COL8 = ISNULL(SS.BASE_DOG,0),

						   COL9 = 
								--сумма превышения
								CASE WHEN 
									(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_NO,0) 
									- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND ref_phys_pers = s.link_face) ,0) ))
									) > @PREDEL
								THEN
									(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_NO,0) 
									- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1 WHERE WAY_CALC = 6 AND ref_phys_pers = s.link_face) ,0) ))
									) - @PREDEL
								ELSE
									0
								END,
						   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),
						   COL44 =  isnull([INSUR],0),
						   COL45 = ISNULL(SACK,'')
					FROM 
						#SZV_PC s LEFT JOIN #SALARY_SUM2 ss ON ss.pers_link = s.link_face
					WHERE 
						code = @CODE and [TYPE] = @TYPE AND PFNUMBER = @PFNUMBER
					
					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 = SUM([INC_M1]),
						   COL7 = SUM([B_BEF_M1]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M1] ELSE 0 END),
						   COL9 = SUM([B_AFT_M1]),
						   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_SUM WHERE code = @CODE and [TYPE] = @TYPE AND PFNUMBER = @PFNUMBER
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]
					
					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 = SUM([INC_M2]),
						   COL7 = SUM([B_BEF_M2]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M2] ELSE 0 END),
						   COL9 = SUM([B_AFT_M2]),
						   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_SUM WHERE code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]
					
					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 = SUM([INC_M3]),
						   COL7 = SUM([B_BEF_M3]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M3] ELSE 0 END),
						   COL9 = SUM([B_AFT_M3]),
						   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_SUM WHERE code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]
					
					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, @DATE
		END

		CLOSE @Cur1
		DEALLOCATE @Cur1

		/*****************************************************/
		-- Собираем информацию по Кореектирующим/Отменяющим
		/*****************************************************/
		DECLARE @Cur2 CURSOR , @PER_EDT1 INT, @PER_OLD INT
		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],[PFNUMBER], [FM],[IM],[OT], PER_EDT  FROM #SZV_ALL where /*T_DOG = 1 and*/ [TYPE] != 1 AND YEAR_EDT >=2014 GROUP BY [FM],[IM],[OT],[PFNUMBER],[TYPE],CODE/*, [T_DOG]*/, PER_EDT ORDER BY [FM],[IM],[OT],[PFNUMBER],[TYPE],CODE/*, [T_DOG]*/, PER_EDT
		OPEN @Cur2
		FETCH NEXT FROM @Cur2 INTO  @CODE,@TYPE,@PFNUMBER,@FM,@IM,@OT,@PER_EDT1
		WHILE (@@fetch_status <> -1)
		BEGIN

			IF (@@fetch_status <> -2)
			BEGIN
				  
				--- Заполнение информации по первому коду категории сотрудника (нр , оои, пнэд)
				IF (/*@T_DOG = 1 and */ @PFNUMBER <> @pf_num1  OR ( @PFNUMBER = @pf_num1 AND  @PER_EDT1 <> @PER_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, COL45)
					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 = CASE WHEN @CODE = 'ООИ' THEN ISNULL(SS.SUMMA_ALL_I,0) ELSE ISNULL(SS.SUMMA_ALL - SS.SUMMA_ALL_I,0) END,
						   COL7 = 
								CASE WHEN @CODE = 'ООИ' THEN
										(CASE WHEN
											(ISNULL(SS.SUMMA_ALL_I - SS.SUMMA_NO_I,0) 
											- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face 
																						and month_base <= (case when @PER_EDT1  = 1 then  3
																						when @PER_EDT1  = 2 then 6
																						when @PER_EDT1  = 3 then 9
																						when @PER_EDT1  = 0 then 12 END )) ,0) ))
											) > @PREDEL_K 
										THEN @PREDEL_K
										ELSE 
											(ISNULL(SS.SUMMA_ALL_I - SS.SUMMA_NO_I,0) 
											- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face 
																						and month_base <= (case when @PER_EDT1  = 1 then  3
																						when @PER_EDT1  = 2 then 6
																						when @PER_EDT1  = 3 then 9
																						when @PER_EDT1  = 0 then 12 END )) ,0) ))
											)
										END)	
									ELSE
										(CASE WHEN 
											( ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0) - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
											- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face 
																						and month_base <= (case when @PER_EDT1  = 1 then  3
																						when @PER_EDT1  = 2 then 6
																						when @PER_EDT1  = 3 then 9
																						when @PER_EDT1  = 0 then 12 END )) ,0) ))
											) > @PREDEL_K 
										THEN @PREDEL_K
										ELSE 
											( ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0) - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
											- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face 
																						and month_base <= (case when @PER_EDT1  = 1 then  3
																						when @PER_EDT1  = 2 then 6
																						when @PER_EDT1  = 3 then 9
																						when @PER_EDT1  = 0 then 12 END )) ,0) ))
											) 
										END) 
								 END,								 

						   COL8 = ISNULL(SS.BASE_DOG,0),

						   COL9 = CASE WHEN @CODE = 'ООИ' THEN
										(CASE WHEN
											(ISNULL(SS.SUMMA_ALL_I,0) - ISNULL(SS.SUMMA_NO_I,0) 
											- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face 
																						and month_base <= (case when @PER_EDT1  = 1 then  3
																						when @PER_EDT1  = 2 then 6
																						when @PER_EDT1  = 3 then 9
																						when @PER_EDT1  = 0 then 12 END )) ,0) ))
											) > @PREDEL_K 
										THEN 
											(ISNULL(SS.SUMMA_ALL_I,0) - ISNULL(SS.SUMMA_NO_I,0) 
											- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face 
																						and month_base <= (case when @PER_EDT1  = 1 then  3
																						when @PER_EDT1  = 2 then 6
																						when @PER_EDT1  = 3 then 9
																						when @PER_EDT1  = 0 then 12 END )) ,0) ))
											) - @PREDEL_K 
										ELSE 
											0
										END)	
									ELSE
										(CASE WHEN 
											(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0) - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
											- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face 
																						and month_base <= (case when @PER_EDT1  = 1 then  3
																						when @PER_EDT1  = 2 then 6
																						when @PER_EDT1  = 3 then 9
																						when @PER_EDT1  = 0 then 12 END )) ,0) ))
											) > @PREDEL_K
										THEN 
											(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0) - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
											- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face 
																						and month_base <= (case when @PER_EDT1  = 1 then  3
																						when @PER_EDT1  = 2 then 6
																						when @PER_EDT1  = 3 then 9
																						when @PER_EDT1  = 0 then 12 END )) ,0) ))
											) - @PREDEL_K
										ELSE 
											0
										END) 
								 END,
																			
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = ISNULL(CONVERT(VARCHAR(1),[per_edt]), ''), 
						   COL14 = ISNULL(CONVERT(VARCHAR(4),[year_edt]), ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   COL44 = isnull([INSUR],0),
						   COL45 = ISNULL([SACK],'')
					FROM 
						#SZV_PC s LEFT JOIN #SALARY_SUM2_K ss ON ss.pers_link = s.link_face
					WHERE 
						code = @CODE and [TYPE] = @TYPE AND PFNUMBER = @PFNUMBER  AND PER_EDT = @PER_EDT1 
						
						

					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 = SUM([INC_M1]),
						   COL7 = SUM([B_BEF_M1]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M1] ELSE 0 END),
						   COL9 = SUM([B_AFT_M1]),
						   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_SUM WHERE  code = @CODE and [TYPE] = @TYPE /*and T_DOG = @T_DOG*/ AND PFNUMBER = @PFNUMBER AND per_edt = @per_edt1
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]

			
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0),	
						   COL3 = CONVERT(VARCHAR(100), '2 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'402'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = SUM([INC_M2]),
						   COL7 = SUM([B_BEF_M2]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M2] ELSE 0 END),
						   COL9 = SUM([B_AFT_M2]),
						   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_SUM WHERE code = @CODE and [TYPE] = @TYPE AND PFNUMBER = @PFNUMBER AND per_edt = @per_edt1
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]

										
					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 = SUM([INC_M3]),
						   COL7 = SUM([B_BEF_M3]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M3] ELSE 0 END),
						   COL9 = SUM([B_AFT_M3]),
						   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_SUM WHERE code = @CODE and [TYPE] = @TYPE AND PFNUMBER = @PFNUMBER AND per_edt = @per_edt1
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]
					
					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 = CASE WHEN @CODE = 'ООИ' then ISNULL(SS.SUMMA_ALL_I,0) ELSE ISNULL(SS.SUMMA_ALL - SS.SUMMA_ALL_I,0) end,
						   COL7 = 
								CASE WHEN @CODE = 'ООИ' THEN
									--база по ООИ
									(ISNULL(SS.SUMMA_ALL_I - SS.SUMMA_NO_I,0) 
									- ( CONVERT(numeric(18,2),ISNULL( (SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 2 AND ref_phys_pers = s.link_face) ,0) ))
									)
								ELSE
									--база по НР
									(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_ALL_I,0) - (ISNULL(SS.SUMMA_NO,0) - ISNULL(SS.SUMMA_NO_I,0))
									- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND I = 1 AND ref_phys_pers = s.link_face) ,0) ))
									)
								END
								- --сумма превышения
								CASE WHEN 
									(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_NO,0) 
									- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND ref_phys_pers = s.link_face) ,0) ))
									) > @PREDEL_K
								THEN
									(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_NO,0) 
									- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND ref_phys_pers = s.link_face) ,0) ))
									) - @PREDEL_K
								ELSE
									0
								END,
													
						   COL8 = ISNULL(SS.BASE_DOG,0),
						   
						   COL9 = 
								--сумма превышения
								CASE WHEN 
									(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_NO,0) 
									- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND ref_phys_pers = s.link_face) ,0) ))
									) > @PREDEL_K
								THEN
									(ISNULL(SS.SUMMA_ALL,0) - ISNULL(SS.SUMMA_NO,0) 
									- ( CONVERT(numeric(18,2),ISNULL((SELECT SUM(DED_M) + SUM(INV_M) FROM #SPR_ESN1_K WHERE WAY_CALC = 6 AND ref_phys_pers = s.link_face) ,0) ))
									) - @PREDEL_K
								ELSE
									0
								END,										
						   COL10 = ISNULL([per],''), 
						   COL11 = ISNULL([year], ''), 
						   COL12 = ISNULL((case WHEN [TYPE] = 1 then 'Исходная' when [TYPE] = 2 then 'Корректирующая' else 'Отменяющая'end), ''), 
						   COL13 = ISNULL([per_edt], ''), 
						   COL14 = ISNULL([year_edt], ''),
						   COL15 = @nom_pp,
						   COL16 = CONVERT(varchar(100),@FM),
						   COL17 = CONVERT(varchar(100),@IM),
						   COL18 = CONVERT(varchar(100),@OT),
						   0
					FROM 
						#SZV_ALL s LEFT JOIN #SALARY_SUM2_K ss ON ss.pers_link = s.link_face
					WHERE 
						S.NUM = 1 AND code = @CODE and [TYPE] = @TYPE AND PFNUMBER = @PFNUMBER and FM = @FM					
					GROUP BY 
						[TYPE],CODE, [T_DOG],[FM],[IM],[OT],[PFNUMBER],[per],[year],[per_edt],[year_edt],[INSUR],[INC_M1],[INC_M2],[INC_M3],[B_BEF_M1],[B_BEF_M2],[B_BEF_M3], [B_AFT_M1],[B_AFT_M2],[B_AFT_M3],SS.SUMMA_ALL_I, SS.SUMMA_NO, SS.SUMMA_NO_I, SS.SUMMA_NO_E
					
					set @nom_pp = @nom_pp + 1
					
					INSERT INTO #TMP1 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL10, COL11, COL12, COL13,COL14, COL15, COL16,COL17, COL18, COL44)
					SELECT CODE = @nom_pp,
						   COL1 = @nom_pp,	
						   COL2 = ISNULL([PFNUMBER],0),
						   COL3 = CONVERT(VARCHAR(100), '1 месяц'),
						   COL4 = CONVERT(VARCHAR(4),'411'),
						   COL5 = CONVERT(VARCHAR(4),@CODE),
						   COL6 = SUM([INC_M1]),
						   COL7 = SUM([B_BEF_M1]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M1] ELSE 0 END),
						   COL9 = SUM([B_AFT_M1]),
						   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 and per_edt = @per_edt1
					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 = SUM([INC_M2]),
						   COL7 = SUM([B_BEF_M2]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M2] ELSE 0 END),
						   COL9 = SUM([B_AFT_M2]),
						   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 AND per_edt = @per_edt1
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]
										
					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 = SUM([INC_M3]),
						   COL7 = SUM([B_BEF_M3]),
						   COL8 = SUM(CASE WHEN T_DOG = 2 THEN [B_BEF_M3] ELSE 0 END),
						   COL9 = SUM([B_AFT_M3]),
						   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 AND  per_edt = @PER_EDT1
					GROUP BY [PFNUMBER],[per],[year],[TYPE],[per_edt],[year_edt]
										
					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	
					--exec [dbo].RSA_RSV_1_PERS_UCH_SZV '20141001', '20141231', 74578 ,1,  2190
		
				end 
			
					set @pf_num1 = @PFNUMBER
					set @CODE_old = @CODE
					set @TYPE_OLD = @TYPE
					SET @PER_OLD = @PER_EDT1
			END

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

		CLOSE @Cur2
		DEALLOCATE @Cur2
       
		SELECT DISTINCT 
			CODE = ROW_NUMBER() OVER (ORDER BY CODE),
			COL1 = ROW_NUMBER() OVER (ORDER BY 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, COL45	
		FROM #TMP1 where col5 <> '' ORDER BY  CODE, COL15
		
	drop table #SALARY_SUM2_K
	drop table #SPR_ESN1_K			
	drop table #SPR_ESN1
	drop table #SALARY_SUM2
	drop table #TMP1

	END  


	IF @REP = 2 
	BEGIN 	
		/*Информация по раздеру 6.6 Информация о корректирующих сведениях*/
		/*К Исходным  заполняется в формах  с типом сведений «исходная» в случае, если в последние три месяца отчетного периода плательщиком страховых взносов 
		* корректируются данные, представленные в предыдущие отчетные периоды.При наличии данных в подразделе 6.6 дополнительно, 
		* в обязательном порядке предоставляются корректирующие (отменяющие)  разделы 6 и (или)  формы СЗВ-6-1, и (или) СЗВ-6-2, и (или) СЗВ-6-4.
		*/
		/*Заполняются в исходных , если есть по ним корректирующие */
	
		--- Обьявляем даты корректирующих сведений
			DECLARE @BYDateK	datetime , @nYEAR_K INT, @nMON1 INT, @nMON2 INT, @nMON3 INT
	

			select top 1 
			@BYDateK = (convert(varchar(4),YEAR_EDT)+'0101'),
			@nYEAR_K = YEAR_EDT,
			@nMON1 = (case  PER_EDT when 1 then  1 when 2 then  4 when 3 then  7 when 4 then  10 else 10 end)
			from #SZV_ALL WHERE [TYPE] = 2
			
			SELECT  @nMON2 = @nMON1 +1 , 	
					@nMON3 = @nMON1 +2 	
					
----------<<<<<<<<< #SPR_ESN для определения скидочной части (кусок ИЗ РСВ)

		/*Корректирующие сведения по физ лицам*/
		SELECT year_edt = p.YEAR_EDT, 
				PER_EDT = p.PER_EDT, 
				link_dep = p.link_dep,
				link_pers = s.link_pers,
				Link_kateg = case when S.Link_kateg = 3 then 1 else S.Link_kateg  end ,
				pachka = s.pachka
		INTO #tmp_pers
		FROM 	dbo.SA_SZV4_PACHKA P 
				INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up 															
		where
			P.link in (select link from #DOCS WHERE vid_kor = 2)
			and P.proverka = 1
			and P.vid_kor > 1
			and p.link_dep = @DEP_LINK


		CREATE TABLE #tmp_pers_kor_sum (link INT  , [date] DATETIME, YEAR_degin INT , per INT , vid_kor int, link_dep INT , proverka INT  , CODE VARCHAR(5), link_pers INT , 
										sum_doh NUMERIC(18,2), sum_str NUMERIC(18,2), sum_nak NUMERIC(18,2),sum_dop NUMERIC(18,2) , pachka int) 
	
		DECLARE @Cur_R2 CURSOR, @link int ,@LINK_pers INT, @year_edt INT , @per_edt INT , @Link_kateg INT ,@pachka int
		SET @Cur_R2 = CURSOR FORWARD_ONLY

		FOR SELECT LINK_pers, year_edt, per_edt, Link_kateg ,pachka FROM #tmp_pers ORDER by link_pers

		OPEN @Cur_R2
		FETCH NEXT FROM @Cur_R2 INTO @LINK_pers, @year_edt, @per_edt , @link_kateg, @pachka
		WHILE (@@fetch_status <> -1)
		BEGIN

			IF (@@fetch_status <> -2)
			BEGIN
				
				
					SET @link = 0
					
					SELECT @link =max(pp.link)
					FROM SA_SZV4_PACHKA pp 
					INNER JOIN dbo.SZV4_SVEDENIA Ss ON ss.link_up = pp.link  
					WHERE  pp.proverka = 1 AND pp.vid_kor = 1 
										  AND pp.link_dep = @DEP_LINK 
										  AND pp.year_begin =@year_edt  
										  AND pp.PER =@per_edt 
										  AND @LINK_pers = ss.link_pers
										  --AND @link_kateg = ss.link_kateg  
										  AND pp.date = (SELECT MAX(p1.[date]) FROM SA_SZV4_PACHKA p1 
																INNER JOIN dbo.SZV4_SVEDENIA S1 ON s1.link_up = p1.link  
																WHERE  pp.proverka = 1 AND p1.vid_kor = 1 
																					  AND p1.link_dep = @DEP_LINK 
																					  AND p1.year_begin =@year_edt  
																					  AND p1.PER =@per_edt 
																					  AND @LINK_pers = s1.link_pers
																					  /*AND @link_kateg = s1.link_kateg*/ )
					
					INSERT INTO #tmp_pers_kor_sum (link, [date], YEAR_degin, per, vid_kor, link_dep, proverka , CODE, link_pers, 
										sum_doh, sum_str, sum_nak,sum_dop, pachka) 
					SELECT pp.link, pp.[date], pp.YEAR_begin, pp.per, pp.vid_kor, pp.link_dep, pp.proverka, CODE = k.code, ss.link_pers, 
										ss.sum_doh, ss.sum_str, ss.sum_nak,ss.sum_dop , pachka = @pachka
					FROM SA_SZV4_PACHKA pp 
					INNER JOIN dbo.SZV4_SVEDENIA Ss ON ss.link_up = pp.link  
					INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = ss.LINK_KATEG AND pp.YEAR_begin BETWEEN YBEG AND YEND		
					WHERE pp.link = @link and pp.proverka = 1 
										 AND pp.vid_kor = 1 
										 AND pp.link_dep = @DEP_LINK 
										 AND pp.year_begin =@year_edt  
										 AND pp.PER =@per_edt 
										 AND ss.link_pers = @LINK_pers
										/* AND ss.link_kateg = @link_kateg*/
										  

			END

			FETCH NEXT FROM @Cur_R2 INTO @LINK_pers, @year_edt, @per_edt, @link_kateg, @pachka
		END

		CLOSE @Cur_R2
		DEALLOCATE @Cur_R2
--exec [dbo].RSA_RSV_1_PERS_UCH_SZV '20141001', '20141231', 74578 ,1,  2191


---------->>>>>>>>>>
		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 = /*case when YEAR_EDT between '2011' and '2013'  then (case*/ [PER_EDT]/* when 1 then 1 when 2 then 2 when 3 then 3 when 4 then 4 else 0 end)
							when YEAR_EDT = '2014' then (case [PER_EDT] when 1 then 3 when 2 then 6 when 3 then 9 when 4 then 0 else null end) end */, 
			   COL3 = CONVERT(VARCHAR(4),YEAR_EDT),
			   COL4 = (CASE WHEN YEAR_EDT = '2014' THEN INSUR - (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum WHERE CODE = 'НР' AND LINK_pers = s.link_face AND  per = s.per_edt )  ELSE 0 END ),
			   COL5 = (CASE WHEN YEAR_EDT < '2014' THEN INSUR - (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum WHERE CODE = 'НР' AND LINK_pers = s.link_face  AND  per = s.per_edt )  ELSE 0 END ),
			   COL6 = (CASE WHEN YEAR_EDT < '2014' THEN GAIN - (SELECT SUM(SUM_NAK) FROM #tmp_pers_kor_sum WHERE CODE = 'НР' AND LINK_pers = s.link_face AND  per = s.per_edt )   ELSE 0 END ),
			   COL7 = CONVERT(VARCHAR(14),PFNUMBER)
		FROM #SZV_ALL s WHERE  [TYPE] = 2 AND id_ex =1 
		GROUP BY link_face, YEAR_EDT,  [PER_EDT] , INSUR , GAIN ,[FM],[IM],[OT], PFNUMBER 
		ORDER BY [FM],[IM],[OT],[PFNUMBER]
		
		UPDATE #TMP2 
			SET col1 = CODE , COL8 = CODE 

		
		SELECT * FROM #TMP2 ORDER BY CODE


		drop table #tmp_pers
		drop table #tmp_pers_kor_sum
		--DROP TABLE #SPR_ESN_K
		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 @BYear_Date	datetime
			SET @BYear_Date = dbo.DateBeginOfYear (@dDate1)

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

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

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


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


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

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


		
		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

	--exec [dbo].RSA_RSV_1_PERS_UCH_SZV '20150401', '20150630', 74578 ,3,  2811
	
		SET @Cur3 = CURSOR FORWARD_ONLY
		FOR SELECT  [CODE],[TYPE],[PFNUMBER], [FM],[IM],[OT], [OSOB_SPO]  
			FROM #SZV_ALL 
			where [TYPE] = 1  --AND ISNULL([OSOB_SPO],'') <> '' 
			GROUP BY [FM],[IM],[OT],[PFNUMBER],[TYPE],CODE,id_ex, [OSOB_SPO] 
			ORDER BY [FM],[IM],[OT],[PFNUMBER],[TYPE],CODE,id_ex, [OSOB_SPO]
		OPEN @Cur3
		FETCH NEXT FROM @Cur3 INTO  @CODE1,@TYPE1,@PFNUMBER1,@FM1,@IM1,@OT1, @OSOB_SPO
		WHILE (@@fetch_status <> -1)
		BEGIN

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

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


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

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

					set @nom_pp1 = @nom_pp1 + 1		
					
					INSERT INTO #TMP3 (CODE, COL1, COL2, COL3, COL4, COL5, COL6, COL7, COL8, COL9, COL42 , COL43, COL44)
					SELECT CODE =  @nom_pp1,
						   COL1 =  @nom_pp1,	
						   COL2 = CONVERT(VARCHAR(100), '3 месяц'),	
						   COL3 = CONVERT(VARCHAR(4),'713'),
						   COL4 = CONVERT(VARCHAR(4),''),
						   COL5 = 0,
						   COL6 = 0,
						   COL7 = ISNULL(@PFNUMBER1,''),
						   COL8 = @nom_pp1,
						   COL9 = @TYPE1,
						   COL42 = CONVERT(varchar(100),@FM1),
						   COL43 = CONVERT(varchar(100),@IM1),
						   COL44 = CONVERT(varchar(100),@OT1)
	
					set @nom_pp1 = @nom_pp1 + 1	
				end 

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

					from #TMP3	
					WHERE #TMP3.COL9 = @TYPE1 
					and #TMP3.COL7 = @PFNUMBER1 AND #TMP3.COL3 = '700' /*and #TMP3.CODE =  @nom_pp1*/


					drop table #TMP03				


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

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

		CLOSE @Cur3
		DEALLOCATE @Cur3
		
		
		
		
		/*****************************************************/
		-- Собираем информацию по Кореектирующим/Отменяющим
		/*****************************************************/
		--create table #TMP1(CODE int,col1 int,   COL2 varchar(14), COL3 varchar(100), COL4 varchar (4), COL5 varchar (4), COL6 numeric(18,2), COL7 numeric(18,2), COL8 numeric(18,2), COL9 numeric(18,2), COL10 varchar(1), COL11 varchar(4), COL12 varchar(15), COL13 varchar(1), COL14 varchar(4),COL15 int)
	

		DECLARE @Cur4 CURSOR
		set @pf_num11 = ''
		set @OSOB_SPO_old = ''  
		set @TYPE_OLD1 = 0
		set @nom_pp1 = (SELECT MAX(CODE) FROM #TMP3 WHERE COL9 = 1) + 1 
		
				
		SET @Cur4 = CURSOR FORWARD_ONLY
		FOR SELECT  [CODE],[TYPE],[PFNUMBER], [FM],[IM],[OT], [OSOB_SPO]  FROM #SZV_ALL where /*T_DOG = 1 and */[TYPE] != 1 and year_edt >=2014  GROUP BY [CODE],[TYPE],[PFNUMBER], [FM],[IM],[OT], [OSOB_SPO]ORDER BY [CODE],[TYPE],[PFNUMBER], [FM],[IM],[OT], [OSOB_SPO]
		OPEN @Cur4
		FETCH NEXT FROM @Cur4 INTO  @CODE1,@TYPE1,@PFNUMBER1,@FM1,@IM1,@OT1, @OSOB_SPO
		WHILE (@@fetch_status <> -1)
		BEGIN

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

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

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

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


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

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

					drop table #TMP04	


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

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

		CLOSE @Cur4
		DEALLOCATE @Cur4
		
		SELECT DISTINCT 
			CODE = ROW_NUMBER() OVER (ORDER BY CODE),
			COL1 = ROW_NUMBER() OVER (ORDER BY 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, COL45, COL46
		FROM #TMP3 where col5 <> 0 or col6 <> 0 or ISNULL(COL10,'') <> '' ORDER BY CODE, COL8

--RSA_RSV_1_PERS_UCH_szv '20140401', '20140630', 13488 , 3, 2786
		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(30), 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(30),ISNULL([OS_CODE],'')),
			   COL6 = CONVERT(VARCHAR(10),ISNULL([EX_CODE],'')),
			   COL7 = CONVERT(VARCHAR(100),ISNULL([f_is_dop],'')),
			   COL8 = CONVERT(VARCHAR(10),ISNULL([P_CODE],'')),
			   COL9 = CONVERT(VARCHAR(100),ISNULL([f_ud_dop],'')),
			   COL10 = CONVERT(VARCHAR(100),ISNULL([PFNUMBER],'')),
			   COL12 = ISNULL([TYPE],0),
			   COL13 = CONVERT(varchar(100),FM),
			   COL14 = CONVERT(varchar(100),IM),
			   COL15 = CONVERT(varchar(100),OT)
		FROM #SZV_ALL 
		WHERE 
			id_ex IS NOT NULL AND YEAR(@dDate1)<=YEAR(Date_END) and MONTH(@dDate2) >= MONTH(Date_END) and MONTH(@dDate2) >= MONTH(Date_BEGIN)
		GROUP BY 
			[FM],[IM],[OT],[PFNUMBER],[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],[TYPE]

		UPDATE #TMP4 
			SET col1 = CODE , COL11 = CODE 

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

END





GO


GRANT EXECUTE ON dbo.[RSA_RSV_1_PERS_UCH_SZV] TO PUBLIC

GO


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

GO

CREATE PROCEDURE dbo.BK_EXPORT_F1152027 (@iLINK_FORM INT)
AS
BEGIN

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

	DECLARE @FNAME VARCHAR (254),
		@FNAME_ID VARCHAR (254),
-- exec BK_EXPORT_F1152027 20026

		@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),
		@POST_GL_BUH	VARCHAR (254),
		@DEP_NAME VARCHAR (254),

		@DOC_ID		VARCHAR (36),

		@NAME_RUK	VARCHAR (60),
		@FAM_RUK	VARCHAR (60),
		@OT_RUK		VARCHAR (60),

		@NAME_GL_BUH	VARCHAR (60),
		@FAM_GL_BUH	VARCHAR (60),
		@OT_GL_BUH	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 (30),
		@OKATO VARCHAR (15),
		@OKATO_D VARCHAR (15),
		@SUMMA	NUMERIC (15,0),
		@NUM_KOR NUMERIC (20),

		@LINK_COL_CODE INT,

		--- Раздел 2 ---
		@LINK_COL_VIDTS	INT,
		@LINK_COL_VIN	INT,
		@LINK_COL_MARKA	INT,
		@LINK_COL_REGNO	INT,
		@LINK_COL_NALBAS INT,
		@LINK_COL_OKEI	INT,
		@LINK_COL_SROK	INT,
		@LINK_COL_K3623	INT,
		@LINK_COL_STAVKA INT,
		@LINK_COL_SUM_IS	INT,
		@LINK_COL_LGOTA	INT,
		@LINK_COL_SUM_LGOTA	INT,
		@LINK_COL_SUM_UPL	INT,

		@strEXEC	VARCHAR (8000)
	--- ---
	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

	SET @cPERIOD_NUM = CASE WHEN @PERIOD_NUM = 1 THEN '21'
							WHEN @PERIOD_NUM = 2 THEN '22'
							WHEN @PERIOD_NUM = 3 THEN '23'
		END

	EXEC dbo.GetRandStr 36, @DOC_ID OUTPUT

	SELECT @PART_NAME_NNN = @DOC_ID

	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],
			@OKATO_D = CONVERT (VARCHAR (11), REPLACE (OKATO, ' ', ''))
	FROM dbo.DICTIONARY_DEPARTMENT
	WHERE LINK = @DEP_LINK

	SELECT @TLF_GL_BUH = A.PHONE,
		@POST_GL_BUH = B.POST_NAME,

		@NAME_GL_BUH = B.IM,
		@FAM_GL_BUH = B.FM,
		@OT_GL_BUH = B.OT

	FROM dbo.DICTIONARY_OTV_FACE A
	LEFT JOIN dbo.KU_EMPL_PLACING B ON (B.LINK = A.FACE_LINK)
	WHERE A.DEP_LINK = @DEP_LINK
		AND A.[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)
	WHERE RSF.LINK_SAVED_FORM = @iLINK_FORM
		AND ORDERS = 2

	CREATE TABLE #TABLE1 (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(100),	-- 
		FCOL2 VARCHAR (1000),
		COL3 NUMERIC (20), 	-- 
		FCOL3 VARCHAR (1000),
		COL4 NUMERIC(20), 	-- 
		FCOL4 varchar (1000),
		COL5 NUMERIC(20),	-- 
		FCOL5 VARCHAR (1000),
		ITOG NUMERIC(20))
	
	IF @iLINK_TABLE > 0
	BEGIN
		SET @strEXEC = 'INSERT INTO #TABLE1 (CHECKED, UPD, DEL, LINK_SAVED_FORM, LINK_ROW, ORDERS, 
					CALC_ORDERS, PRINT_NULL, CODE, COL1, COL2, FCOL2, COL3, FCOL3, COL4, FCOL4, 
					COL5, FCOL5, ITOG)
				EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
					+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'
		EXECUTE (@strEXEC)
	END

	SELECT @KBK = COL4,
		@OKATO = COL2,
		@SUMMA = COL3,
		@NUM_KOR = COL5
	FROM #TABLE1

	-- ДАННЫЕ РАЗДЕЛА 2 --
	-- !!!Расчет!!! --
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM 	(select *, CASE WHEN ORDERS = 1 THEN 2 WHEN ORDERS = 2 THEN 1 END AS REAL_ORD
		from report_tables
		where link_form = (select link_form
							from report_saved_forms
							where link_saved_form=@iLINK_FORM)) AS T
	WHERE REAL_ORD = 2

	CREATE TABLE #TEMP (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(100),	-- ВИД ТС
		FCOL2 VARCHAR,
		COL3 VARCHAR (100), 	-- ВИН
		FCOL3 VARCHAR,
		COL4 VARCHAR(100), 	-- МАРКА ТС
		FCOL4 varchar,
		COL5 VARCHAR(100),	-- РЕГ. НОМЕР
		FCOL5 VARCHAR,
		COL6 NUMERIC(20,2), 	-- НАЛ. БАЗА
		FCOL6 VARCHAR,
		COL7 VARCHAR(50),	-- ОКЕИ
		FCOL7 VARCHAR,
		COL8 NUMERIC(20,0),	-- СРОК
		FCOL8 VARCHAR,
		COL9 NUMERIC(20,2),	-- К3623
		FCOL9 VARCHAR,
		COL10 NUMERIC(20,2),	-- СТАВКА
		FCOL10 VARCHAR,
		COL11 NUMERIC(20,2),	-- СУМ. ИСЧИСЛ.
		FCOL11 VARCHAR,	
		COL12 VARCHAR(50),	-- КОД НАЛ. ЛЬГОТЫ 
		FCOL12 VARCHAR,
		COL13 NUMERIC(20,2),	-- СУМ. НАЛ. ЛЬГОТЫ 
		FCOL13 VARCHAR,
		COL14 NUMERIC(20,2),	-- СУМ. УПЛ.
		FCOL14 VARCHAR) 
	
	SET @strEXEC = 'INSERT INTO #TEMP (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, COL13, FCOL13, COL14, FCOL14)
			EXEC dbo.RI_PROC_T' + LTRIM (STR (@iLINK_TABLE))
				+ ' ' + LTRIM (STR (@iLINK_FORM)) + ', 0'

	EXECUTE (@strEXEC)
	
	--- Формирование XML ---
	SELECT @FNAME_ID = 'NO_TRANA_' + 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" xsi:noNamespaceSchemaLocation="NO_TRANA_1_077_00_04_01_01.XSD"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ИдФайл="' + RTRIM (@FNAME_ID) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсФорм="4.01"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ТипИнф="ТРАНА"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВерсПрог="' + RTRIM (LEFT (@NAME_PROG, 40)) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КолДок="1">')

-- Сведения об отправителе	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ИдОтпр ДолжОтв="'
		+ RTRIM (LEFT (ISNULL (@POST_GL_BUH, ''), 45)) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Тлф="' + RTRIM (ISNULL (@TLF_GL_BUH, '')) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'E-mail="">')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ФИООтв')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, ' Фамилия="' + RTRIM (ISNULL (@FAM_GL_BUH, '')) 
					+ '" Имя="' + RTRIM (ISNULL (@NAME_GL_BUH, '')) + '"'
					+ CASE WHEN ISNULL (@OT_GL_BUH, '') <> '' THEN ' Отчество="'
											+ RTRIM (ISNULL (@OT_GL_BUH, '')) + '"'
							ELSE '' END
					+ '/>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ИдОтпр>')

-- Документ
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<Документ ИдДок="' + @DOC_ID + '">')

	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, 'ОКВЭД="' + 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, '<СвРукОрг')
	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, '<ОписПерСвед КНД="1152027"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ВидДок="' + CONVERT (VARCHAR (10), ISNULL (@NUM_KOR, 0)) + '"')
	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, 'ДатаДок="' + CONVERT (VARCHAR (10), GETDATE (), 104) + '"')
	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 (@OKATO, '') = '' 
											THEN ISNULL (@OKATO_D, '')
										ELSE @OKATO END + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'СумУплБюдж="' + LTRIM (STR (ISNULL (@SUMMA, 0))) + '">')
	
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT)
	SELECT @FNAME,
		'<РасчНалТС КодВидТС="' + CONVERT (VARCHAR (5), ISNULL (COL2, '')) + '"'
		+ ' ИдНомТС="' + CONVERT (VARCHAR (25), ISNULL (RTRIM (COL3), '')) + '"'
		+ ' МаркаТС="' + CONVERT (VARCHAR (120), ISNULL (RTRIM (COL4), '')) + '"'
		+ ' РегЗнакТС="' + CONVERT (VARCHAR (30), ISNULL (RTRIM (COL5), '')) + '"'
		+ ' НалБаза="' + LTRIM (STR (ISNULL (COL6, 0), 15, 2)) + '"'
		+ ' ОКЕИНалБаза="' + CONVERT (VARCHAR (30), ISNULL (RTRIM (COL7), '' )) + '"'
		+ ' СрокИспольз="' + LTRIM (STR (ISNULL (COL8, 0), 3)) + '"'
		+ ' Коэф3623="' + LTRIM (STR (ISNULL (COL9, 0), 3, 2)) + '"'
		+ ' НалСтавка="' + LTRIM (STR (ISNULL (COL10, 0), 8, 2)) + '"'
		+ ' СумИсчисл="' + LTRIM (STR (ISNULL (COL11, 0), 15)) + '"'
		+ CASE WHEN ISNULL (RTRIM (COL12), '' ) = ''
			THEN ''
			ELSE ' КодНалЛьг="' + CONVERT (VARCHAR (5), ISNULL (RTRIM (COL12), '' )) + '"'
		END	
		+ ' СумНалЛьг="' + LTRIM (STR (ISNULL (COL13, 0), 15)) + '"'
		+ ' СумИсчислУпл="' + LTRIM (STR (ISNULL (COL14, 0), 15)) + '"'
		+ '/>'
	FROM #TEMP 

	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 #TASK_PROP

	DROP TABLE #TEMP
	DROP TABLE #TABLE1 
END 

GO


GRANT EXECUTE ON dbo.[BK_EXPORT_F1152027] TO PUBLIC

GO



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

GO

CREATE PROCEDURE [dbo].BK_EXPORT_F1152028 (@iLINK_FORM INT)
AS
BEGIN

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

	DECLARE @FNAME VARCHAR (254),
		@FNAME_ID VARCHAR (254),
-- BK_EXPORT_F1152028  12533

			@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),

			@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),

			@LINK_COL_CODE	INT,
			@LINK_COL_SUM	INT,
			@LINK_COL_STAVKA	INT,
			@LINK_COL_LGOT	INT,

			--- Раздел 1 ---
			@KBK VARCHAR (30),
			@OKATO VARCHAR (15),
			@OKATO_D VARCHAR (15),
			@SUMMA	NUMERIC (15,0),

			--- Раздел 2 ---
			@ST_IMUSH	NUMERIC (15,0),
			@CODE_NL	VARCHAR (7),
			@ST_IMUSH_NO NUMERIC (15,0),
			@Dol_ST	VARCHAR (21),
			@CODE_LG_PNS VARCHAR (7),
			@NAL_STAV	NUMERIC (3,2),

			@SumAV	NUMERIC (15),
			@CODE_LG_UM	VARCHAR (7),
			@SUM_LG_UM NUMERIC (15),

			@LINK_COL1	INT,
			@LINK_COL3	INT,
			@LINK_COL4	INT

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

	SET @cPERIOD_NUM = CASE WHEN @PERIOD_NUM = 1 THEN '21'
							WHEN @PERIOD_NUM = 2 THEN '31'
							WHEN @PERIOD_NUM = 3 THEN '33'
		END

	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],
			@OKATO_D = CONVERT (VARCHAR (11), REPLACE (OKATO, ' ', ''))
	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 	(select *, CASE WHEN ORDERS = 1 THEN 2 WHEN ORDERS = 2 THEN 3
		WHEN ORDERS = 3 THEN 1 END AS REAL_ORD
		from report_tables
		where link_form = (select link_form
							from report_saved_forms
							where link_saved_form=@iLINK_FORM)) AS T
	WHERE REAL_ORD = 1

	SELECT @KBK = KBK, @OKATO = OKATO, @SUMMA = SUMMA
	FROM
	(SELECT (SELECT CONVERT (VARCHAR (30), Str_Val) FROM dbo.REPORT_STRING
				WHERE LINK_SAVED_FORM = @iLINK_FORM
				AND LINK_COL = (SELECT RC1.LINK_COL FROM dbo.REPORT_COLOUMNS RC1 WHERE RC1.LINK_TABLE = @iLINK_TABLE
									AND UPPER (RC1.[NAME]) = 'КОД БК')
				) AS KBK,
		(SELECT CONVERT (VARCHAR (20), Str_Val) FROM dbo.REPORT_STRING
					WHERE LINK_SAVED_FORM = @iLINK_FORM
					AND LINK_COL = (SELECT RC1.LINK_COL FROM dbo.REPORT_COLOUMNS RC1 WHERE RC1.LINK_TABLE = @iLINK_TABLE
										AND UPPER (RC1.[NAME]) = 'КОД ПО ОКАТО')
					) AS OKATO,
		(SELECT CONVERT (NUMERIC (15), SUMMA) FROM dbo.REPORT_SUMMA
					WHERE LINK_SAVED_FORM = @iLINK_FORM
					AND LINK_COL = (SELECT RC1.LINK_COL FROM dbo.REPORT_COLOUMNS RC1 WHERE RC1.LINK_TABLE = @iLINK_TABLE
										AND UPPER (RC1.[NAME]) = 'ПОДЛЕЖИТ УПЛАТЕ')
					) AS SUMMA
	FROM dbo.REPORT_ROWS RR
	WHERE RR.LINK_TABLE = @iLINK_TABLE) AS T

	-- ДАННЫЕ РАЗДЕЛА 2 --
	-- !!!Расчет!!! --
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM 	(select *, CASE WHEN ORDERS = 1 THEN 2 WHEN ORDERS = 2 THEN 3
		WHEN ORDERS = 3 THEN 1 END AS REAL_ORD
		from report_tables
		where link_form = (select link_form
							from report_saved_forms
							where link_saved_form=@iLINK_FORM)) AS T
	WHERE REAL_ORD = 3

	SELECT @LINK_COL_CODE = RC1.LINK_COL
	FROM dbo.REPORT_COLOUMNS RC1
	WHERE RC1.LINK_TABLE = @iLINK_TABLE
		AND UPPER (RC1.[NAME]) = 'КОД СТРОКИ' 

	SELECT @LINK_COL_SUM = RC1.LINK_COL
	FROM dbo.REPORT_COLOUMNS RC1
	WHERE RC1.LINK_TABLE = @iLINK_TABLE
		AND UPPER (RC1.[NAME]) = 'ЗНАЧЕНИЕ ПОКАЗАТЕЛЕЙ' 

	SELECT @LINK_COL_STAVKA = RC1.LINK_COL
	FROM dbo.REPORT_COLOUMNS RC1
	WHERE RC1.LINK_TABLE = @iLINK_TABLE
		AND UPPER (RC1.[NAME]) = 'НАЛОГОВАЯ СТАВКА(%)' 

	SELECT @LINK_COL_LGOT = RC1.LINK_COL
	FROM dbo.REPORT_COLOUMNS RC1
	WHERE RC1.LINK_TABLE = @iLINK_TABLE
		AND UPPER (RC1.[NAME]) = 'КОД ЛЬГОТЫ/КОД ОКАТО' 

--	SELECT @KBK = KBK, @OKATO = OKATO, @SUMMA = SUMMA
	
	SELECT @ST_IMUSH = CONVERT (NUMERIC (15), SUMMA) FROM dbo.REPORT_SUMMA
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_SUM
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '120')

	SELECT @CODE_NL = CONVERT (VARCHAR (7), Str_Val) FROM dbo.REPORT_STRING
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_LGOT
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '130')

	SELECT @ST_IMUSH_NO = CONVERT (NUMERIC (15), SUMMA) FROM dbo.REPORT_SUMMA
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_SUM
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '140')

	SELECT @Dol_ST = CONVERT (VARCHAR (21), Str_Val) FROM dbo.REPORT_STRING
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_LGOT
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '150')

	SELECT @CODE_LG_PNS = CONVERT (VARCHAR (7), Str_Val) FROM dbo.REPORT_STRING
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_LGOT
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '160')

	SELECT @NAL_STAV = CONVERT (NUMERIC (3,2), SUMMA) FROM dbo.REPORT_SUMMA
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_STAVKA
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '170')

	SELECT @SumAV = CONVERT (NUMERIC (15,0), SUMMA) FROM dbo.REPORT_SUMMA
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_SUM
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '180')

	SELECT @CODE_LG_UM = CONVERT (VARCHAR (7), Str_Val) FROM dbo.REPORT_STRING
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_LGOT
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '190')

	SELECT @SUM_LG_UM = CONVERT (NUMERIC (15,0), SUMMA) FROM dbo.REPORT_SUMMA
					WHERE LINK_SAVED_FORM = @iLINK_FORM
						AND LINK_COL = @LINK_COL_SUM
						AND LINK_ROW = (SELECT RF.LINK_ROW FROM REPORT_FORMULA RF
											WHERE RF.LINK_COL = @LINK_COL_CODE
												AND RF.FORMULA = '200')

	--- Остаточная стоимость имущества по месяцам ---
	DECLARE @TABLE_R21 TABLE (COL1 VARCHAR (6), CODE VARCHAR (3),
				SUM_ALL NUMERIC (15,0), SUM_LG NUMERIC (15,0))

	SELECT @iLINK_TABLE = LINK_TABLE
	FROM 	(select *, CASE WHEN ORDERS = 1 THEN 2 WHEN ORDERS = 2 THEN 3
		WHEN ORDERS = 3 THEN 1 END AS REAL_ORD
		from report_tables
		where link_form = (select link_form
							from report_saved_forms
							where link_saved_form=@iLINK_FORM)) AS T
	WHERE REAL_ORD = 2

	SELECT @LINK_COL1 = RC1.LINK_COL
	FROM dbo.REPORT_COLOUMNS RC1
	WHERE RC1.LINK_TABLE = @iLINK_TABLE
		AND UPPER (RC1.[NAME]) = 'ПО СОСТОЯНИЮ НА' 

	SELECT @LINK_COL_CODE = RC1.LINK_COL
	FROM dbo.REPORT_COLOUMNS RC1
	WHERE RC1.LINK_TABLE = @iLINK_TABLE
		AND UPPER (RC1.[NAME]) = 'КОД СТРОКИ' 

	SELECT @LINK_COL3 = RC1.LINK_COL
	FROM dbo.REPORT_COLOUMNS RC1
	WHERE RC1.LINK_TABLE = @iLINK_TABLE
		AND UPPER (RC1.[NAME]) = 'ВСЕГО' 

	SELECT @LINK_COL4 = RC1.LINK_COL
	FROM dbo.REPORT_COLOUMNS RC1
	WHERE RC1.LINK_TABLE = @iLINK_TABLE
		AND UPPER (RC1.[NAME]) = 'В Т.Ч. СТОИМОСТЬ ЛЬГОТИРУЕМОГО ИМУЩЕСТВА' 

	INSERT INTO @TABLE_R21
	SELECT (SELECT CONVERT (VARCHAR (6), FORMULA)
					FROM dbo.REPORT_FORMULA RS
					WHERE RS.LINK_COL = @LINK_COL1
						AND RS.LINK_ROW = RF.LINK_ROW) AS COL1,
			CONVERT (VARCHAR (3), RF.FORMULA) AS CODE,
			(SELECT CONVERT (NUMERIC (15), SUMMA)
					FROM dbo.REPORT_SUMMA RS
					WHERE RS.LINK_SAVED_FORM = @iLINK_FORM
						AND RS.LINK_COL = @LINK_COL3
						AND RS.LINK_ROW = RF.LINK_ROW) AS SUM_ALL,
			(SELECT CONVERT (NUMERIC (15), SUMMA)
					FROM dbo.REPORT_SUMMA RS
					WHERE RS.LINK_SAVED_FORM = @iLINK_FORM
						AND RS.LINK_COL = @LINK_COL4
						AND RS.LINK_ROW = RF.LINK_ROW) AS SUM_LG
	FROM dbo.REPORT_FORMULA RF
	WHERE RF.LINK_COL = @LINK_COL_CODE

-- SELECT * FROM @TABLE_R21
--SELECT @ST_IMUSH, @CODE_NL, @ST_IMUSH_NO, @Dol_ST, @CODE_LG_PNS, @NAL_STAV 
-- BK_EXPORT_F1152028  12533
--	FROM dbo.REPORT_ROWS RR
--	WHERE RR.LINK_TABLE = @iLINK_TABLE) AS T

--	select @iLINK_TABLE, @LINK_COL_CODE, @LINK_COL_SUM, @LINK_COL_STAVKA, @LINK_COL_LGOT	

	--- Формирование 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'
-- SELECT @FNAME 
	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.01">')

-- Документ
	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, 'ОтчетГод="' + LTRIM (STR (YEAR (@dDATE_FORM))) + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'Период="' + @cPERIOD_NUM + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'КодНО="' + ISNULL (@IMNS, '') + '"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'НомКорр="0"')
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, 'ПоМесту="214">')

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

	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 (@OKATO, '') = ''
																			THEN ISNULL (@OKATO_D, '')
																			ELSE @OKATO 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, '<РасОб ВидИмущ="3">')

	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, '<СтоимМес>')
/*
SELECT SUM_ALL,
	CASE WHEN ISNULL (SUM_ALL, 0) = 0 THEN ''
		ELSE STR (SUM_ALL, 0) -- ' СтОст="' + LTRIM (STR (SUM_ALL, 0)) +'"'
	END
FROM @TABLE_R21
*/
	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) 
	SELECT @FNAME,
		'<ОстСтом' + REPLACE (RTRIM (COL1), '.', '')
				+ CASE WHEN ISNULL (SUM_ALL, 0) = 0 THEN ''
						ELSE ' СтОст="' + LTRIM (STR (SUM_ALL)) +'"'
					END
				+ CASE WHEN ISNULL (SUM_LG, 0) = 0 THEN ''
						ELSE ' СтЛьгИмущ="' + LTRIM (STR (SUM_LG)) +'"'
					END
				+ '/>'
	FROM @TABLE_R21

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</СтоимМес>')

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '</ДанРас>')
--SELECT @ST_IMUSH, @CODE_NL, @ST_IMUSH_NO, @Dol_ST, @CODE_LG_PNS, @NAL_STAV 

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<ОтчПер СумАвИсчисл="' + LTRIM (STR (ISNULL (@SumAV, 0))) + '"'
			+ CASE WHEN ISNULL (@CODE_LG_UM, '') = '' THEN ''
					ELSE ' КодЛгУмен="' + RTRIM (@CODE_LG_UM) + '"'
			END
			+ CASE WHEN ISNULL (@SUM_LG_UM, 0) = 0 THEN ''
					ELSE ' СумЛгУмен="' + RTRIM (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, '</РасОбДеятРФ>')

	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 #TASK_PROP
END 


GO


GRANT EXECUTE ON dbo.[BK_EXPORT_F1152028] TO PUBLIC

GO


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

GO
CREATE PROCEDURE dbo.BK_EXPORT_F1152028_502 (@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 (30),
		@OKATO VARCHAR (15),
		@OKATO_D 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),

		@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],
			@OKATO_D = CONVERT (VARCHAR (11), REPLACE (OKATO, ' ', ''))
	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 = 3)
	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, ''),
		@OKATO = 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 --
	-- Данные раздела 1.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_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 = 2)
	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 @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'

	--- Формирование 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.02">')

-- Документ

	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 (@OKATO, '') = ''
											THEN ISNULL (@OKATO_D, '')
											ELSE @OKATO 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, '</СтоимМес>')

	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, '</РасОбДеятРФ>')

	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 #TASK_PROP
END 


GO


GRANT EXECUTE ON dbo.[BK_EXPORT_F1152028_502] 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 (30),
		@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 = FULL_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

	IF ISNULL (@strNUM_COR, '') = ''
		SET @strNUM_COR = '0'

	-- ДАННЫЕ РАЗДЕЛА 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, 'НалПУ="' + CONVERT (VARCHAR (20), 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, '<ДанРас СтИмущ="' + CONVERT (VARCHAR (20), ISNULL (@ST_IMUSH, 0)) + '"'
			+	CASE WHEN ISNULL (@CODE_NL, '') = '' THEN ''
					ELSE ' КодНалЛьг="' + @CODE_NL + '"'
				END
			+	CASE WHEN ISNULL (@ST_IMUSH_NO, 0) = 0 THEN ''
					ELSE ' СтИмущНеобл="' + CONVERT (VARCHAR (20), @ST_IMUSH_NO) + '"'
				END
			+	CASE WHEN ISNULL (@Dol_ST, '') = '' THEN ''
					ELSE ' ДолСт="' + @Dol_ST + '"'
				END
			+	CASE WHEN ISNULL (@CODE_LG_PNS, '') = '' THEN ''
					ELSE ' КодЛгПНС="' + @CODE_LG_PNS + '"'
				END
			+	' НалСтав="' + CONVERT (VARCHAR (5), ISNULL (@NAL_STAV, 0.0)) + '"'
			+ '>')

	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 ' СтОстОН="' + CONVERT (VARCHAR (20), COL3) +'"'
			END
		+ CASE WHEN ISNULL (COL4, 0) = 0 THEN ''
				ELSE ' СтЛьгИмущ="' + CONVERT (VARCHAR (20), COL4) +'"'
			END
		+ '/>'
	FROM #TAB_R21

	INSERT INTO @OUTPUT (F_NAME, OUT_TEXT) VALUES (@FNAME, '<СтОстВс>' + CONVERT (VARCHAR (20), 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 ' СумЛгУмен="' + CONVERT (VARCHAR (20), 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.[SA_REP_RL_ONE]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE dbo.[SA_REP_RL_ONE]

GO

CREATE     PROCEDURE dbo.SA_REP_RL_ONE
	@varKScYear VARCHAR(4),
	@varKSnMonth INT,
	@varKScVal1 CHAR(1), @varKSnOtborLink1 int,	
	@varKSnOption1 int,
	@nCheck3 int,	/* Разделять Б/Л за счет ФСС и работодателя */
	@nLinkEmpl int = 0,
	@nCheckIST INT = 0,
	@nCheck5 int = 0, /* Печатать пустые р/л*/
	@nCheck7 int = 0, /* Отображать разряд */
	@varKScVal2 CHAR(1) = '', @varKSnOtborLink2 int = 0,
	@nCheck8 int = 0 /* Выводить Ф.И.О. полностью */,
	@nCheck9 int = 0 , /* Выводить наименование отдела вместо кода */
	@nCheck10 int = 0  /* Формировать р/л за каждый месяц с начала года по выбранный месяц */
as


create table #date (
ID int, 
LINK_EMPL1 int, 
FIO  VARCHAR(254), 
TN VARCHAR(15), 
[STATUS] VARCHAR(20),
MON TINYINT,
SUBDIV VARCHAR(254), 
POST VARCHAR(50), 
OKLAD NUMERIC(20,2), 
FWT INT, 
REST_BEG NUMERIC(20,2), 
REST_D NUMERIC(20,2), 
SUM_TOTAL NUMERIC(20,2), 
DEDUCT NUMERIC(20,2), 
NDFL NUMERIC(20,2), 
INSUR NUMERIC(20,2), 
GAIN NUMERIC(20,2), 
NUM int, 
LINK_EMPL int, 
DAYS numeric (15,2), 
PERC numeric (15,2),
CODE_PAY VARCHAR(10), 
NAME_PAY VARCHAR(254), 
SUM_PAY NUMERIC(20,2), 
CODE_TAX VARCHAR(10), 
NAME_TAX VARCHAR(254), 
SUM_TAX NUMERIC(20,2), 
ORDERS TINYINT, 
VKR_CODE VARCHAR(30),
VKR_NAME VARCHAR(120),
VKR_ALL VARCHAR(300),
NAME  VARCHAR(254)
)

set nocount on

insert into #date 
EXEC dbo.SD_REP_RL
	@varKScYear,
	@varKSnMonth,
	@varKScVal1, 
	@varKSnOtborLink1,
	@varKSnOption1,
	@nCheck3,
 	@nLinkEmpl,
	@nCheckIST,
	@nCheck5,
	@nCheck7,
	@varKScVal2, @varKSnOtborLink2,
	@nCheck8,
	@nCheck9, /* Выводить наименование отдела вместо кода */
	@nCheck10 /* Формировать р/л за каждый месяц с начала года по выбранный месяц */

update #date
Set num = CEILING(CAST([ID] AS FLOAT ) / 4.0) /*4 штуки на листке*/


/*Условно разделим на 2 части и подравняем длинну двух соседних листочков*/

declare @Cursor Cursor
Set @cursor = cursor forward_only
for 
	Select distinct 
	lid= D.id,
	lcnt= (select count(id) from  #date D1 where d1.id = d.id),
	rid = D.id + 1 ,
	rcnt= (select count(id) from  #date D1 where d1.id = d.id + 1)
from #date D where id % 2 = 1

declare @lid int, @lcnt int, @rid int, @rcnt int, @i int

open @cursor
fetch next  from @Cursor  into @lid, @lcnt, @rid, @rcnt
while (@@fetch_status <> -1)
begin
	if (@@fetch_status <> 2)
	begin	
		Set @i = abs (@lcnt - @rcnt)
		while @i > 0
		begin	
			insert into #date (id, LINK_EMPL1, FIO, TN, [STATUS],  MON, SUBDIV, POST, OKLAD, FWT, REST_BEG, REST_D, SUM_TOTAL, DEDUCT, NDFL, INSUR, GAIN, NUM, ORDERS, VKR_ALL)
			Select top 1 id, LINK_EMPL1, FIO, TN,[STATUS], MON, SUBDIV, POST, OKLAD, FWT, REST_BEG, REST_D, SUM_TOTAL, DEDUCT, NDFL, INSUR, GAIN, NUM,  21, VKR_ALL
				from #date where id = (case when @lcnt < @rcnt then @lid else @rid end)

			Set @i = @i - 1
		end
	end
	fetch next  from @Cursor  into @lid, @lcnt, @rid, @rcnt
end
close @cursor
deallocate @cursor

/*Листочек на левой стороне*/
Select link = identity(int,1,1), *
into #left
from #date D where id % 2 = 1
order by id, ORDERS, CODE_PAY

/*Листочек на правой стороне*/
Select link = identity(int,1,1), 
	rID= ID, rLINK_EMPL1 = LINK_EMPL1, rFIO = FIO, rTN = TN, rSTATUS = [STATUS], rMON = MON, rSUBDIV = SUBDIV, 
	rPOST = POST, rOKLAD = OKLAD, rFWT = FWT, rREST_BEG = REST_BEG, rREST_D = REST_D, 
	rSUM_TOTAL = SUM_TOTAL, rDEDUCT = DEDUCT, rNDFL = NDFL, rINSUR = INSUR, rGAIN = GAIN, 
	rNUM = NUM, rLINK_EMPL = LINK_EMPL, rDAYS = DAYS, rPERC = PERC, rCODE_PAY = CODE_PAY, 
	rNAME_PAY = NAME_PAY, rSUM_PAY = SUM_PAY, rCODE_TAX = CODE_TAX, rNAME_TAX = NAME_TAX, 
	rSUM_TAX = SUM_TAX, rORDERS = ORDERS, rVKR_CODE = VKR_CODE, rVKR_NAME = VKR_NAME, rVKR_ALL = VKR_ALL, rNAME = NAME
into #right
from #date D where id % 2 = 0
order by id, ORDERS, CODE_PAY

set nocount off

select * 
from #left L left join #right R on L.link = R.link
order by id, ORDERS, CODE_PAY


return 0



GO


GRANT EXECUTE ON dbo.[SA_REP_RL_ONE] TO PUBLIC

GO



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

GO
CREATE procedure dbo.sa_fot_empl_save @BufferName varchar(50)
as

declare @LINK_KBK INT,
        @DATE_BEGIN DATETIME,
		@DATE_END DATETIME,
		@EMPL_LINK INT,
		@ORDER_TYPE INT
SELECT @DATE_BEGIN = omp.DATE_BEGIN,
	   @DATE_END = omp.DATE_END,
	   @EMPL_LINK = omp.EMPL_LINK,
	   @ORDER_TYPE = omp.ORDER_TYPE
from 
	dbo.ORDER_MONEY_PERIOD omp 
	inner join dbo.buffer b on omp.link = b.link
	INNER JOIN dbo.PAYS p ON p.LINK = omp.PAY_LINK
where FLAG_JC = 0 and ACTIVE = 1 and  b.id = ltrim(rtrim(@BufferName))
	 

SELECT @DATE_BEGIN,@DATE_END,@EMPL_LINK,@ORDER_TYPE
		 
IF (@LINK_KBK IS NULL OR @LINK_KBK = 0)
		SET @LINK_KBK = (SELECT TOP 1 LINK_KBK FROM DBO.SA_EMPLS_INFO(@DATE_BEGIN, @EMPL_LINK) )
	
IF (@LINK_KBK IS NULL OR @LINK_KBK = 0)
BEGIN
	ROLLBACK
	RETURN 5
END

IF @ORDER_TYPE = (SELECT CODE FROM ORDER_TYPES WHERE OBJ_CODE = 'MONEY_CHANGE') 
BEGIN
	insert into dbo.pays_empl (LINK_EMPL, LINK_PAYS, DATE, SUMMA, LINK_MP, LINK_KBK)
	select EMPL_LINK,PAY_LINK,DATE_BEGIN,
		[VALUE] = CASE WHEN p.WAY_CALC = 10 AND omp.DOING_CODE = 0 THEN 1 ELSE [VALUE] END, 
		omp.link , @LINK_KBK
	from 
		dbo.ORDER_MONEY_PERIOD omp 
		inner join dbo.buffer b on omp.link = b.link
		INNER JOIN dbo.PAYS p ON p.LINK = omp.PAY_LINK
	where FLAG_JC = 0 and ACTIVE = 1 and b.id = ltrim(rtrim(@BufferName))
	
	IF ISNULL(@DATE_END,'29991231') <> '29991231'
	BEGIN
		insert into dbo.pays_empl (LINK_EMPL, LINK_PAYS, DATE, SUMMA, LINK_MP, LINK_KBK)
		select EMPL_LINK,PAY_LINK,@DATE_END+1,
			0, 
			omp.link , @LINK_KBK
		from 
			dbo.ORDER_MONEY_PERIOD omp 
			inner join dbo.buffer b on omp.link = b.link
			INNER JOIN dbo.PAYS p ON p.LINK = omp.PAY_LINK
		where FLAG_JC = 1 and ACTIVE = 1 and b.id = ltrim(rtrim(@BufferName))
	END
END ELSE 
	BEGIN
		insert into dbo.pays_empl (LINK_EMPL, LINK_PAYS, DATE, SUMMA, LINK_MP, LINK_KBK)
		select EMPL_LINK,PAY_LINK,DATE_BEGIN,
			[VALUE] = CASE WHEN p.WAY_CALC = 10 AND omp.DOING_CODE = 0 THEN 1 ELSE [VALUE] END, 
			omp.link , @LINK_KBK
		from 
			dbo.ORDER_MONEY_PERIOD omp 
			inner join dbo.buffer b on omp.link = b.link
			INNER JOIN dbo.PAYS p ON p.LINK = omp.PAY_LINK
		where FLAG_JC = 0 and ACTIVE = 1 and b.id = ltrim(rtrim(@BufferName))	
	END


return 0

GO


GRANT EXECUTE ON dbo.[sa_fot_empl_save] TO PUBLIC

GO



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

GO

CREATE PROCEDURE [dbo].SA_PRINT_RL_XML

@cYear1 VARCHAR(4)	/* Расчетный год */,
@nMonth1 int	/* Расчетный месяц */,
@nOption1 int = 1	/* Порядок сортировки */,
@nCheck1 int = 0	/* Печатать только по одному  Р/Л на сотрудника */,
@nCheck2 int = 0	/* Не печатать должность сотрудника */,
@nCheck3 int = 0	/* Разделять Б/Л за счет ФСС и работодателя */,
@nCheck4 int = 0	/* Отображать источник финансирования */,
@nCheck5 int = 0	/* Формировать пустые р/л */,
@nOption2 int = 1	/* Создание отчёта */,
@nCombo1 int = 3 /* Количество листочков на листе */,
@nCheck6 int = 0	/* Детализировать остаток */,
@nCheck7 int = 0 /* Отображать разряд */,
@nCheck8 int = 0 /* ФИО полностью */,
@nCheck9 int = 0 /*Выводить наименование отдела вместо кода*/,
@nCheck10 int	/* Формировать р/л за каждый месяц с начала года по выбранный месяц */,
@nFilterLink int	/* Фильтр */

AS

IF COALESCE(@nCombo1,0) = 0
	SET @nCombo1 = 3

IF @nCombo1 = 1
	SET @nCombo1 = 999999
ELSE
	SET @nCombo1 = @nCombo1 - 1

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_GROUPS_EMPL'))
SELECT @cVal2 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink2 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE='QUERY_OTBOR_CHECK'))


CREATE TABLE #DATA (
		[ID] INT,
		LINK_EMPL1 INT, FIO VARCHAR(254), TN VARCHAR(15), [STATUS] VARCHAR(20), MON TINYINT, SUBDIV VARCHAR(254),POST VARCHAR(50),
		OKLAD NUMERIC(20,2), FWT INT,
		REST_BEG NUMERIC(20,2), REST_D NUMERIC(20,2),
		
		SUM_TOTAL NUMERIC(20,2), 
		DEDUCT NUMERIC(20,2), 	
		NDFL NUMERIC(20,2),	
		
		INSUR NUMERIC(20,2), 	
		GAIN NUMERIC(20,2),	
		NUM INT,

		LINK_EMPL INT,
		DAYS NUMERIC(15,2), PERC NUMERIC(15,2),
		CODE_PAY VARCHAR(10), NAME_PAY VARCHAR(254), SUM_PAY NUMERIC(20,2),
		CODE_TAX VARCHAR(10), NAME_TAX VARCHAR(254), SUM_TAX NUMERIC(20,2),
		ORDERS TINYINT,VKR_CODE VARCHAR(30),VKR_NAME VARCHAR(400),
		VKR_ALL VARCHAR(400), NAME VARCHAR(254)
)

DECLARE @DATE_BEG DATETIME, @DATE_01 DATETIME, @END_DATE DATETIME, @START_YEAR DATETIME
SET @DATE_BEG = dbo.ConvertDMY2Date(1, @nMonth1, CONVERT(INT,@cYear1))
SET @DATE_01 = DATEADD(DAY, -1, @DATE_BEG)
SET @END_DATE = dbo.DateEndOfMonth(@DATE_BEG)
SET @START_YEAR = dbo.DateBeginOfYear(@DATE_BEG)


 
INSERT INTO #DATA
exec DBO.SD_REP_RL @cYear1, @nMonth1, @cVal1, @nOtborLink1,
@nOption1	/* Порядок сортировки */,
@nCheck3	/* Разделять Б/Л за счет ФСС и работодателя */,
0, --nLinkEmpl
@nCheck4	/* Отображать источник финансирования */,
@nCheck5	/* Формировать пустые р/л */,
@nCheck7	/* Отображать разряд */,
@cVal2, @nOtborLink2, 
@nCheck8, --ФИО полностью
@nCheck9, --Выводить наименование отдела вместо кода
@nCheck10 --Формировать р/л за каждый месяц с начала года по выбранный месяц

DECLARE @lcFNAME varchar(254)
SET @lcFNAME = 'RL.XML'

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

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) + '<!--Отчет xmlns="http://tempuri.org/XMLSchema.xsd"-->'
UNION ALL SELECT @lcFNAME, SPACE(0) + '<Отчет xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="XMLSchema.xsd">'
	UNION ALL SELECT @lcFNAME, SPACE(1) + '<ПарамЧасть>'
		UNION ALL SELECT @lcFNAME, SPACE(2) + '<ИстПарам>' + CONVERT(VARCHAR(10),@nCheck4) + '</ИстПарам>'
		UNION ALL SELECT @lcFNAME, SPACE(2) + '<ШабПарам>' + CONVERT(VARCHAR(10),@nCheck1) + '</ШабПарам>'
		UNION ALL SELECT @lcFNAME, SPACE(2) + '<ДолжПарам>' + CONVERT(VARCHAR(10),@nCheck2) + '</ДолжПарам>'
		UNION ALL SELECT @lcFNAME, SPACE(2) + '<КолЛисточков>' + CONVERT(VARCHAR(10),@nCombo1) + '</КолЛисточков>'
		UNION ALL SELECT @lcFNAME, SPACE(2) + '<ДеталОст>' + CONVERT(VARCHAR(10),@nCheck6) + '</ДеталОст>'
	UNION ALL SELECT @lcFNAME, SPACE(1) + '</ПарамЧасть>'

	DECLARE @Cur1 CURSOR, @ID INT, @BEFORE VARCHAR(2000), @AFTER VARCHAR(2000), @LINK_EMPL INT
	SET @Cur1 = CURSOR FORWARD_ONLY

	FOR SELECT DISTINCT
		ID,
		B = 
	SPACE(1) + '<ИнфЧасть>'	+ CHAR(13) + CHAR(10)	
	+ SPACE(2) + '<ФизЛицо>' + CHAR(13) + CHAR(10)
		+ SPACE(3) + '<Таб>' + LTRIM(RTRIM(COALESCE(TN,''))) + '</Таб>' + CHAR(13) + CHAR(10)
		+ SPACE(3) + '<Отдел>' + LTRIM(RTRIM(COALESCE(SUBDIV,''))) + '</Отдел>' + CHAR(13) + CHAR(10)
		+ SPACE(3) + '<Должность>' + LTRIM(RTRIM(COALESCE(POST,''))) + '</Должность>' + CHAR(13) + CHAR(10)
		+ SPACE(3) + '<Оклад>' + RTRIM(LTRIM(STR(COALESCE(OKLAD,0),15,2))) + '</Оклад>' + CHAR(13) + CHAR(10)
		+ SPACE(3) + '<ФИО>' + LTRIM(RTRIM(COALESCE(FIO,'')))  + '</ФИО>' + CHAR(13) + CHAR(10)
		+ SPACE(3) + '<СтатусCотруд>' + LTRIM(RTRIM(COALESCE([STATUS],''))) + '</СтатусCотруд>' + CHAR(13) + CHAR(10)
	+ SPACE(2) + '</ФизЛицо>' + CHAR(13) + CHAR(10)

	+ SPACE(2) + '<Период>' + CHAR(13) + CHAR(10)
		+ SPACE(3) + '<Год>' + LTRIM(RTRIM(@cYear1)) + '</Год>' + CHAR(13) + CHAR(10)
		+ SPACE(3) + '<Месяц>' + RTRIM(LTRIM(STR(COALESCE(MON,0),15))) + '</Месяц>' + CHAR(13) + CHAR(10)
		+ SPACE(3) + '<ФРабВрем>' + RTRIM(LTRIM(STR(COALESCE(FWT,0),15,2))) + '</ФРабВрем>' + CHAR(13) + CHAR(10)
	+ SPACE(2) + '</Период>' + CHAR(13) + CHAR(10)

	+ SPACE(2) + '<Остаток>' + RTRIM(LTRIM(STR(COALESCE(REST_BEG,0),15,2))) + '</Остаток>' + CHAR(13) + CHAR(10),

	A = 
	  SPACE(2) + '<ДолгОрг>' + RTRIM(LTRIM(STR(COALESCE(REST_D,0),15,2))) + '</ДолгОрг>' + CHAR(13) + CHAR(10)

	+ SPACE(2) + '<НДФЛ>' + CHAR(13) + CHAR(10)
		+ SPACE(3) + '<СовДох>' + RTRIM(LTRIM(STR(COALESCE(SUM_TOTAL,0),15,2))) + '</СовДох>' + CHAR(13) + CHAR(10)
		+ SPACE(3) + '<Налог>' + RTRIM(LTRIM(STR(COALESCE(NDFL,0),15,2))) + '</Налог>' + CHAR(13) + CHAR(10)
		+ SPACE(3) + '<Вычеты>' + RTRIM(LTRIM(STR(COALESCE(DEDUCT,0),15,2))) + '</Вычеты>' + CHAR(13) + CHAR(10)
	+ SPACE(2) + '</НДФЛ>' + CHAR(13) + CHAR(10)

	+ SPACE(2) + '<ПенСтрах>' + CHAR(13) + CHAR(10)
		+ SPACE(3) + '<СтрахЧасть>' + RTRIM(LTRIM(STR(COALESCE(INSUR,0),15,2))) + '</СтрахЧасть>' + CHAR(13) + CHAR(10)
		+ SPACE(3) + '<НакопЧасть>' + RTRIM(LTRIM(STR(COALESCE(GAIN,0),15,2))) + '</НакопЧасть>' + CHAR(13) + CHAR(10)
	+ SPACE(2) + '</ПенСтрах>' + CHAR(13) + CHAR(10)

	+ SPACE(2) + '<ИстФин>' + CHAR(13) + CHAR(10)
		+ SPACE(3) + '<Комментарий>' + LTRIM(RTRIM(COALESCE(VKR_ALL,''))) + '</Комментарий>' + CHAR(13) + CHAR(10)
	+ SPACE(2) + '</ИстФин>' + CHAR(13) + CHAR(10)
	+ SPACE(1) + '</ИнфЧасть>',
	
	LINK_EMPL1

 	FROM 
		#DATA

	OPEN @Cur1
	FETCH NEXT FROM @Cur1 INTO @ID, @BEFORE, @AFTER, @LINK_EMPL
	WHILE (@@fetch_status <> -1)
	BEGIN
		IF (@@fetch_status <> -2)
		BEGIN

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, @BEFORE

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, 
				SPACE(2) + '<НачУд>' + CHAR(13) + CHAR(10)
				+	SPACE(3) + '<Источник>' + RTRIM(LTRIM(COALESCE(VKR_CODE,''))) + '</Источник>' + CHAR(13) + CHAR(10)
				+	SPACE(3) + '<Код>' 
					+ CASE WHEN RTRIM(LTRIM(COALESCE(CODE_PAY,''))) <> '' 
						THEN RTRIM(LTRIM(COALESCE(CODE_PAY,''))) 
						ELSE RTRIM(LTRIM(COALESCE(CODE_TAX,''))) 
					  END
					+ '</Код>' + CHAR(13) + CHAR(10)
				+	SPACE(3) + '<Дни>' + RTRIM(LTRIM(STR(COALESCE(DAYS,0),15,2))) + '</Дни>' + CHAR(13) + CHAR(10)
				+	SPACE(3) + '<Часы>' + RTRIM(LTRIM(STR(COALESCE(PERC,0),15,2))) + '</Часы>' + CHAR(13) + CHAR(10)
				+	SPACE(3) + '<Наименование>' 
					+ CASE WHEN RTRIM(LTRIM(COALESCE(NAME_PAY,''))) <> ''
						THEN RTRIM(LTRIM(COALESCE(NAME_PAY,'')))
						ELSE RTRIM(LTRIM(COALESCE(NAME_TAX,'')))
					  END
					+ '</Наименование>' + CHAR(13) + CHAR(10)
				+	SPACE(3) + '<Начисл>' + RTRIM(LTRIM(STR(COALESCE(SUM_PAY,0),15,2))) + '</Начисл>' + CHAR(13) + CHAR(10)
				+	SPACE(3) + '<Удерж>' + RTRIM(LTRIM(STR(COALESCE(SUM_TAX,0),15,2))) + '</Удерж>' + CHAR(13) + CHAR(10)
			+	SPACE(2) + '</НачУд>' + CHAR(13) + CHAR(10)
			FROM 
				#DATA
			WHERE
				ID = @ID

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, 
				SPACE(2) + '<ОстК>' + CHAR(13) + CHAR(10)
				+	SPACE(3) + '<ОстКИсточник>' + RTRIM(LTRIM(COALESCE(F.CODE,''))) + '/'+ RTRIM(LTRIM(ISNULL(E.CODE,''))) + '</ОстКИсточник>' + CHAR(13) + CHAR(10)
				+	SPACE(3) + '<ОстКСумНМ>' + RTRIM(LTRIM(STR(COALESCE(SUMMA1,0),15,2))) + '</ОстКСумНМ>' + CHAR(13) + CHAR(10)		
				+	SPACE(3) + '<ОстКСумН>' + RTRIM(LTRIM(STR(COALESCE(SUMMA2,0),15,2))) + '</ОстКСумН>' + CHAR(13) + CHAR(10)
				+	SPACE(3) + '<ОстКСумУ>' + RTRIM(LTRIM(STR(COALESCE(SUMMA3,0),15,2))) + '</ОстКСумУ>' + CHAR(13) + CHAR(10)
				+	SPACE(3) + '<ОстКСум>' + RTRIM(LTRIM(STR(COALESCE(SUMMA4,0),15,2))) + '</ОстКСум>' + CHAR(13) + CHAR(10)
			+	SPACE(2) + '</ОстК>' + CHAR(13) + CHAR(10)
			FROM 
				DBO.SA_BALANCE_DECODING(@START_YEAR,@END_DATE,1,1) T 
				LEFT JOIN DBO.SAL_SFIN F ON F.LINK = T.LINK_VKR
				LEFT JOIN dbo.KOSGU E ON E.LINK = T.LINK_EKR
			WHERE 
				LINK_EMPL = @LINK_EMPL
				AND
				@nCheck6 = 1

			INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
			SELECT @lcFNAME, @AFTER

		END
	
		FETCH NEXT FROM @Cur1 INTO @ID, @BEFORE, @AFTER, @LINK_EMPL
	END
	
	CLOSE @Cur1
	DEALLOCATE @Cur1

INSERT INTO #OUTPUT (F_NAME, OUT_TEXT) SELECT @lcFNAME, SPACE(0) + '</Отчет>'

SELECT * FROM #OUTPUT
DROP TABLE #OUTPUT



GO


GRANT EXECUTE ON dbo.[SA_PRINT_RL_XML] TO PUBLIC

GO


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

GO

/*
© Кейсистемс (Keysystems), 2005
*/
CREATE PROCEDURE dbo.SALARY_DOC_RESERV_RASCHET
	@LINK int

AS

--[SALARY_DOC_RESERV_RASCHET] 32353

BEGIN

DECLARE @MONTH INT, @YEAR INT, @LINK_DEP INT
SELECT @MONTH = MONTH(SD.PERIOD), @YEAR = YEAR(SD.PERIOD), @LINK_DEP = S.LINK_DEP
FROM
	dbo.SDOC S with (nolock) 
	INNER JOIN dbo.SDOC_RESERV SD with (nolock) ON S.LINK = SD.LINK_UP
WHERE
	S.LINK = @LINK	

--Сумма начислений
IF OBJECT_ID('TEMPDB..#J','U') IS NOT NULL
	DROP TABLE #J
	
CREATE TABLE #J (PERS INT, SUMMA NUMERIC(20,2))

INSERT INTO #J (PERS, SUMMA)
SELECT E.PERS_LINK, SUM(J.SUMMA)
FROM
	dbo.PAYS_REF PR 
	INNER JOIN dbo.CALCULATE_JURNAL J ON J.LINK_PAYS = PR.LINK_PAYS
	INNER JOIN dbo.EMPL E ON E.LINK = J.LINK_EMPL
WHERE
	PR.LINK_GROUPS = dbo.sa_get_option_by_code('DOCUMENTS_ADD_RESERV_OPT1')
	AND
	J.LINK_DEP = @LINK_DEP
	AND
	YEAR(J.PERIOD_BEGIN) = @YEAR
	AND
	MONTH(J.PERIOD_BEGIN) = @MONTH
GROUP BY
	E.PERS_LINK


--Тариф по физлицам (пока на основе рассчитанных стр. взносов)
DECLARE @LinkEKR_R211 int
SELECT @LinkEKR_R211 = LINK FROM dbo.DICTIONARY_ITEM WHERE CODE = 'R211'

IF OBJECT_ID('TEMPDB..#S','U') IS NOT NULL
	DROP TABLE #S
	
CREATE TABLE #S (PERS INT, [PERCENT] NUMERIC(20,2))

INSERT INTO #S (PERS, [PERCENT])
SELECT E.PERS_LINK, SUM(J.SUMMA)/(SUM(J.SUMMA_BASE)/SUM(1)) * 100
FROM
	dbo.PAYS P 
	INNER JOIN dbo.CALCULATE_JURNAL J ON J.LINK_PAYS = P.LINK
	INNER JOIN dbo.EMPL E ON E.LINK = J.LINK_EMPL
WHERE
	P.[OBJECT] = 3 AND P.WAY_CALC <> 5
	AND
	J.LINK_DEP = @LINK_DEP
	AND
	YEAR(J.PERIOD_BEGIN) = @YEAR
	AND
	MONTH(J.PERIOD_BEGIN) = @MONTH	
	AND
	J.LINK_EKR <> @LinkEKR_R211
GROUP BY
	E.PERS_LINK
HAVING
	SUM(J.SUMMA_BASE) > 0

IF OBJECT_ID('TEMPDB..#ST','U') IS NOT NULL
	DROP TABLE #ST
	
CREATE TABLE #ST ([PERCENT] NUMERIC(20,2))

--Общий тариф по травматизму
INSERT INTO #ST ([PERCENT])
SELECT TOP 1 [PERCENT]
FROM 
	dbo.PAYS P
	INNER JOIN dbo.DICTIONARY_RANGE DR ON P.LINK = DR.LINK_PAYS
WHERE
	P.[OBJECT] = 3 AND P.WAY_CALC = 5
	AND TARIF = 1
	AND DR.[DATE]= (SELECT TOP 1 [DATE] FROM dbo.DICTIONARY_RANGE DR1 
		WHERE DR1.TARIF = DR.TARIF AND LINK_PAYS = P.LINK AND [DATE] <= dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@MONTH,@YEAR)) ORDER BY [DATE] DESC) 

--Тариф по травматизму для инвалидов
IF OBJECT_ID('TEMPDB..#STI','U') IS NOT NULL
	DROP TABLE #STI
	
CREATE TABLE #STI (PERS_LINK INT, [PERCENT] NUMERIC(20,2))

INSERT INTO #STI (PERS_LINK, [PERCENT])
SELECT
	I.PERS_LINK, [PERCENT] = MP.summa
FROM	
	dbo.MINROT_PAYS MP
	INNER JOIN dbo.PERS_INVALID I ON 1=1
WHERE
	[OBJECT] = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS WHERE CODE = 'COLUMN_REF_PAY_MROT_T3')
	AND
	LINK_MINROT = (SELECT TOP 1 LINK FROM dbo.MINROT WHERE PERIOD<=dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@MONTH,@YEAR)) ORDER BY PERIOD DESC)
	AND
	dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@MONTH,@YEAR)) BETWEEN I.DATE_BEGIN AND COALESCE(I.DATE_END,'29990101')	


--Остаток неиспользованных дней отпуска
IF OBJECT_ID('TEMPDB..#VAC','U') IS NOT NULL
	DROP TABLE #VAC
	
CREATE TABLE #VAC (LINK_EMPL INT, [SUMMA] INT)

INSERT INTO #VAC (LINK_EMPL, [SUMMA])
SELECT
	LINK, ISNULL([not_us_o],0) + ISNULL([not_us_D],0)
FROM	
	dbo.ku_EmplNormVacationR(dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@MONTH,@YEAR)))

DECLARE @DAYS INT
SET @DAYS = 
	datediff(
		day,
		dbo.DateBeginOfMonth(dbo.ConvertDMY2Date(1,@MONTH,@YEAR)),
		dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@MONTH,@YEAR))
	) + 1

--SELECT 
--	datediff(
--		day,
--		dbo.DateBeginOfMonth(dbo.ConvertDMY2Date(1,@MONTH,@YEAR)),
--		dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@MONTH,@YEAR))
--	) + 1
--	-
--	(		
--	SELECT 
--		COUNT(DH.[DAY])
--	FROM
--		dbo.days_ex(
--			dbo.DateBeginOfMonth(dbo.ConvertDMY2Date(1,@MONTH,@YEAR)), 
--			dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@MONTH,@YEAR))
--			) A
--		INNER JOIN dbo.HOLIDAYS DH ON day(A.[DATE]) = DH.[DAY] and month(A.DATE) = DH.[MONTH] AND YEAR(A.DATE) = DH.[YEAR] AND DH.TYPE_HOL = 1
--	)		

DELETE FROM dbo.SDOC_RESERV_TABLE WHERE LINK_UP = @LINK

INSERT INTO dbo.SDOC_RESERV_TABLE (LINK_UP, ORDERS, LINK_EMPL, SUMMA_BASE, AMOUNT_DED, SUMMA_DED, AMOUNT_TR, SUMMA_TR, OST_VAC_D, SUMMA_RESERV)

SELECT 
	LINK_UP = @LINK
	,ORD = ROW_NUMBER () OVER (ORDER BY P.FM,P.IM,P.OT)
	,LINK_EMPL = E.LINK
	,SUMMA_BASE = ISNULL(J.SUMMA,0)
	,PERCENT_S = ISNULL(S.[PERCENT],0)
	,SUMMA_S = ROUND(ISNULL(J.SUMMA,0) * ISNULL(S.[PERCENT],0) / 100,2)
	,PERCENT_T = COALESCE(STI.[PERCENT],ST.[PERCENT],0)
	,SUMMA_ST = ROUND(ISNULL(J.SUMMA,0) * COALESCE(STI.[PERCENT],ST.[PERCENT],0) / 100,2)
	,DAYS_VAC = ISNULL(VAC.SUMMA,0)
	,SUUMA_R = 
		(
			ISNULL(J.SUMMA,0)
		+	ROUND(ISNULL(J.SUMMA,0) * ISNULL(S.[PERCENT],0) / 100,2)
		+	ROUND(ISNULL(J.SUMMA,0) * COALESCE(STI.[PERCENT],ST.[PERCENT],0) / 100,2)
		) 
		/ (@DAYS)
		* (ISNULL(VAC.SUMMA,0) / 12)

FROM
	DBO.EMPL E with (nolock)
	--Заполняем сотрудником с последним приказом о приеме
	INNER JOIN (
		/*выбор последних линков сотрудников для статусов основной и внешний совместитель
		берется последний табельный, если увольнялся, затем заново принимался*/
		SELECT E.DEP_LINK, E.PERS_LINK, E.LINK, E.TAB, NUM = ROW_NUMBER () OVER (PARTITION BY E.DEP_LINK, E.PERS_LINK ORDER BY DATE_BEGIN DESC)
			FROM dbo.EMPL E INNER JOIN dbo.ITEM_MOVE IM ON E.LINK = IM.EMPL_LINK
				WHERE IM.ACTIVE = 1 AND IM.NEW_FACE=1 AND (IM.[STATUS]=1 OR IM.[STATUS]=3) AND DATE_BEGIN <= dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@MONTH,@YEAR))
		/*выбор линков сотрудников для статусов внутренний совместитель*/
		UNION ALL
		SELECT E.DEP_LINK, E.PERS_LINK, E.LINK, E.TAB, NUM = 1
			FROM dbo.EMPL E INNER JOIN dbo.ITEM_MOVE IM ON E.LINK = IM.EMPL_LINK
				WHERE IM.ACTIVE = 1 AND IM.NEW_FACE=1 AND IM.[STATUS]=2 AND DATE_BEGIN <= dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@MONTH,@YEAR))
		) T ON T.DEP_LINK = E.DEP_LINK AND E.LINK = T.LINK AND T.NUM = 1	
	INNER JOIN DBO.PERSON P with (nolock) ON E.PERS_LINK = P.LINK
	LEFT JOIN DBO.ITEM_DIS_FACE IDF with (nolock) ON IDF.EMPL_LINK = E.LINK AND IDF.ACTIVE=1 AND COALESCE(IDF.DIS_DATE,'20490101') < dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,@MONTH,@YEAR))	
	LEFT JOIN #J J ON J.PERS = E.PERS_LINK
	LEFT JOIN #S S ON S.PERS = E.PERS_LINK
	LEFT JOIN #ST ST ON 1=1
	LEFT JOIN #STI STI ON STI.PERS_LINK = E.PERS_LINK
	LEFT JOIN #VAC VAC ON VAC.LINK_EMPL = E.LINK
WHERE
	E.DEP_LINK = @LINK_DEP
	AND
	COALESCE(IDF.LINK,0) = 0


RETURN 0


END 


GO


GRANT EXECUTE ON dbo.[SALARY_DOC_RESERV_RASCHET] TO PUBLIC

GO


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

GO

CREATE FUNCTION dbo.BK_DOC_TAB_MX3_INV_FN
	(@intLINK_DOC	INT =	NULL)
RETURNS TABLE
AS
RETURN
	SELECT 
		OTR.LINK,
		OTR.LINK_UP,
		OTR.[OBJECT],
		OTR.ORDERS,
		OTR.LINK_OPER,
		OT1.INV_TYPE,
		INV = T2.LINK,
		T2.INV_CODE,
		T2.INV_NAME,
		UM	=	DG.LINK,
		UM_CODE	=	DG.CODE,
		UM_SNAME	=	DG.SNAME,
		OTMC.QTY,
		OTMC.SUMMA,
		OTMC.PRICE,
		COMMENT = (SELECT CONVERT (VARCHAR (254), OTS.STRING)
					FROM dbo.OUT_TABLE_STRING OTS
					WHERE OTS.LINK_UP = OTR.LINK
						AND OTS.[OBJECT] = dbo.GetObjLink ('DOC_MX3_INV_T_COMMENT')
					),
		INV_CHAR = (SELECT CONVERT (VARCHAR (254), OTS.STRING)
					FROM dbo.OUT_TABLE_STRING OTS
					WHERE OTS.LINK_UP = OTR.LINK
						AND OTS.[OBJECT] = dbo.GetObjLink ('DOC_MX3_INV_T_INV_CHAR')
					)
	FROM dbo.OUT_TABLE_ROW OTR
	LEFT JOIN dbo.OUT_TABLE_INV_TYPE OT1 ON (OT1.LINK_UP = OTR.LINK)
	LEFT JOIN dbo.SELECT_MZ_WITH_TYPE T2 ON (T2.INV_TYPE = OT1.INV_TYPE
		AND (OT1.INV_TYPE = 'INVENTORY_CARD' AND T2.LINK = OT1.INV
			OR (OT1.INV_TYPE = 'BV_NOMENCLATURE' OR OT1.INV_TYPE = 'DICTIONARY_SERV') AND T2.LINK = OT1.NOMEN
			OR OT1.INV_TYPE = 'DICTIONARY_TMC' AND T2.LINK = OT1.TMC)
			)
	LEFT JOIN dbo.DICTIONARY_DIGIT DG ON (DG.LINK = T2.UM_LINK)
	LEFT JOIN dbo.OUT_TABLE_MZ_CHARGE OTMC ON (OTMC.LINK_UP = OTR.LINK)
	WHERE OTR.[OBJECT] = dbo.GetObjLink ('DOC_MX3_INV_TABLE')
		AND (@intLINK_DOC IS NULL
			OR OTR.LINK_UP = @intLINK_DOC
			)	

GO


GRANT SELECT ON dbo.[BK_DOC_TAB_MX3_INV_FN] TO PUBLIC

GO


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


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

CREATE PROCEDURE dbo.BK_IMPORT_PROV_FROM_BKS 
	@cBufferID	char(20),  
	@dDateB		datetime,
	@dDateE		datetime,
	@cBuffIdKBK char(100),
	@cBuffIdSGU char(100),
	@cBuffIdACC char(100),
	@iNotOperLoad	tinyint = 0

AS
BEGIN
	DECLARE
		--- Реквизиты документа ---	
		@intDOC_BKS INT,
		@DOC_NUM VARCHAR (30),
		@DOC_DATE DATETIME,
		@DATE_PROV DATETIME,
		@DOC_TYPE INT,
		@DOC_CODE VARCHAR (254),
		@DOC_NAME VARCHAR (254),
		@DEP_INN VARCHAR (12),
		@COMMENT  VARCHAR (254),
		@DEP_ACC  VARCHAR (20),
	
		@intDOC_SMETA	INT,
		@intDEP_LINK	INT,
		@intDEP_ACC	INT,
	
		--- Создание операций ---
		@intLINK_G1	INT,
		@strNAME_OPER_G1	VARCHAR (254),
		@intORDERS_G1	INT,

		--- СОХРАНЕНИЕ ПРОВОДОК ---
		--- G_PROV2 ---
		@intLINK_G2	INT,
		@strNAME_OPER_G2	VARCHAR (254),
		@intORDERS_G2	INT,
		@intECON_OPER	INT,

		@strJO_CODE	VARCHAR (10),
		@intJO		INT,

		@nSUMMA		NUMERIC(19,2),

		--- G_PROV_AP (дебет)---
		@strACC_CODE_DT	VARCHAR(10),
		@strKBK_CODE_DT	VARCHAR(20),
		@intKBK_TYPE_DT	INT,
		@strSGU_CODE_DT	VARCHAR(3),
		@strEKR_CODE_DT	VARCHAR(3),
		@strDCL_CODE_DT	VARCHAR(20),
		@strDEP_ACC_DT	VARCHAR(20),
		@strDEP_INN_DT	VARCHAR(13),
		@strDEP_NAME_DT	VARCHAR(254),	
		@strDEP_OKATO_DT VARCHAR(15),
		
		@intACC_DT	INT,
		@intKBK_DT	INT,
		@intSGU_DT	INT,
		@intEKR_DT	INT,
		@intDCL_DT	INT,
		@intDEP_ACC_DT	INT,
		@intDEP_DT	INT,

		--- G_PROV_AP (кредит)---
		@strACC_CODE_KT	VARCHAR(10),
		@strKBK_CODE_KT	VARCHAR(20),
		@intKBK_TYPE_KT	INT,
		@strSGU_CODE_KT	VARCHAR(3),
		@strEKR_CODE_KT	VARCHAR(3),
		@strDCL_CODE_KT	VARCHAR(20),
		@strDEP_ACC_KT	VARCHAR(20),
		@strDEP_INN_KT	VARCHAR(13),	
		@strDEP_NAME_KT	VARCHAR(254),	
		@strDEP_OKATO_KT VARCHAR(15),
		
		@intACC_KT	INT,
		@intKBK_KT	INT,
		@intSGU_KT	INT,
		@intEKR_KT	INT,
		@intDCL_KT	INT,
		@intDEP_ACC_KT	INT,
		@intDEP_KT	INT,


		--- ---
		@intERROR	INT,
		@cStrVal	varchar(100),
		@cStr		varchar(8000),
		@nameServer varchar(100),
		@nameBase	varchar(100),
		@nameUser	varchar(100),
		@userPass	varchar(100),
		@uid		uniqueidentifier,
		@cDepNextCode varchar(10),

		@intCount_Prov_Save	INT,
		@intCount_Doc_Save	INT,
		@cINNOwner varchar(12)

	select @cINNOwner = INN from dbo.DEPARTMENTS where LINK = isnull(dbo.BK_GetDepZB(),dbo.GetOwnDepLink())
	--- Список созданных документов ---
	DECLARE @TABLE_DOCS TABLE (DOC_BKS INT, DOC_SMETA INT, DATE DATETIME, DATE_PROV DATETIME, DOC_NUM char(25), DOC_CODE VARCHAR (254))
	create table #tProtocol(txt varchar(1000), NEW_ROW tinyint, nSTATUS tinyint, nTAB tinyint)

	exec X_GET_OPTION 'REPORT_ORTIONS_SERVER_BKS',0,@cStrVal output	
	set @nameServer=RTRIM(ISNULL(@cStrVal,''))
	IF  @nameServer = ''
	begin
		insert into #tProtocol values('Не указан сервер для подключению к ПК "Бюджет-КС"',1,2,0)
		select * from #tProtocol
		return 2
	end 

	exec X_GET_OPTION 'REPORT_ORTIONS_BASE_BKS',0,@cStrVal output 	
	set @nameBase=RTRIM(ISNULL(@cStrVal,''))
	IF  @nameBase = ''
	begin
		insert into #tProtocol values('Не указана база для подключения к ПК "Бюджет-КС"',1,2,0)
		select * from #tProtocol
		return 2
	end 

	exec X_GET_OPTION 'REPORT_ORTIONS_USER_BKS',0,@cStrVal output 	
	set @nameUser=RTRIM(ISNULL(@cStrVal,''))
	IF  @nameUser = ''
	begin
		insert into #tProtocol values('Не указан пользователь для подключению к ПК "Бюджет-КС"',1,2,0)
		select * from #tProtocol
		return 2
	end 

	exec X_GET_OPTION 'REPORT_ORTIONS_PASS_BKS',0,@cStrVal output 	
	set @userPass=RTRIM(ISNULL(@cStrVal,''))

	insert into #tProtocol values('Соединение с сервером ПК "Бюджет-КС"',1,0,0)
	insert into #tProtocol values('Сервер: ' + @nameServer + ', База: ' + @nameBase + ', Пользователь: ' + @nameUser,1,0,1)

	exec XO_CONNECT_ANOTHER_SERVER @nameServer,@nameUser,@userPass
	execute('if not exists (select * from ['+@nameServer + '].[' + @nameBase + '].dbo.sysobjects where name = ''PROV2SMETA'')
		begin
			insert into #tProtocol values(''Возможность импорта не реализована в указаной базе ПК "Бюджет-КС"'',1,2,0)
			select * from #tProtocol
		end')
	if @@rowcount > 0
		return 2

	--- Запрос в БКС ---
	CREATE TABLE #PROV_BKS (LINK int, NUMBER varchar(25), DATE datetime, DATE_PROV datetime, 
			DOC_TYPE int, DOC_CODE varchar(254), DOC_NAME varchar(254), DEP_INN varchar(13), COMMENT varchar(254), DEP_ACC varchar(20),
			ACC_CODE_DT varchar(10), ACC_LINK_DT int, KBK_CODE_DT varchar(20), KBK_LINK_DT int, KBK_TYPE_DT int, 
			SGU_CODE_DT varchar(3), SGU_LINK_DT int, EKR_CODE_DT varchar(3), EKR_LINK_DT int, DCL_CODE_DT varchar(20), 
			DEP_ACC_DT varchar(20), DACC_LINK_DT int, DEP_INN_DT varchar(13), DEP_LINK_DT int, DEP_NAME_DT varchar(254), DEP_OKATO_DT varchar(20), 
			ACC_CODE_KT varchar(10), ACC_LINK_KT int, KBK_CODE_KT varchar(20), KBK_LINK_KT int, KBK_TYPE_KT int, 
			SGU_CODE_KT varchar(3), SGU_LINK_KT int, EKR_CODE_KT varchar(3), EKR_LINK_KT int, DCL_CODE_KT varchar(20), 
			DEP_ACC_KT varchar(20), DACC_LINK_KT int, DEP_INN_KT varchar(13), DEP_LINK_KT int, DEP_NAME_KT varchar(254), DEP_OKATO_KT varchar(20), 
			SUMMA money, OPER_NAME varchar(254), JO_CODE varchar(10))
	
	insert into #tProtocol values('Прием данных из ПК "Бюджет-КС"',1,0,0)
	--execute('exec #tFromBKS ['+@nameServer + '].[' + @nameBase + '].dbo.[PROV2SMETA] ''' + convert(varchar(20),@dDateB,112) + ''','''  + convert(varchar(20),@dDateE,112) + ''',4,0,0,0,0,0,0,0,0,0,0,0,0')
	--set @cStr = 'insert into #PROV_BKS exec ['+@nameServer + '].[' + @nameBase + '].dbo.[PROV2SMETA] ''' + convert(varchar(20),@dDateB,112) + ''','''  + convert(varchar(20),@dDateE,112) + ''',4,0,0,0,0,0,0,0,0,0,0,0,0'
	
	set @uid = newid()
	set @cStr = 'exec ['+@nameServer + '].[' + @nameBase + '].dbo.[PROV2SMETA] ''' + convert(varchar(50),@uid) + ''',''' + convert(varchar(20),@dDateB,112) + ''','''  + convert(varchar(20),@dDateE,112) + ''',4,0,0,0,0,0,0,0,0,0,0,0,0'
	execute(@cStr)

	--select * from #PROV_BKS
	set @cStr = 'insert into #PROV_BKS
			select BKS.LINK, BKS.NUMBER, BKS.DATE, BKS.DATE_PROV, 
			DOC_TYPE = DT.LINK, 
			DOC_CODE = replace(BKS.DOC_CODE,''DOCUMENTS_0401003A'',''DOCUMENTS_0401003''), 
			BKS.DOC_NAME, 
			BKS.DEP_INN, 
			BKS.COMMENT, 
			BKS.DEP_ACC,
			ACC_CODE_DT = case when IO.LINK is not null then '''' else BKS.ACC_CODE_DT end, 
			ACC_LINK_DT = case when IO.LINK is not null then IO.DT_ACC_LINK else null end, 
			KBK_CODE_DT = case when IO.LINK is not null and IO.DT_KBK = 3 then ''''  when IO.LINK is not null and IO.DT_KBK = 2 then BKS.KBK_CODE_KT else BKS.KBK_CODE_DT end,
			KBK_LINK_DT = case when IO.LINK is not null and IO.DT_KBK = 3 then IO.DT_KBK_LINK else NULL end,
			KBK_TYPE_DT = case when IO.LINK is not null and IO.DT_KBK = 3 then ''''  when IO.LINK is not null and IO.DT_KBK = 2 then BKS.KBK_TYPE_KT else BKS.KBK_TYPE_DT end, 
			SGU_CODE_DT = case when IO.LINK is not null and IO.DT_SGU = 3 then '''' when IO.LINK is not null and IO.DT_SGU = 2 then BKS.SGU_CODE_KT else BKS.SGU_CODE_DT end,
			SGU_LINK_DT = case when IO.LINK is not null and IO.DT_SGU = 3 then IO.DT_SGU_LINK else NULL end,
			EKR_CODE_DT = case when IO.LINK is not null and IO.DT_EKR = 3 then '''' when IO.LINK is not null and IO.DT_EKR = 2 then BKS.EKR_CODE_KT when IO.LINK is not null and IO.DT_EKR = 4 then BKS.SGU_CODE_DT when IO.LINK is not null and IO.DT_EKR = 5 then BKS.SGU_CODE_KT else BKS.EKR_CODE_DT end,
			EKR_LINK_DT = case when IO.LINK is not null and IO.DT_EKR = 3 then IO.DT_EKR_LINK else NULL end,
			BKS.DCL_CODE_DT, 
			DEP_ACC_DT = case when IO.LINK is not null and IO.DT_ACC = 3 then ''''  when IO.LINK is not null and IO.DT_ACC = 2 then BKS.DEP_ACC_KT else BKS.DEP_ACC_DT end,
			DACC_LINK_DT = case when IO.LINK is not null and IO.DT_ACC = 3 then IO.DT_DACC_LINK else NULL end,
			DEP_CODE_DT = case when IO.LINK is not null and IO.DT_DEP = 3 then '''' when IO.LINK is not null and IO.DT_DEP = 2 then BKS.DEP_INN_KT when IO.LINK is not null and IO.DT_DEP = 4 then BKS.DEP_INN_UT else BKS.DEP_INN_DT end,
			DEP_LINK_DT = case when IO.LINK is not null and IO.DT_DEP = 3 then IO.DT_DEP_LINK else NULL end,
			DEP_NAME_DT = case when IO.LINK is not null and IO.DT_DEP = 3 then '''' when IO.LINK is not null and IO.DT_DEP = 2 then BKS.DEP_N_KT when IO.LINK is not null and IO.DT_DEP = 4 then BKS.DEP_N_UT else BKS.DEP_N_DT end,
			DEP_OKATO_DT = case when IO.LINK is not null and IO.DT_DEP = 3 then '''' when IO.LINK is not null and IO.DT_DEP = 2 then BKS.DEP_OKATO_KT when IO.LINK is not null and IO.DT_DEP = 4 then BKS.DEP_OKATO_UT else BKS.DEP_OKATO_DT end,
			
			ACC_CODE_KT = case when IO.LINK is not null then '''' else BKS.ACC_CODE_KT end, 
			ACC_LINK_KT = case when IO.LINK is not null then IO.KT_ACC_LINK else null end, 
			KBK_CODE_KT = case when IO.LINK is not null and IO.KT_KBK = 3 then ''''  when IO.LINK is not null and IO.KT_KBK = 1 then BKS.KBK_CODE_DT else BKS.KBK_CODE_KT end,
			KBK_LINK_KT = case when IO.LINK is not null and IO.KT_KBK = 3 then IO.KT_KBK_LINK else NULL end,
			KBK_TYPE_KT = case when IO.LINK is not null and IO.KT_KBK = 3 then ''''  when IO.LINK is not null and IO.KT_KBK = 1 then BKS.KBK_TYPE_DT else BKS.KBK_TYPE_KT end,  
			SGU_CODE_KT = case when IO.LINK is not null and IO.KT_SGU = 3 then '''' when IO.LINK is not null and IO.KT_SGU = 1 then BKS.SGU_CODE_DT else BKS.SGU_CODE_KT end,
			SGU_LINK_KT = case when IO.LINK is not null and IO.KT_SGU = 3 then IO.KT_SGU_LINK else NULL end,
			EKR_CODE_KT = case when IO.LINK is not null and IO.KT_EKR = 3 then '''' when IO.LINK is not null and IO.KT_EKR = 1 then BKS.EKR_CODE_DT when IO.LINK is not null and IO.KT_EKR = 4 then BKS.SGU_CODE_DT  when IO.LINK is not null and IO.KT_EKR = 5 then BKS.SGU_CODE_KT else BKS.EKR_CODE_KT end,
			EKR_LINK_KT = case when IO.LINK is not null and IO.KT_EKR = 3 then IO.KT_EKR_LINK else NULL end,
			BKS.DCL_CODE_KT, 
			DEP_ACC_KT = case when IO.LINK is not null and IO.KT_ACC = 3 then ''''  when IO.LINK is not null and IO.KT_ACC = 1 then BKS.DEP_ACC_DT else BKS.DEP_ACC_KT end,
			DACC_LINK_KT = case when IO.LINK is not null and IO.KT_ACC = 3 then IO.KT_DACC_LINK else NULL end,
			DEP_CODE_KT = case when IO.LINK is not null and IO.KT_DEP = 3 then ''''  when IO.LINK is not null and IO.KT_DEP = 1 then BKS.DEP_INN_DT when IO.LINK is not null and IO.KT_DEP = 4 then BKS.DEP_INN_UT else BKS.DEP_INN_KT end,
			DEP_LINK_KT = case when IO.LINK is not null and IO.KT_DEP = 3 then IO.KT_DEP_LINK else NULL end,
			DEP_NAME_KT = case when IO.LINK is not null and IO.KT_DEP = 3 then ''''  when IO.LINK is not null and IO.KT_DEP = 1 then BKS.DEP_N_DT when IO.LINK is not null and IO.KT_DEP = 4 then BKS.DEP_N_UT else BKS.DEP_N_KT end,
			DEP_OKATO_KT = case when IO.LINK is not null and IO.KT_DEP = 3 then ''''  when IO.LINK is not null and IO.KT_DEP = 1 then BKS.DEP_OKATO_DT when IO.LINK is not null and IO.KT_DEP = 4 then BKS.DEP_OKATO_UT else BKS.DEP_OKATO_KT end,
			
			SUMMA = case isnull(IO.[sign],0) when 1 then -BKS.SUMMA else BKS.SUMMA end, 
			OPER_NAME = case when IO.LINK is not null then IO.OP_NAME else BKS.OPER_NAME end,
			BKS.JO_CODE 
			from ['+@nameServer + '].[' + @nameBase + '].dbo.[DOC2SMETA] BKS 
			inner join dbo.DICTIONARY_DOC_TYPES DT on DT.CODE_BKS = replace(BKS.DOC_CODE,''DOCUMENTS_0401003A'',''DOCUMENTS_0401003'')
			inner join dbo.BufferGetTableByID(''' + @cBufferID + ''') B on DT.LINK = B.LINK
			' + case @iNotOperLoad when 0 then 'left' else 'inner' end + 
			' join dbo.BB_IMPORT_BKS_OPER IO on IO.USED = 1 and
														(BKS.ACC_CODE_DT = IO.BDT_ACC_CODE or IO.BDT_ACC_CODE = '''') and
														(BKS.ACC_CODE_KT = IO.BKT_ACC_CODE or IO.BKT_ACC_CODE = '''') and
														(BKS.SGU_CODE_DT like Replace(Replace(rtrim(IO.BDT_SGU_CODE),''*'',''%''),''?'',''_'') or IO.BDT_SGU_CODE = '''') and
														(BKS.SGU_CODE_KT like Replace(Replace(rtrim(IO.BKT_SGU_CODE),''*'',''%''),''?'',''_'') or IO.BKT_SGU_CODE = '''') and
														(IO.BDT_KBK_FILTER = '''' or left(rtrim(IO.BDT_KBK_FILTER),1) <> ''!'' and BKS.KBK_CODE_DT like Replace(Replace(rtrim(IO.BDT_KBK_FILTER),''*'',''%''),''?'',''_'') or 
																					 left(rtrim(IO.BDT_KBK_FILTER),1) = ''!'' and BKS.KBK_CODE_DT not like Replace(Replace(Replace(rtrim(IO.BDT_KBK_FILTER),''*'',''%''),''?'',''_''),''!'','''')) and
														(IO.BKT_KBK_FILTER = '''' or left(rtrim(IO.BKT_KBK_FILTER),1) <> ''!'' and BKS.KBK_CODE_KT like Replace(Replace(rtrim(IO.BKT_KBK_FILTER),''*'',''%''),''?'',''_'')or 
																					 left(rtrim(IO.BKT_KBK_FILTER),1) = ''!'' and BKS.KBK_CODE_KT not like Replace(Replace(Replace(rtrim(IO.BKT_KBK_FILTER),''*'',''%''),''?'',''_''),''!'','''')) 
			where BKS.UID = ''' + convert(varchar(50),@uid) + ''' and BKS.DEP_INN = ''' + STR(@cINNOwner) + ''''
	--select @cStr
	execute(@cStr)
	--select * from #PROV_BKS where number = '9'
	--insert into #tProtocol values('Принято ' + ltrim(str(@@rowcount)) + ' проводок',1,0,0)
		
/*
	set @cStr = 'delete from ['+@nameServer + '].[' + @nameBase + '].dbo.[DOC2SMETA] where UID = ''' + convert(varchar(50),@uid) + ''''
	execute(@cStr)
*/
/*
	
	set @cStr = 'select BKS.* 
			from ['+@nameServer + '].[' + @nameBase + '].dbo.[DOC2SMETA] BKS 
			inner join dbo.DICTIONARY_DOC_TYPES DT on DT.CODE_BKS = replace(BKS.DOC_CODE,''DOCUMENTS_0401003A'',''DOCUMENTS_0401003'')
			inner join dbo.BufferGetTableByID(''' + @cBufferID + ''') B on DT.LINK = B.LINK
			where BKS.UID = ''' + convert(varchar(50),@uid) + ''''
execute(@cStr)
	
 select * from #PROV_BKS*/

	set @cStr = 'EXEC ['+@nameServer + '].[' + @nameBase + '].dbo.DEL_FROM_DOC2SMETA ''' + convert(varchar(50),@uid) + ''''
	execute(@cStr)

	SELECT @intDEP_LINK = ISNULL (dbo.BK_GetDepZB (), dbo.GetOwnDepLink ())
	/*INSERT #PROV_BKS (LINK, NUMBER, DATE, DATE_PROV, DOC_CODE, DOC_NAME, DEP_INN, COMMENT, DEP_ACC,
				ACC_CODE_DT, KBK_CODE_DT, KBK_TYPE_DT, SGU_CODE_DT, EKR_CODE_DT, DCL_CODE_DT, DEP_ACC_DT, DEP_INN_DT, 
				ACC_CODE_KT, KBK_CODE_KT, KBK_TYPE_KT, SGU_CODE_KT, EKR_CODE_KT, DCL_CODE_KT, DEP_ACC_KT, DEP_INN_KT,
				SUMMA, OPER_NAME, JO_CODE)
	EXECUTE BKS_SMETA.DBO.PROV2SMETA @DATE_START, @DATE_END */
-- проверим наличие КБК,СГУ,Субсчетов при выключеных фильтрах
--КБК
	if isnull(@cBuffIdKBK,'') = ''
	begin 
		insert into #tProtocol
		select 'В справочнике КБК не найден КБК: ' + P.KBK_CODE_DT + ' Тип ' + str(P.KBK_TYPE_DT) as txt,1 ,1,0
		from #PROV_BKS P
		where not exists (select * from dbo.KL_KBK KBK where P.KBK_CODE_DT = replace(KBK.CODE,'.','') and P.KBK_TYPE_DT = KBK.[TYPE]) 
		union
		select 'В справочнике КБК не найден КБК: ' + P.KBK_CODE_KT + ' Тип ' + str(P.KBK_TYPE_KT) as txt,1 ,1,0
		from #PROV_BKS P
		where not exists (select * from dbo.KL_KBK KBK where P.KBK_CODE_KT = replace(KBK.CODE,'.','') and P.KBK_TYPE_KT = KBK.[TYPE]) 
		
	end
	ELSE
	begin
		update #PROV_BKS
		SET KBK_CODE_DT = KBK_CODE_KT
		where KBK_CODE_DT not in(SELECT replace(CODE,'.','') from dbo.KL_KBK KBK inner join dbo.BufferGetTableByID(@cBuffIdKBK) B on KBK.LINK = B.LINK) and
				KBK_CODE_KT in(SELECT replace(CODE,'.','') from dbo.KL_KBK KBK inner join dbo.BufferGetTableByID(@cBuffIdKBK) B on KBK.LINK = B.LINK)
		
		update #PROV_BKS
		SET KBK_CODE_KT = KBK_CODE_DT
		where KBK_CODE_KT not in(SELECT replace(CODE,'.','') from dbo.KL_KBK KBK inner join dbo.BufferGetTableByID(@cBuffIdKBK) B on KBK.LINK = B.LINK) and
				KBK_CODE_DT in(SELECT replace(CODE,'.','') from dbo.KL_KBK KBK inner join dbo.BufferGetTableByID(@cBuffIdKBK) B on KBK.LINK = B.LINK)
	end

--КБК
	if isnull(@cBuffIdSGU,'') = ''
	begin 
		insert into #tProtocol
		select 'В справочнике КОСГУ не найден КОСГУ/Д: ' + SGU_CODE_DT as txt,1 ,1,0
		from #PROV_BKS
		where SGU_CODE_DT not in (select CODE from dbo.KOSGU) 
		union
		select 'В справочнике КОСГУ не найден КОСГУ/К: ' + SGU_CODE_KT as txt,1,1,0
		from #PROV_BKS
		where SGU_CODE_KT not in (select CODE from dbo.KOSGU)
		union
		select 'В справочнике КОСГУ не найден КОСГУ (ЭКР/Д): ' + EKR_CODE_DT as txt,1 ,1,0
		from #PROV_BKS
		where EKR_CODE_DT not in (select CODE from dbo.KOSGU) 
		union
		select 'В справочнике КОСГУ не найден КОСГУ (ЭКР/К): ' + EKR_CODE_KT as txt,1,1,0
		from #PROV_BKS
		where EKR_CODE_KT not in (select CODE from dbo.KOSGU)
		order by txt
/*	
		select 'В справочнике КОСГУ не найден КОСГУ: ' + EKR_CODE_DT as txt,1 ,1,0
		from #PROV_BKS
		where SGU_CODE_DT not in (select CODE from dbo.KOSGU) 
		union
		select 'В справочнике КОСГУ не найден КОСГУ: ' + EKR_CODE_KT + '' as txt,1,1,0
		from #PROV_BKS
		where SGU_CODE_KT not in (select CODE from dbo.KOSGU)
		order by txt
*/	end

--КБК
	if isnull(@cBuffIdACC,'') = ''
	begin 
		insert into #tProtocol
		select 'В плане счетов не найден субсчет: ' + ACC_CODE_DT as txt,1 ,1,0
		from #PROV_BKS
		where ACC_CODE_DT not in (select replace(CODE,'.','') from dbo.S_ACCOUNTS) 
		union
		select 'В плане счетов не найден субсчет: ' + ACC_CODE_KT + '' as txt,1,1,0
		from #PROV_BKS
		where ACC_CODE_KT not in (select replace(CODE,'.','') from dbo.S_ACCOUNTS)
		order by txt
	end

-- конец проверки

--select * from #PROV_BKS
--where ACC_CODE_DT = ''
--where ACC_CODE_DT in ('120201') --, '140201')
--	OR ACC_CODE_KT in ('120201', '140201')
/*
	SELECT	all BKS.LINK, CONVERT (VARCHAR (15), ISNULL (BKS.NUMBER, '')),
			BKS.[DATE], BKS.DATE_PROV, 
			BKS.DOC_TYPE, BKS.DOC_CODE, BKS.DOC_NAME, BKS.DEP_INN, BKS.COMMENT, BKS.DEP_ACC,
		
			coalesce(ACCD1.LINK,BKS.ACC_LINK_DT,ACCD.LINK) as ACC_LINK_DT, BKS.ACC_CODE_DT, 
			isnull(BKS.KBK_LINK_DT,KBKD.LINK) as KBK_LINK_DT, BKS.KBK_CODE_DT, BKS.KBK_TYPE_DT, 
			isnull(BKS.SGU_LINK_DT,SGUD.LINK) as SGU_LINK_DT, BKS.SGU_CODE_DT, 
			EKRD.LINK as EKR_LINK_DT, EKRD.CODE as EKR_CODE_DT, 
			BKS.DCL_CODE_DT, 
			isnull(BKS.DACC_LINK_DT,null), BKS.DEP_ACC_DT, 
			isnull(BKS.DEP_LINK_DT,null), BKS.DEP_INN_DT, BKS.DEP_NAME_DT, 

			coalesce(ACCK1.LINK,BKS.ACC_LINK_KT,ACCK.LINK) as ACC_LINK_KT, BKS.ACC_CODE_KT, 
			isnull(BKS.KBK_LINK_KT,KBKK.LINK) as KBK_LINK_KT, BKS.KBK_CODE_KT, BKS.KBK_TYPE_KT, 
			isnull(BKS.SGU_LINK_KT,SGUK.LINK) as SGU_LINK_KT, BKS.SGU_CODE_KT, 
			EKRK.LINK as EKR_LINK_KT, EKRK.CODE as EKR_CODE_KT, 
			BKS.DCL_CODE_KT, 
			isnull(BKS.DACC_LINK_KT,null), BKS.DEP_ACC_KT, 
			isnull(BKS.DEP_LINK_KT,null),BKS.DEP_INN_KT, BKS.DEP_NAME_KT,
			BKS.SUMMA, CONVERT (VARCHAR (254), BKS.OPER_NAME), BKS.JO_CODE

			FROM #PROV_BKS BKS
			left join dbo.KL_KBK KBKD on BKS.KBK_CODE_DT = replace(KBKD.CODE,'.','')
				OR KBKD.LINK = BKS.KBK_LINK_DT and BKS.KBK_LINK_DT is not null
			left join dbo.BufferGetTableByID(@cBuffIdKBK) BKBKD on KBKD.LINK = BKBKD.LINK
			left join dbo.KL_KBK KBKK on BKS.KBK_CODE_KT = replace(KBKK.CODE,'.','')
				OR KBKK.LINK = BKS.KBK_LINK_KT and BKS.KBK_LINK_KT is not null
			left join dbo.BufferGetTableByID(@cBuffIdKBK) BKBKK on KBKK.LINK = BKBKK.LINK
			left join dbo.KOSGU SGUD on BKS.SGU_CODE_DT = SGUD.CODE
				OR SGUD.LINK = BKS.SGU_LINK_DT and BKS.SGU_LINK_DT is not null
			left join dbo.BufferGetTableByID(@cBuffIdSGU) BSGUD on SGUD.LINK = BSGUD.LINK
			left join dbo.KOSGU SGUK on BKS.SGU_CODE_KT = SGUK.CODE
				OR SGUK.LINK = BKS.SGU_LINK_KT and BKS.SGU_LINK_KT is not null
			left join dbo.BufferGetTableByID(@cBuffIdSGU) BSGUK on SGUK.LINK = BSGUK.LINK
			left join dbo.S_ACCOUNTS ACCD on (BKS.ACC_CODE_DT = replace(ACCD.CODE,'.','') and ACCD.CODE <> ''
				OR ACCD.LINK = BKS.ACC_LINK_DT)
			left join dbo.S_ACCOUNTS ACCK on (BKS.ACC_CODE_KT = replace(ACCK.CODE,'.','') and ACCK.CODE <> ''
				OR ACCK.LINK = BKS.ACC_LINK_KT)
			left join dbo.KOSGU EKRD on (ACCD.P_KASSA = 1 or BKS.SGU_LINK_DT = -1) and isnull(BKS.SGU_LINK_DT,SGUD.LINK) = EKRD.LINK or ACCD.P_KASSA = 0 and (BKS.EKR_CODE_DT = EKRD.CODE OR EKRD.LINK = BKS.EKR_LINK_DT and BKS.EKR_LINK_DT is not null) 
			left join dbo.BufferGetTableByID(@cBuffIdSGU) BEKRD on EKRD.LINK = BEKRD.LINK
			--left join dbo.KOSGU EKRK on (ACCK.P_EKR = 1 and ACCK.ANALIT_EKR = EKRK.LINK  or ACCK.P_EKR = 0 and(ACCK.P_KASSA = 1 and SGUK.LINK = EKRK.LINK or ACCK.P_KASSA = 0 and BKS.EKR_CODE_KT = EKRK.CODE)) 
			left join dbo.KOSGU EKRK on (ACCK.P_KASSA = 1 or BKS.SGU_LINK_KT = -1) and isnull(BKS.SGU_LINK_KT,SGUK.LINK) = EKRK.LINK or ACCK.P_KASSA = 0 and (BKS.EKR_CODE_KT = EKRK.CODE OR EKRK.LINK = BKS.EKR_LINK_KT and BKS.EKR_LINK_KT is not null) 
			left join dbo.BufferGetTableByID(@cBuffIdSGU) BEKRK on EKRK.LINK = BEKRK.LINK
			left join dbo.S_ACCOUNTS ACCD1 on EKRD.IS_EKR = 1 and ACCD1.cSinth = ACCD.cSinth and ACCD1.cSource = ACCD.cSource and ACCD1.ANALIT_EKR = EKRD.LINK
			left join dbo.BufferGetTableByID(@cBuffIdACC) BACCD on ACCD.LINK = BACCD.LINK
			left join dbo.S_ACCOUNTS ACCK1 on EKRK.IS_EKR = 1 and ACCK1.cSinth = ACCK.cSinth and ACCK1.cSource = ACCK.cSource and ACCK1.ANALIT_EKR = EKRK.LINK
			left join dbo.BufferGetTableByID(@cBuffIdACC) BACCK on ACCK.LINK = BACCK.LINK
			--left join dbo.KOSGU EKRD on (ACCD.P_EKR = 1 and ACCD.ANALIT_EKR = EKRD.LINK  or ACCD.P_EKR = 0 and(ACCD.P_KASSA = 1 and SGUD.LINK = EKRD.LINK or ACCD.P_KASSA = 0 and BKS.EKR_CODE_DT = EKRD.CODE)) 
			where	KBKD.LINK is not null and SGUD.LINK is not null and ACCD.LINK is not null and --(EKRD.LINK is not null and (BKS.EKR_CODE_DT <> '' or ACCD.P_EKR = 1 or ACCD.P_EKR = 1) or EKRD.LINK is null and BKS.EKR_CODE_DT = '') and
					KBKK.LINK is not null and SGUK.LINK is not null and ACCK.LINK is not null and --(EKRK.LINK is not null and (BKS.EKR_CODE_DT <> '' or ACCK.P_EKR = 1 or ACCK.P_EKR = 1) or EKRK.LINK is null and BKS.EKR_CODE_DT = '') and
--					(@cBuffIdKBK = '' or @cBuffIdKBK <> '' and BKBKD.LINK is not null and BKBKK.LINK is not null) and
--					(@cBuffIdKBK = '' or @cBuffIdKBK <> '' and (BKBKD.LINK is not null OR BKBKK.LINK is not null)) and
					(@cBuffIdSGU = '' or @cBuffIdSGU <> '' and BSGUD.LINK is not null and BSGUK.LINK is not null and BEKRD.LINK is not null and BEKRK.LINK is not null) and
					(@cBuffIdACC = '' or @cBuffIdACC <> '' and BACCD.LINK is not null and BACCK.LINK is not null)
			ORDER BY BKS.LINK
*/

	DECLARE #CURS_BKS CURSOR STATIC LOCAL FOR 
	SELECT	all BKS.LINK, CONVERT (VARCHAR (15), ISNULL (BKS.NUMBER, '')),
			BKS.[DATE], BKS.DATE_PROV, 
			BKS.DOC_TYPE, BKS.DOC_CODE, BKS.DOC_NAME, BKS.DEP_INN, BKS.COMMENT, BKS.DEP_ACC,
		
			coalesce(ACCD1.LINK,BKS.ACC_LINK_DT,ACCD.LINK) as ACC_LINK_DT, BKS.ACC_CODE_DT, 
			isnull(BKS.KBK_LINK_DT,KBKD.LINK) as KBK_LINK_DT, BKS.KBK_CODE_DT, BKS.KBK_TYPE_DT, 
			isnull(BKS.SGU_LINK_DT,SGUD.LINK) as SGU_LINK_DT, BKS.SGU_CODE_DT, 
			EKRD.LINK as EKR_LINK_DT, EKRD.CODE as EKR_CODE_DT, 
			BKS.DCL_CODE_DT, 
			isnull(BKS.DACC_LINK_DT,null), BKS.DEP_ACC_DT, 
			isnull(BKS.DEP_LINK_DT,null), BKS.DEP_INN_DT, BKS.DEP_NAME_DT, BKS.DEP_OKATO_DT,

			coalesce(ACCK1.LINK,BKS.ACC_LINK_KT,ACCK.LINK) as ACC_LINK_KT, BKS.ACC_CODE_KT, 
			isnull(BKS.KBK_LINK_KT,KBKK.LINK) as KBK_LINK_KT, BKS.KBK_CODE_KT, BKS.KBK_TYPE_KT, 
			isnull(BKS.SGU_LINK_KT,SGUK.LINK) as SGU_LINK_KT, BKS.SGU_CODE_KT, 
			EKRK.LINK as EKR_LINK_KT, EKRK.CODE as EKR_CODE_KT, 
			BKS.DCL_CODE_KT, 
			isnull(BKS.DACC_LINK_KT,null), BKS.DEP_ACC_KT, 
			isnull(BKS.DEP_LINK_KT,null),BKS.DEP_INN_KT, BKS.DEP_NAME_KT, BKS.DEP_OKATO_KT,
			BKS.SUMMA, CONVERT (VARCHAR (254), BKS.OPER_NAME), BKS.JO_CODE

			FROM #PROV_BKS BKS
			left join dbo.KL_KBK KBKD on BKS.KBK_CODE_DT = replace(KBKD.CODE,'.','') and KBK_TYPE_DT = KBKD.TYPE
				OR KBKD.LINK = BKS.KBK_LINK_DT and BKS.KBK_LINK_DT is not null
			left join dbo.BufferGetTableByID(@cBuffIdKBK) BKBKD on KBKD.LINK = BKBKD.LINK
			left join dbo.KL_KBK KBKK on BKS.KBK_CODE_KT = replace(KBKK.CODE,'.','') and KBK_TYPE_KT = KBKK.TYPE
				OR KBKK.LINK = BKS.KBK_LINK_KT and BKS.KBK_LINK_KT is not null
			left join dbo.BufferGetTableByID(@cBuffIdKBK) BKBKK on KBKK.LINK = BKBKK.LINK
			left join dbo.KOSGU SGUD on BKS.SGU_CODE_DT = SGUD.CODE
				OR SGUD.LINK = BKS.SGU_LINK_DT and BKS.SGU_LINK_DT is not null
			left join dbo.BufferGetTableByID(@cBuffIdSGU) BSGUD on SGUD.LINK = BSGUD.LINK
			left join dbo.KOSGU SGUK on BKS.SGU_CODE_KT = SGUK.CODE
				OR SGUK.LINK = BKS.SGU_LINK_KT and BKS.SGU_LINK_KT is not null
			left join dbo.BufferGetTableByID(@cBuffIdSGU) BSGUK on SGUK.LINK = BSGUK.LINK
			left join dbo.S_ACCOUNTS ACCD on (BKS.ACC_CODE_DT = replace(ACCD.CODE,'.','') and ACCD.CODE <> ''
				OR ACCD.LINK = BKS.ACC_LINK_DT)
			left join dbo.S_ACCOUNTS ACCK on (BKS.ACC_CODE_KT = replace(ACCK.CODE,'.','') and ACCK.CODE <> ''
				OR ACCK.LINK = BKS.ACC_LINK_KT)
			left join dbo.KOSGU EKRD on (ACCD.P_KASSA = 1 or BKS.SGU_LINK_DT = -1) and isnull(BKS.SGU_LINK_DT,SGUD.LINK) = EKRD.LINK or ACCD.P_KASSA = 0 and (BKS.EKR_CODE_DT = EKRD.CODE OR EKRD.LINK = BKS.EKR_LINK_DT and BKS.EKR_LINK_DT is not null) 
			left join dbo.BufferGetTableByID(@cBuffIdSGU) BEKRD on EKRD.LINK = BEKRD.LINK
			--left join dbo.KOSGU EKRK on (ACCK.P_EKR = 1 and ACCK.ANALIT_EKR = EKRK.LINK  or ACCK.P_EKR = 0 and(ACCK.P_KASSA = 1 and SGUK.LINK = EKRK.LINK or ACCK.P_KASSA = 0 and BKS.EKR_CODE_KT = EKRK.CODE)) 
			left join dbo.KOSGU EKRK on (ACCK.P_KASSA = 1 or BKS.SGU_LINK_KT = -1) and isnull(BKS.SGU_LINK_KT,SGUK.LINK) = EKRK.LINK or ACCK.P_KASSA = 0 and (BKS.EKR_CODE_KT = EKRK.CODE OR EKRK.LINK = BKS.EKR_LINK_KT and BKS.EKR_LINK_KT is not null) 
			left join dbo.BufferGetTableByID(@cBuffIdSGU) BEKRK on EKRK.LINK = BEKRK.LINK
			left join dbo.S_ACCOUNTS ACCD1 on EKRD.IS_EKR = 1 and ACCD1.cSinth = ACCD.cSinth and ACCD1.cSource = ACCD.cSource and ACCD1.ANALIT_EKR = EKRD.LINK
			left join dbo.BufferGetTableByID(@cBuffIdACC) BACCD on ACCD.LINK = BACCD.LINK
			left join dbo.S_ACCOUNTS ACCK1 on EKRK.IS_EKR = 1 and ACCK1.cSinth = ACCK.cSinth and ACCK1.cSource = ACCK.cSource and ACCK1.ANALIT_EKR = EKRK.LINK
			left join dbo.BufferGetTableByID(@cBuffIdACC) BACCK on ACCK.LINK = BACCK.LINK
			--left join dbo.KOSGU EKRD on (ACCD.P_EKR = 1 and ACCD.ANALIT_EKR = EKRD.LINK  or ACCD.P_EKR = 0 and(ACCD.P_KASSA = 1 and SGUD.LINK = EKRD.LINK or ACCD.P_KASSA = 0 and BKS.EKR_CODE_DT = EKRD.CODE)) 
			where	KBKD.LINK is not null and SGUD.LINK is not null and ACCD.LINK is not null and --(EKRD.LINK is not null and (BKS.EKR_CODE_DT <> '' or ACCD.P_EKR = 1 or ACCD.P_EKR = 1) or EKRD.LINK is null and BKS.EKR_CODE_DT = '') and
					KBKK.LINK is not null and SGUK.LINK is not null and ACCK.LINK is not null and --(EKRK.LINK is not null and (BKS.EKR_CODE_DT <> '' or ACCK.P_EKR = 1 or ACCK.P_EKR = 1) or EKRK.LINK is null and BKS.EKR_CODE_DT = '') and
--					(@cBuffIdKBK = '' or @cBuffIdKBK <> '' and BKBKD.LINK is not null and BKBKK.LINK is not null) and
--					(@cBuffIdKBK = '' or @cBuffIdKBK <> '' and (BKBKD.LINK is not null OR BKBKK.LINK is not null)) and
					(@cBuffIdSGU = '' or @cBuffIdSGU <> '' and BSGUD.LINK is not null and BSGUK.LINK is not null and BEKRD.LINK is not null and BEKRK.LINK is not null) and
					(@cBuffIdACC = '' or @cBuffIdACC <> '' and BACCD.LINK is not null and BACCK.LINK is not null)
			ORDER BY BKS.LINK
	
	--insert into #tProtocol values('Принято ' + ltrim(str(@@rowcount)) + ' проводок',1,0,0)
	
	OPEN #CURS_BKS 
	
	insert into #tProtocol values('Принято ' + ltrim(str(@@rowcount)) + ' проводок',1,0,0)
	insert into #tProtocol values('Сохранение принятых документов',1,0,0)
	
	FETCH FROM #CURS_BKS 
	INTO	@intDOC_BKS, @DOC_NUM, @DOC_DATE, @DATE_PROV, @DOC_TYPE, @DOC_CODE, @DOC_NAME,
			@DEP_INN, @COMMENT, @DEP_ACC,
		
			@intACC_DT, @strACC_CODE_DT, 
			@intKBK_DT, @strKBK_CODE_DT, @intKBK_TYPE_DT, 
			@intSGU_DT, @strSGU_CODE_DT, 
			@intEKR_DT, @strEKR_CODE_DT, 
			@strDCL_CODE_DT,@intDEP_ACC_DT, @strDEP_ACC_DT, 
			@intDEP_DT, @strDEP_INN_DT, @strDEP_NAME_DT, @strDEP_OKATO_DT,

			@intACC_KT, @strACC_CODE_KT, 
			@intKBK_KT, @strKBK_CODE_KT, @intKBK_TYPE_KT, 
			@intSGU_KT, @strSGU_CODE_KT, 
			@intEKR_KT, @strEKR_CODE_KT, 
			@strDCL_CODE_KT, @intDEP_ACC_KT, @strDEP_ACC_KT, 
			@intDEP_KT, @strDEP_INN_KT, @strDEP_NAME_KT, @strDEP_OKATO_KT,
			
			@nSUMMA, @strNAME_OPER_G1, @strJO_CODE
	
	SELECT @intCount_Prov_Save = 0,
		@intCount_Doc_Save = 0

	WHILE @@FETCH_STATUS = 0 
	BEGIN
		--- Выбор документа для СМЕТЫ, если нет, то создаем новый ---
		SELECT @intDOC_SMETA = (SELECT DOC_SMETA FROM @TABLE_DOCS WHERE DOC_BKS = @intDOC_BKS)
		
					
		--- Создание нового документа в смете ---
		IF @intDOC_SMETA IS NULL
		BEGIN
			insert into #tProtocol values('Прием документа "' + @DOC_NAME + '" №' + isnull(@DOC_NUM,'') + isnull(' от ' + ltrim(rtrim(convert(char(20),@DOC_DATE,104))),''),1,0,0)
			if exists(select * from dbo.DOCUMENTS_OPER G where NUMBER = isnull(@DOC_NUM,'') and DATE = @DOC_DATE and DATE_PROV = @DATE_PROV and DEP_LINK = @intDEP_LINK and KIND_CODE_BKS = @DOC_CODE) and
				not exists(select * from @TABLE_DOCS where @DATE_PROV = DATE_PROV and DATE = @DOC_DATE and @DOC_NUM = DOC_NUM and @DOC_CODE = DOC_CODE) or 
				(@DOC_CODE = 'DOCUMENTS_0401002' and exists(select P.* 
															from dbo.DOCUMENTS_PAY P 
															inner join dbo.G_PROV1 G1 on G1.LINK_UP = P.LINK  
															inner join dbo.G_PROV2 G2 on G2.LINK_UP = G1.LINK and G2.SUMMA = @nSUMMA  
															where P.NUMBER = isnull(@DOC_NUM,'') and P.DATE_PROV = @DATE_PROV and P.DATE = @DOC_DATE and P.DEP_LINK = @intDEP_LINK))
				insert into #tProtocol values('Документ "' + @DOC_NAME + '" №' + isnull(@DOC_NUM,'') + isnull(' от ' + ltrim(rtrim(convert(char(20),@DOC_DATE,104))),'') + ' уже существует. ',1,0,1)
			else
			begin
				SELECT @intDEP_ACC = (SELECT TOP 1 LINK FROM dbo.DEPARTMENT_ACCOUNTS WHERE CODE = @DEP_ACC)
				insert into #tProtocol values('Создание документа "' + @DOC_NAME + '" №' + isnull(@DOC_NUM,'') + isnull(' от ' + ltrim(rtrim(convert(char(20),@DOC_DATE,104))),''),1,0,1)
			
				SELECT @COMMENT = 'Принят из БКС: ' + ISNULL (@COMMENT, RTRIM (ISNULL (@DOC_NAME, '')))
				EXEC @intERROR = dbo.X_SAVE_DOCUMENTS_OPER @intDOC_SMETA OUTPUT, @DOC_NUM, @DOC_DATE, @DATE_PROV,
					0, @COMMENT, DEFAULT, @DOC_TYPE, @intDEP_LINK, @intDEP_ACC
				IF @intERROR <> 0
					RETURN @intERROR
				
				SET @intCount_Doc_Save = @intCount_Doc_Save + 1

				INSERT INTO @TABLE_DOCS (DOC_BKS, DOC_SMETA, DATE, DATE_PROV, DOC_NUM, DOC_CODE)
				VALUES (@intDOC_BKS, @intDOC_SMETA, @DOC_DATE, @DATE_PROV, @DOC_NUM, @DOC_CODE) 
			end
		END	-- IF @intDOC_SMETA IS NULL
	
		IF @intDOC_SMETA IS NULL
		BEGIN
			insert into #tProtocol values('Невозможно создать документ.',1,1,1)
			FETCH FROM #CURS_BKS 
			INTO	@intDOC_BKS, @DOC_NUM, @DOC_DATE, @DATE_PROV, @DOC_TYPE, @DOC_CODE, @DOC_NAME,
			@DEP_INN, @COMMENT, @DEP_ACC,
		
			@intACC_DT, @strACC_CODE_DT, 
			@intKBK_DT, @strKBK_CODE_DT, @intKBK_TYPE_DT, 
			@intSGU_DT, @strSGU_CODE_DT, 
			@intEKR_DT, @strEKR_CODE_DT, 
			@strDCL_CODE_DT,@intDEP_ACC_DT, @strDEP_ACC_DT, 
			@intDEP_DT, @strDEP_INN_DT, @strDEP_NAME_DT, @strDEP_OKATO_DT,

			@intACC_KT, @strACC_CODE_KT, 
			@intKBK_KT, @strKBK_CODE_KT, @intKBK_TYPE_KT, 
			@intSGU_KT, @strSGU_CODE_KT, 
			@intEKR_KT, @strEKR_CODE_KT, 
			@strDCL_CODE_KT, @intDEP_ACC_KT, @strDEP_ACC_KT, 
			@intDEP_KT, @strDEP_INN_KT, @strDEP_NAME_KT, @strDEP_OKATO_DT,
			
			@nSUMMA, @strNAME_OPER_G1, @strJO_CODE
			CONTINUE
		END

		--select @strDEP_INN_DT, @strDEP_NAME_DT, @strDEP_INN_KT, @strDEP_NAME_KT,@DOC_NUM
		--- ВЫЧИСЛЕНИЕ ЗНАЧЕНИЯ РЕКВИЗИТОВ ПРОВОДКИ (АНАЛИТИКИ) ---
		--- Дебетовая часть ---
		
		set @intDCL_DT = (SELECT TOP 1 LINK
		FROM dbo.DOP_CLASSIF
		WHERE CODE = @strDCL_CODE_DT)

		IF ISNULL (@strDEP_INN_DT, '') <> '' and @intDEP_DT is null
			SELECT TOP 1 @intDEP_DT = LINK
			FROM dbo.DEPARTMENTS  
			WHERE (rtrim(INN) + case INN_DOP when '' then '' else '/' + INN_DOP end) = @strDEP_INN_DT		

		IF @intDEP_ACC_DT is null and ISNULL (@strDEP_ACC_DT, '') <> '' 
			SELECT TOP 1 @intDEP_ACC_DT = LINK
			FROM dbo.DEPARTMENT_ACCOUNTS
			WHERE CODE = @strDEP_ACC_DT
				
		if isnull(@strDCL_CODE_DT,'') <> '' and @intDCL_DT is null
			insert into #tProtocol values('В справочнике не найдена доп. классификация: ' + @strDCL_CODE_DT,1 ,1,2)

	
		--print @strDEP_INN_DT
		if isnull(@strDEP_INN_DT,'') <> '' and isnull(@strDEP_NAME_DT,'') <> '' and @intDEP_DT is null
		begin
			select @cDepNextCode = cast(ISNULL(MAX(CONVERT(bigint, CODE)),0) + 1 as varchar(10))  
			FROM  dbo.DEPARTMENTS
			where dbo.CheckIsNumeric(CODE) = 1
			insert into dbo.DEPARTMENTS (CODE, INN, [NAME], FULL_NAME, TYPE, OKATO)
			values(@cDepNextCode,@strDEP_INN_DT,@strDEP_NAME_DT,@strDEP_NAME_DT,1, ISNULL(@strDEP_OKATO_DT,''))
			insert into #tProtocol values('Организация ' + @strDEP_NAME_DT + ' с ИНН: ' + @strDEP_INN_DT + ' добалена в справочник',1 ,1,2)
		end

		if isnull(@strDEP_INN_DT,'') <> '' and @intDEP_DT is null
				insert into #tProtocol values('В справочнике не найдена организация с ИНН: ' + @strDEP_INN_DT,1 ,1,2)

		if isnull(@strDEP_ACC_DT,'') <> '' and @intDEP_ACC_DT is null
				insert into #tProtocol values('В справочнике не найден счет организации: ' + @strDEP_ACC_DT,1 ,1,2)
		
	--	select @strDEP_INN_KT,@strDEP_NAME_KT,@strDEP_NAME_KT
	
--- Кредитовая часть ---
		
		set @intDCL_KT = (SELECT TOP 1 LINK
		FROM dbo.DOP_CLASSIF
		WHERE CODE = @strDCL_CODE_KT)	 

		IF ISNULL (@strDEP_INN_KT, '') <> '' and @intDEP_KT is null
			SELECT TOP 1 @intDEP_KT = LINK
			FROM dbo.DEPARTMENTS  
			WHERE (rtrim(INN) + case INN_DOP when '' then '' else '/' + INN_DOP end) = @strDEP_INN_KT		

		IF @intDEP_ACC_KT is null and ISNULL (@strDEP_ACC_KT, '') <> '' 
			SELECT TOP 1 @intDEP_ACC_KT = LINK
			FROM dbo.DEPARTMENT_ACCOUNTS
			WHERE CODE = @strDEP_ACC_KT

		if isnull(@strDCL_CODE_KT,'') <> '' and @intDCL_KT is null
			insert into #tProtocol values('В справочнике не найдена доп. классификация: ' + @strDCL_CODE_KT,1 ,1,2)

		if isnull(@strDEP_INN_KT,'') <> '' and @intDEP_KT is null and isnull(@strDEP_NAME_KT,'') <> '' 
		begin	
			select @cDepNextCode = cast(ISNULL(MAX(CONVERT(bigint, CODE)),0) + 1 as varchar(10))  
			FROM  dbo.DEPARTMENTS
			where dbo.CheckIsNumeric(CODE) = 1
			insert into dbo.DEPARTMENTS (CODE, INN, [NAME], FULL_NAME, TYPE, OKATO)
			values(@cDepNextCode,@strDEP_INN_KT,@strDEP_NAME_KT,@strDEP_NAME_KT,1, ISNULL(@strDEP_OKATO_KT,''))
			insert into #tProtocol values('Организация ' + @strDEP_NAME_KT + ' с ИНН: ' + @strDEP_INN_KT + ' добалена в справочник',1 ,1,2)
		end		

		if isnull(@strDEP_INN_KT,'') <> '' and @intDEP_KT is null
				insert into #tProtocol values('В справочнике не найдена организация с ИНН: ' + @strDEP_INN_KT,1 ,1,2)

		if isnull(@strDEP_ACC_KT,'') <> '' and @intDEP_ACC_KT is null
				insert into #tProtocol values('В справочнике не найден счет организации: ' + @strDEP_ACC_KT,1 ,1,2)

		IF @intACC_DT IS NULL OR @intACC_KT IS NULL
		BEGIN
			
			insert into #tProtocol values('Отсутствуе счет:' + case when @intACC_DT is null then @strACC_CODE_DT else '' end + '  ' + case when @intACC_KT is null then @strACC_CODE_KT else '' end,1,1,2)
			FETCH FROM #CURS_BKS 
			INTO	@intDOC_BKS, @DOC_NUM, @DOC_DATE, @DATE_PROV, @DOC_TYPE, @DOC_CODE, @DOC_NAME,
			@DEP_INN, @COMMENT, @DEP_ACC,
		
			@intACC_DT, @strACC_CODE_DT, 
			@intKBK_DT, @strKBK_CODE_DT, @intKBK_TYPE_DT, 
			@intSGU_DT, @strSGU_CODE_DT, 
			@intEKR_DT, @strEKR_CODE_DT, 
			@strDCL_CODE_DT,@intDEP_ACC_DT, @strDEP_ACC_DT, 
			@intDEP_DT, @strDEP_INN_DT, @strDEP_NAME_DT, @strDEP_OKATO_DT,

			@intACC_KT, @strACC_CODE_KT, 
			@intKBK_KT, @strKBK_CODE_KT, @intKBK_TYPE_KT, 
			@intSGU_KT, @strSGU_CODE_KT, 
			@intEKR_KT, @strEKR_CODE_KT, 
			@strDCL_CODE_KT, @intDEP_ACC_KT, @strDEP_ACC_KT, 
			@intDEP_KT, @strDEP_INN_KT, @strDEP_NAME_KT, @strDEP_OKATO_DT,
			
			@nSUMMA, @strNAME_OPER_G1, @strJO_CODE
			CONTINUE
		END
		if exists(select * from dbo.S_ACCOUNTS where LINK = @intACC_DT and P_KASSA = 1)
			select @intEKR_DT = @intSGU_DT, @strEKR_CODE_DT = @strSGU_CODE_DT

		if exists(select * from dbo.S_ACCOUNTS where LINK = @intACC_DT and P_EKR = 1)
			select @intEKR_DT = EKR.LINK, @strEKR_CODE_DT = EKR.CODE
			from dbo.S_ACCOUNTS SA
			inner join dbo.KOSGU EKR on SA.ANALIT_EKR = EKR.LINK
			where SA.LINK = @intACC_DT 

		if exists(select * from dbo.S_ACCOUNTS where LINK = @intACC_KT and P_KASSA = 1)
			select @intEKR_KT = @intSGU_KT, @strEKR_CODE_KT = @strSGU_CODE_KT

		if exists(select * from dbo.S_ACCOUNTS where LINK = @intACC_KT and P_EKR = 1)
			select @intEKR_KT = EKR.LINK, @strEKR_CODE_KT = EKR.CODE
			from dbo.S_ACCOUNTS SA
			inner join dbo.KOSGU EKR on SA.ANALIT_EKR = EKR.LINK
			where SA.LINK = @intACC_KT 


	
		insert into #tProtocol values('Сохранение операции ' + @strNAME_OPER_G1,1,1,2)
		--- Сохранение операции (G_PROV1) ---
		SELECT @intLINK_G1 = NULL
		SELECT @intORDERS_G1 = (SELECT MAX (ORDERS) FROM dbo.G_PROV1 WHERE LINK_UP = @intDOC_SMETA)
		SELECT @intORDERS_G1 = ISNULL (@intORDERS_G1, 0) + 1
			
			
		EXEC @intERROR = dbo.X_UPDATE_G_PROV1 @intLINK_G1 OUTPUT, @intDOC_SMETA, NULL,
			@strNAME_OPER_G1, @intORDERS_G1
		IF @intERROR <> 0
			RETURN @intERROR
		
					
		IF @intLINK_G1 IS NULL
		BEGIN
			insert into #tProtocol values('Ошибка при создании операции ' + @strNAME_OPER_G1,1,1,3)
			FETCH FROM #CURS_BKS 
			INTO	@intDOC_BKS, @DOC_NUM, @DOC_DATE, @DATE_PROV, @DOC_TYPE, @DOC_CODE, @DOC_NAME,
			@DEP_INN, @COMMENT, @DEP_ACC,
		
			@intACC_DT, @strACC_CODE_DT, 
			@intKBK_DT, @strKBK_CODE_DT, @intKBK_TYPE_DT, 
			@intSGU_DT, @strSGU_CODE_DT, 
			@intEKR_DT, @strEKR_CODE_DT, 
			@strDCL_CODE_DT,@intDEP_ACC_DT, @strDEP_ACC_DT, 
			@intDEP_DT, @strDEP_INN_DT, @strDEP_NAME_DT, @strDEP_OKATO_DT,

			@intACC_KT, @strACC_CODE_KT, 
			@intKBK_KT, @strKBK_CODE_KT, @intKBK_TYPE_KT, 
			@intSGU_KT, @strSGU_CODE_KT, 
			@intEKR_KT, @strEKR_CODE_KT, 
			@strDCL_CODE_KT, @intDEP_ACC_KT, @strDEP_ACC_KT, 
			@intDEP_KT, @strDEP_INN_KT, @strDEP_NAME_KT, @strDEP_OKATO_DT,
			
			@nSUMMA, @strNAME_OPER_G1, @strJO_CODE
			CONTINUE
		END

		--- Сохранение проводки (G_PROV2) ---
		
		SELECT @intLINK_G2 = NULL
		SELECT @intORDERS_G2 = (SELECT MAX (ORDERS) FROM dbo.G_PROV2 WHERE LINK_UP = @intLINK_G1)
		SELECT @intORDERS_G2 = ISNULL (@intORDERS_G2, 0) + 1
		SELECT @intECON_OPER = NULL

		SELECT TOP 1 @intECON_OPER = LINK
		FROM dbo.BX_BPROV_VIBOR_ECON_OPER (@intACC_DT, @intACC_KT)

		SET @strNAME_OPER_G2 = @strNAME_OPER_G1

		insert into #tProtocol values('Сохранение проводки: Дт "' + @strACC_CODE_DT + ' КБК: ' + @strKBK_CODE_DT + ' СГУ: ' + @strSGU_CODE_DT + ' ЭКР: ' + @strEKR_CODE_DT + ' Доп.кл: ' + @strDCL_CODE_DT + ' Орг.: ' + @strDEP_INN_DT + ' Счет.: ' + @strDEP_ACC_DT,1,0,3)
		insert into #tProtocol values('						Кт "' + @strACC_CODE_KT + ' КБК: ' + @strKBK_CODE_KT + ' СГУ: ' + @strSGU_CODE_KT + ' ЭКР: ' + @strEKR_CODE_KT + ' Доп.кл: ' + @strDCL_CODE_KT + ' Орг.: ' + @strDEP_INN_KT + ' Счет.: ' + @strDEP_ACC_KT,1,0,3)
		insert into #tProtocol values('						сумма ' + str(@nSUMMA,20,2),1,1,2) 
		EXEC @intERROR = dbo.X_UPDATE_G_PROV2 @intLINK_G2 OUTPUT, @intLINK_G1, NULL,
			@nSUMMA, 0, 0, @strNAME_OPER_G2, @intECON_OPER, @intORDERS_G2
		IF @intERROR <> 0
			RETURN @intERROR
			
		
		IF @intLINK_G2 IS NULL
		BEGIN
			insert into #tProtocol values('Ошибка при создании проводки ' + @strNAME_OPER_G2,1,1,3)
			FETCH FROM #CURS_BKS 
			INTO	@intDOC_BKS, @DOC_NUM, @DOC_DATE, @DATE_PROV, @DOC_TYPE, @DOC_CODE, @DOC_NAME,
			@DEP_INN, @COMMENT, @DEP_ACC,
		
			@intACC_DT, @strACC_CODE_DT, 
			@intKBK_DT, @strKBK_CODE_DT, @intKBK_TYPE_DT, 
			@intSGU_DT, @strSGU_CODE_DT, 
			@intEKR_DT, @strEKR_CODE_DT, 
			@strDCL_CODE_DT,@intDEP_ACC_DT, @strDEP_ACC_DT, 
			@intDEP_DT, @strDEP_INN_DT, @strDEP_NAME_DT, @strDEP_OKATO_DT,

			@intACC_KT, @strACC_CODE_KT, 
			@intKBK_KT, @strKBK_CODE_KT, @intKBK_TYPE_KT, 
			@intSGU_KT, @strSGU_CODE_KT, 
			@intEKR_KT, @strEKR_CODE_KT, 
			@strDCL_CODE_KT, @intDEP_ACC_KT, @strDEP_ACC_KT, 
			@intDEP_KT, @strDEP_INN_KT, @strDEP_NAME_KT, @strDEP_OKATO_DT,
			
			@nSUMMA, @strNAME_OPER_G1, @strJO_CODE
			CONTINUE
		END

/*
CREATE                  PROCEDURE X_UPDATE_G_PROV_AP
	@varKSLink_Up	INT,
	@varKSDB_KR	tinyint,
	@varKSAccount	INT,
	@varKSKBK		INT,
	@varKSEKR		INT,
	@varKSDEP		INT,
	@varKSSUB		INT,
	@varKSEMP		INT,
	@varKSNOMEN	INT,
	@varKSINV		INT,
	@varKSKAU		INT,
	@varKSDEP_ACC	INT,
	@varKSTMC 		INT,
	@varKSINDATE	DATETIME,
	@varKSAP1		INT,
	@varKSAP2		INT,
	@varKSAP3		INT,
	@varKSSGU		INT = null
*/
		--- Сохранение аналитики (Дебет) ---
		
				
		EXEC @intERROR = dbo.X_UPDATE_G_PROV_AP @intLINK_G2, 0, @intACC_DT, @intKBK_DT, @intEKR_DT, 
			@intDEP_DT, NULL, NULL, NULL, NULL, NULL, @intDEP_ACC_DT, NULL, NULL,
			NULL, @intDCL_DT, NULL, @intSGU_DT 
		IF @intERROR <> 0
			RETURN @intERROR

		
		--- Сохранение аналитики (Кредит) ---
		EXEC @intERROR = dbo.X_UPDATE_G_PROV_AP @intLINK_G2, 1, @intACC_KT, @intKBK_KT, @intEKR_KT, 
			@intDEP_KT, NULL, NULL, NULL, NULL, NULL, @intDEP_ACC_KT, NULL, NULL,
			NULL, @intDCL_KT, NULL, @intSGU_KT 
		IF @intERROR <> 0
			RETURN @intERROR
		
		SELECT @intCount_Prov_Save = @intCount_Prov_Save + 1
		FETCH FROM #CURS_BKS 
		INTO	@intDOC_BKS, @DOC_NUM, @DOC_DATE, @DATE_PROV, @DOC_TYPE, @DOC_CODE, @DOC_NAME,
			@DEP_INN, @COMMENT, @DEP_ACC,
		
			@intACC_DT, @strACC_CODE_DT, 
			@intKBK_DT, @strKBK_CODE_DT, @intKBK_TYPE_DT, 
			@intSGU_DT, @strSGU_CODE_DT, 
			@intEKR_DT, @strEKR_CODE_DT, 
			@strDCL_CODE_DT,@intDEP_ACC_DT, @strDEP_ACC_DT, 
			@intDEP_DT, @strDEP_INN_DT, @strDEP_NAME_DT, @strDEP_OKATO_DT,

			@intACC_KT, @strACC_CODE_KT, 
			@intKBK_KT, @strKBK_CODE_KT, @intKBK_TYPE_KT, 
			@intSGU_KT, @strSGU_CODE_KT, 
			@intEKR_KT, @strEKR_CODE_KT, 
			@strDCL_CODE_KT, @intDEP_ACC_KT, @strDEP_ACC_KT, 
			@intDEP_KT, @strDEP_INN_KT, @strDEP_NAME_KT, @strDEP_OKATO_DT,
			
			@nSUMMA, @strNAME_OPER_G1, @strJO_CODE
		END
	
	CLOSE #CURS_BKS
	DEALLOCATE #CURS_BKS
	
	exec dbo.X_SALDO_CommitChanges
	--SELECT * FROM #PROV_BKS
	insert into #tProtocol values('Сохранено документов: ' + LTRIM (STR (@intCount_DOC_Save)),1,0,0)
	insert into #tProtocol values('Сохранено проводок: ' + LTRIM (STR (@intCount_Prov_Save)),1,0,0)

	DROP TABLE #PROV_BKS
	
	exec dbo.BufferClear @cBufferID
	exec dbo.BufferClear @cBuffIdKBK
	exec dbo.BufferClear @cBuffIdSGU
	exec dbo.BufferClear @cBuffIdACC
	--SELECT * FROM @TABLE_DOCS
	select * from #tProtocol
	RETURN 0

END	--- END PROC ---

GO


GRANT ALL ON dbo.[BK_IMPORT_PROV_FROM_BKS] TO PUBLIC
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 '20151001', '20150331', 13488 ,1,  252

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

	DECLARE @PREDEL NUMERIC(18,2)
	SET @PREDEL = ISNULL((SELECT MIN(PREDEL) FROM dbo.DICTIONARY_RANGE_PF WHERE WAY_CALC = 6 AND TARIF = 1 AND [DATE] >= dbo.ConvertDMY2Date(1,1,YEAR(@dDate1))),0)
	-----------

	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),			
			[INSUR] = ROUND(CONVERT(NUMERIC(18,2),
						sum(
						CASE WHEN ISNULL(S.BASE_AFTER_M1,0) + ISNULL(S.BASE_AFTER_M2,0) + ISNULL(S.BASE_AFTER_M3,0) <> 0 THEN
								ISNULL(S.BASE_BEFORE_M1,0) * PERCENT1 / 100 + ISNULL(S.BASE_BEFORE_M2,0) * PERCENT1 / 100 + ISNULL(S.BASE_BEFORE_M3,0) * PERCENT1 / 100
							ELSE
								ISNULL(S.sum_doh,0)
							END						
						)
						),@ROUND_LEN,@ROUND_TYPE),
			[INSUR1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_str)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_nak)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dop)),@ROUND_LEN,@ROUND_TYPE),
			sd_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_str)),@ROUND_LEN,@ROUND_TYPE),
			sud_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_str)),@ROUND_LEN,@ROUND_TYPE),
			sd_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_nak)),@ROUND_LEN,@ROUND_TYPE),
			sud_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_nak)),@ROUND_LEN,@ROUND_TYPE),
			[PER] = ISNULL(CASE WHEN year_begin >= 2013 THEN PER ELSE NULL END ,0) ,
			[PER10] = ISNULL(CASE WHEN year_begin >= 2013 THEN PER ELSE NULL END ,0) ,
			[TYPE] = p.[vid_kor],
			[PER_EDT] = ISNULL(PER_EDT,0),
			[YEAR_EDT] = ISNULL(YEAR_EDT,0),
			[T_DOG] = s.forma,
			DATE_CRT = '20131201',
			DATE_DOC = [date],
			SZV = MAX(S.forma),
			FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),year_begin) + '-ORG-' + LTRIM(RTRIM(d.PFNUMBER)) + '-DCK-' + REPLACE(str(S.pachka,5),' ','0') + '-DPT-000000-DCK-00000.XML',
			LINK_DOC = P.link,
			link_pers = S.link_pers,
			LINK_KATEG = (case when S.LINK_KATEG = 3 then 1 else  S.LINK_KATEG  end )
		into #TMP
		from
			dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up  AND (s.forma = 1
															OR s.forma = 2 AND NOt EXISTS(SELECT * from dbo.SZV4_SVEDENIA WHERE  link_up = S.link_up and link_pers = s.link_pers AND forma = 1) )
			
			INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND
			inner join departments d on d.link = p.link_dep
			INNER JOIN
			(
				SELECT
					TARIF, PERCENT1
				FROM
					dbo.DICTIONARY_RANGE_PF D
				WHERE
					WAY_CALC = 6 AND PREDEL = @PREDEL
					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 WAY_CALC = 6 AND DATE <= @dDate1 ORDER BY [DATE] DESC)
			) C ON C.TARIF = K.LINK2 			
		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], S.link_pers, S.LINK_KATEG
		order by
			S.pachka

		Select 	
			[YEAR] = ISNULL(CASE WHEN year_begin >= 2013 THEN year_begin ELSE NULL END ,0),
			[NGROUP] = S.pachka,
			[DOCCOUNT] = COALESCE(MAX(case when S.forma = 2 then CEILING (CAST(S.orders AS FLOAT) /5 ) else 0 end),0)
					+ SUM(case when S.forma = 1 then 1 else 0 end),
			[PERS_CNT] = COUNT(S.orders),
			[cGRP] = REPLACE(str(S.pachka,5),' ','0'),
			[OPT1] = (case when p.type = 1 then 1 else 0 end),
			[OPT2] = (case when p.type = 2 then 1 else 0 end),
			[OPT3] = (case when vid_kor = 2 then 1 else 0 end),
			[OPT4] = (case when vid_kor = 3 then 1 else 0 end),
			INC_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.INCOME_M1)),@ROUND_LEN,@ROUND_TYPE),																																	
			INC_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.INCOME_M2)),@ROUND_LEN,@ROUND_TYPE),																														
			INC_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.INCOME_M3)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M1)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M2)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M3)),@ROUND_LEN,@ROUND_TYPE),
			B_AFT_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_AFTER_M1)),@ROUND_LEN,@ROUND_TYPE),
			B_AFT_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_AFTER_M2)),@ROUND_LEN,@ROUND_TYPE),
			B_AFT_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_AFTER_M3)),@ROUND_LEN,@ROUND_TYPE),
			--[INSUR] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_doh)),@ROUND_LEN,@ROUND_TYPE),
			[INSUR] = ROUND(CONVERT(NUMERIC(18,2),
						sum(
						CASE WHEN ISNULL(S.BASE_AFTER_M1,0) + ISNULL(S.BASE_AFTER_M2,0) + ISNULL(S.BASE_AFTER_M3,0) <> 0 THEN
								ISNULL(S.BASE_BEFORE_M1,0) * PERCENT1 / 100 + ISNULL(S.BASE_BEFORE_M2,0) * PERCENT1 / 100 + ISNULL(S.BASE_BEFORE_M3,0) * PERCENT1 / 100
							ELSE
								ISNULL(S.sum_doh,0)
							END						
						)
						),@ROUND_LEN,@ROUND_TYPE),			
			[INSUR1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_str)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_nak)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dop)),@ROUND_LEN,@ROUND_TYPE),
			sd_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_str)),@ROUND_LEN,@ROUND_TYPE),
			sud_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_str)),@ROUND_LEN,@ROUND_TYPE),
			sd_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_nak)),@ROUND_LEN,@ROUND_TYPE),
			sud_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_nak)),@ROUND_LEN,@ROUND_TYPE),
			[PER] = ISNULL(CASE WHEN year_begin >= 2013 THEN PER ELSE NULL END ,0),
			[PER10] = ISNULL(CASE WHEN year_begin >= 2013 THEN PER ELSE NULL END ,0),
			[TYPE] = p.[vid_kor],
			[PER_EDT] = ISNULL(PER_EDT,0),
			[YEAR_EDT] = ISNULL(YEAR_EDT,0),
			[T_DOG] = s.forma,
			DATE_CRT = '20131201',
			DATE_DOC = [date],
			SZV = MAX(S.forma),
			FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),year_begin) + '-ORG-' + LTRIM(RTRIM(d.PFNUMBER)) + '-DCK-' + REPLACE(str(S.pachka,5),' ','0') + '-DPT-000000-DCK-00000.XML',
			LINK_DOC = P.link,
			link_pers = S.link_pers,
			LINK_KATEG = (case when S.LINK_KATEG = 3 then 1 else  S.LINK_KATEG  end )
		into #TMP_1
		from
			dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up
																	and s.forma = 2
																	AND EXISTS(SELECT * from dbo.SZV4_SVEDENIA WHERE  link_up = S.link_up and link_pers = s.link_pers AND forma = 1)
			
			INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND
			inner join departments d on d.link = p.link_dep
			INNER JOIN
			(
				SELECT
					TARIF, PERCENT1
				FROM
					dbo.DICTIONARY_RANGE_PF D
				WHERE
					WAY_CALC = 6 AND PREDEL = @PREDEL
					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 WAY_CALC = 6 AND DATE <= @dDate1 ORDER BY [DATE] DESC)
			) C ON C.TARIF = K.LINK2 				
		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] , S.link_pers,S.LINK_KATEG
		order by
			S.pachka


		UPDATE t
			SEt t.INC_M1 = t.INC_M1+ t1.INC_M1,
				t.INC_M2 = t.INC_M2+ t1.INC_M2,
				t.INC_M3 = t.INC_M3 + t1.INC_M3 ,
				t.B_BEF_M1 = t.B_BEF_M1 + t1.B_BEF_M1,
				t.B_BEF_M2 = t.B_BEF_M2 + t1.B_BEF_M2,
				t.B_BEF_M3 = t.B_BEF_M3 + t1.B_BEF_M3,
				t.B_AFT_M1 = t.B_AFT_M1 + t1.B_AFT_M1,
				t.B_AFT_M2 = t.B_AFT_M2 + t1.B_AFT_M2,
				t.B_AFT_M3 = t.B_AFT_M3 + t1.B_AFT_M3,
				t.[INSUR] =  t.[INSUR] + t1.[INSUR] ,
				t.[INSUR1] = t.[INSUR1] + t1.[INSUR1],
				t.[GAIN] = t.[GAIN] + t1.[GAIN] ,
				t.[GAIN1] = t.[GAIN1] + t1.[GAIN1] ,
				t.sd_str = t.sd_str + t1.sd_str,
				t.sud_str = t.sud_str + t1.sud_str,
				t.sd_nak = t.sd_nak + t1.sd_nak,
				t.sud_nak = t.sud_nak + t1.sud_nak
		FROM #TMP t inner join #TMP_1 t1 ON t.LINK_PERS = t1.link_pers


		UPDATE T
				SET	FNAME = REPLACE( FNAME, REPLACE(str(((SELECT MAX(nGROUP) FROM #TMP  where link_pers =t.link_pers )),5)+'-',' ','0'),REPLACE(str(((SELECT MIN(nGROUP) FROM #TMP  where link_pers =t.link_pers )),5)+'-',' ','0')),
					nGROUP = (SELECT MIN(nGROUP) FROM #TMP  where link_pers =t.link_pers ),
					cGRP = REPLACE(str((SELECT MIN(nGROUP) FROM #TMP  where link_pers =t.link_pers ),5),' ','0')
		FROM #TMP T
		WHERE t.link_pers in (SELECT link_pers FROM #TMP  GROUP BY link_pers/*,LINK_KATEG*/ HAVING COUNT(link_pers) > 1)


		SELECT
			CODE = CONVERT(VARCHAR(10), [NGROUP]),
			COL1 = CONVERT(VARCHAR(10),[NGROUP]),
			COL2 = CONVERT(VARCHAR(10),''),
			COL3 = isnull((SUM(isnull(b_bef_m1,0)) + SUM(isnull(b_bef_m2,0)) + SUM(isnull(b_bef_m3,0))),0.00),
			COL4 = SUM(isnull(insur,0.00)),
			COL5 = SUM(ISNULL(pers_cnt,0)),
			COL6 = isnull(fname,''),
			COL7 = CONVERT(VARCHAR(10), date_doc, 104),
			COL8 = [TYPE],
			COL9 = PER,
			COL10 = [YEAR],
			COL11 = [LINK_DOC]
		FROM
			#TMP
		GROUP BY
			[NGROUP], fname , date_doc	, [TYPE] , PER , [YEAR] , [LINK_DOC]
		ORDER BY
			NGROUP


		--exec [dbo].RSA_RSV_1_PERS_UCH '20151001', '20150331', 74578 ,0,  2775


		drop table #TMP	
		drop table #TMP_1
					
	END
	
	IF @REP = 1
	BEGIN 	
		Select 	
			[YEAR] = ISNULL(CASE WHEN year_begin >= 2013 THEN year_begin ELSE NULL END ,0),
			[MONTH] = ISNULL(month_end ,0),
			[PER] = case PER when 1 then 3 when 2 then 6 when 3 then 9 when 4 then 0 else null end ,
			[NGROUP] = S.pachka,
			[cGRP] = REPLACE(str(S.pachka,5),' ','0'),
			[CODE] = K.CODE,
			--[INSUR] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_doh)),@ROUND_LEN,@ROUND_TYPE),
			[INSUR] = ROUND(CONVERT(NUMERIC(18,2),
						sum(
						CASE WHEN ISNULL(S.BASE_AFTER_M1,0) + ISNULL(S.BASE_AFTER_M2,0) + ISNULL(S.BASE_AFTER_M3,0) <> 0 THEN
								ISNULL(S.BASE_BEFORE_M1,0) * PERCENT1 / 100 + ISNULL(S.BASE_BEFORE_M2,0) * PERCENT1 / 100 + ISNULL(S.BASE_BEFORE_M3,0) * PERCENT1 / 100
							ELSE
								ISNULL(S.sum_doh,0)
							END						
						)
						),@ROUND_LEN,@ROUND_TYPE),				
			[INSUR1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_str)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_nak)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dop)),@ROUND_LEN,@ROUND_TYPE),
			sd_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_str)),@ROUND_LEN,@ROUND_TYPE),
			sud_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_str)),@ROUND_LEN,@ROUND_TYPE),
			sd_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_nak)),@ROUND_LEN,@ROUND_TYPE),
			sud_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_nak)),@ROUND_LEN,@ROUND_TYPE),		
			[PERS_CNT] = COUNT(S.orders),
			[PER_EDT] = case ISNULL(PER_EDT,0 ) when 1 then 3 when 2 then 6 when 3 then 9 when 4 then 0 else null end ,
			[YEAR_EDT] = ISNULL(YEAR_EDT,0),
			FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),year_begin) + '-ORG-' + LTRIM(RTRIM(d.PFNUMBER)) + '-DCK-' + REPLACE(str(S.pachka,5),' ','0') + '-DPT-000000-DCK-00000.XML',
			IT_ROUND = @IT_ROUND_TYPE,
			DATE_DOC = p.[date],
			[TYPE] = p.[vid_kor],
			B_BEF_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M1)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M2)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M3)),@ROUND_LEN,@ROUND_TYPE),
			[T_DOG] = s.forma,
			LINK_DOC = P.link,
			link_pers = S.link_pers,
			dep_pFNUM = d.PFNUMBER
		into #TMP1
		from
			dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up AND (s.forma = 1
															OR s.forma = 2 AND NOt EXISTS(SELECT * from dbo.SZV4_SVEDENIA WHERE  link_up = S.link_up and link_pers = s.link_pers AND forma = 1) )
			INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND
			inner join departments d on d.link = p.link_dep
			INNER JOIN
			(
				SELECT
					TARIF, PERCENT1
				FROM
					dbo.DICTIONARY_RANGE_PF D
				WHERE
					WAY_CALC = 6 AND PREDEL = @PREDEL
					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 WAY_CALC = 6 AND DATE <= @dDate1 ORDER BY [DATE] DESC)
			) C ON C.TARIF = K.LINK2 				
		where
			P.link in (select link from #docs_kor_otm)
			and P.proverka = 1
			and P.vid_kor > 1
			and p.link_dep = @DEP_LINK
		group by
			s.pachka, s.Forma, year_begin,month_end,per, p.[vid_kor], K.CODE, PER_EDT, YEAR_EDT, d.PFNUMBER, p.[date], P.[link],S.link_pers

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

select @MAX_PACHKA_ISHOD = max(s.pachka),
		@MIN_PACHKA_ISHOD = min(s.pachka),
		@MIN_PACHKA_KORR = (select max(s.pachka) FROM dbo.SA_SZV4_PACHKA p INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up and P.LINK = @ATR_PERS_UCH)
		FROM dbo.SA_SZV4_PACHKA p INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up and P.LINK_ISHOD = @ATR_PERS_UCH

IF @min_PACHKA_ISHOD = @MIN_PACHKA_KORR
BEGIN
	declare @Cur cursor , @GR int , @cGR int
	set @ID = 1
	SET @Cur = CURSOR FORWARD_ONLY
	FOR
		select ngroup,cGRP  from #tmp1 group by ngroup,cGRP
	OPEN @Cur
	FETCH NEXT FROM @Cur INTO @GR, @cGR
	
	WHILE (@@fetch_status <> -1)
	BEGIN
		
		IF (@@fetch_status <> -2)
		BEGIN	

			UPDATE #tmp1
				set NGROUP = @MAX_PACHKA_ISHOD+@ID --, t.[cGRP] =  '00'+ (@MAX_PACHKA_ISHOD+@ID)
			where ngroup = @GR AND cGRP = @cGR
				
			set @ID = @ID+1	
		end
		FETCH NEXT FROM @Cur INTO @GR , @cGR
	end

	CLOSE @Cur
	DEALLOCATE @Cur

END

UPDATE t
	SET  cGRP=  '00'+ convert(varchar(3),NGROUP)
	from #tmp1 t
UPDATE t
	SET  FNAME=  'PFR-700-Y-' + CONVERT(VARCHAR(4),[year]) + '-ORG-' + LTRIM(RTRIM(dep_pFNUM)) + '-DCK-' + REPLACE(str(NGROUP,5),' ','0') + '-DPT-000000-DCK-00000.XML'	
	from #tmp1 t  WHERE TYPE <> 1

		Select 	
			[YEAR] = ISNULL(CASE WHEN year_begin >= 2013 THEN year_begin ELSE NULL END ,0),
			[MONTH] = ISNULL(month_end ,0),
			[PER] =  case PER when 1 then 3 when 2 then 6 when 3 then 9 when 4 then 0 else null end,
			[NGROUP] = S.pachka,
			[cGRP] = REPLACE(str(S.pachka,5),' ','0'),
			[CODE] = K.CODE,
			--[INSUR] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_doh)),@ROUND_LEN,@ROUND_TYPE),
			[INSUR] = ROUND(CONVERT(NUMERIC(18,2),
						sum(
						CASE WHEN ISNULL(S.BASE_AFTER_M1,0) + ISNULL(S.BASE_AFTER_M2,0) + ISNULL(S.BASE_AFTER_M3,0) <> 0 THEN
								ISNULL(S.BASE_BEFORE_M1,0) * PERCENT1 / 100 + ISNULL(S.BASE_BEFORE_M2,0) * PERCENT1 / 100 + ISNULL(S.BASE_BEFORE_M3,0) * PERCENT1 / 100
							ELSE
								ISNULL(S.sum_doh,0)
							END						
						)
						),@ROUND_LEN,@ROUND_TYPE),				
			[INSUR1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_str)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_nak)),@ROUND_LEN,@ROUND_TYPE),
			[GAIN1] = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dop)),@ROUND_LEN,@ROUND_TYPE),
			sd_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_str)),@ROUND_LEN,@ROUND_TYPE),
			sud_str = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_str)),@ROUND_LEN,@ROUND_TYPE),
			sd_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_dolg_nak)),@ROUND_LEN,@ROUND_TYPE),
			sud_nak = ROUND(CONVERT(NUMERIC(18,2),sum(S.sum_uplata_dolga_nak)),@ROUND_LEN,@ROUND_TYPE),		
			[PERS_CNT] = COUNT(S.orders),
			[PER_EDT] = case when YEAR_EDT between '2011' and '2013'  then (case ISNULL(PER_EDT,0) when 1 then 1 when 2 then 2 when 3 then 3 when 4 then 4 else 0 end)
							when YEAR_EDT >= '2014' then (case ISNULL(PER_EDT,0) when 1 then 3 when 2 then 6 when 3 then 9 when 4 then 0 else null end)
							end ,
			[YEAR_EDT] = ISNULL(YEAR_EDT,0),
			FNAME = 'PFR-700-Y-' + CONVERT(VARCHAR(4),year_begin) + '-ORG-' + LTRIM(RTRIM(d.PFNUMBER)) + '-DCK-' + REPLACE(str(S.pachka,5),' ','0') + '-DPT-000000-DCK-00000.XML',
			IT_ROUND = @IT_ROUND_TYPE,
			DATE_DOC = p.[date],
			[TYPE] = p.[vid_kor],
			B_BEF_M1 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M1)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M2 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M2)),@ROUND_LEN,@ROUND_TYPE),
			B_BEF_M3 = ROUND(CONVERT(NUMERIC(18,2),sum(S.BASE_BEFORE_M3)),@ROUND_LEN,@ROUND_TYPE),
			[T_DOG] = s.forma,
			LINK_DOC = P.link,
			link_pers = S.link_pers
		into #TMP1_1
		from
			dbo.SA_SZV4_PACHKA P INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up 																	
																	and s.forma = 2
																	AND EXISTS(SELECT * from dbo.SZV4_SVEDENIA WHERE  link_up = S.link_up and link_pers = s.link_pers AND forma = 1)
			INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = S.LINK_KATEG AND year_begin BETWEEN YBEG AND YEND
			inner join departments d on d.link = p.link_dep
			INNER JOIN
			(
				SELECT
					TARIF, PERCENT1
				FROM
					dbo.DICTIONARY_RANGE_PF D
				WHERE
					WAY_CALC = 6 AND PREDEL = @PREDEL
					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 WAY_CALC = 6 AND DATE < @dDate1 ORDER BY [DATE] DESC)
			) C ON C.TARIF = K.LINK2 				
		where
			P.link in (select link from #docs_kor_otm)
			and P.proverka = 1
			and P.vid_kor > 1
			and p.link_dep = @DEP_LINK
		group by
			s.pachka, s.Forma, year_begin,month_end,per, p.[vid_kor], K.CODE, PER_EDT, YEAR_EDT, d.PFNUMBER, p.[date], P.[link],S.link_pers

		/*Корректирующие сведения по физ лицам*/
		SELECT year_edt = p.YEAR_EDT,
				PER_EDT = p.PER_EDT,
				link_dep = p.link_dep,
				link_pers = s.link_pers,
				Link_kateg = (case when S.LINK_KATEG = 3 then 1 else  S.LINK_KATEG  end ),
				pachka = s.pachka
		INTO #tmp_pers
		FROM 	dbo.SA_SZV4_PACHKA P
				INNER JOIN dbo.SZV4_SVEDENIA S ON P.link = S.link_up 															
		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


		CREATE TABLE #tmp_pers_kor_sum (link INT  , [date] DATETIME, YEAR_degin INT , per INT , vid_kor int, link_dep INT , proverka INT  , CODE VARCHAR(5), link_pers INT ,
										sum_doh NUMERIC(18,2), sum_str NUMERIC(18,2), sum_nak NUMERIC(18,2),sum_dop NUMERIC(18,2) , pachka int)
	
		DECLARE @Cur1 CURSOR, @link int ,@LINK_pers INT, @year_edt INT , @per_edt INT , @Link_kateg INT ,@pachka int
		SET @Cur1 = CURSOR FORWARD_ONLY

		FOR SELECT LINK_pers, year_edt, per_edt, Link_kateg ,pachka FROM #tmp_pers ORDER by link_pers

		OPEN @Cur1
		FETCH NEXT FROM @Cur1 INTO @LINK_pers, @year_edt, @per_edt , @link_kateg, @pachka
		WHILE (@@fetch_status <> -1)
		BEGIN

			IF (@@fetch_status <> -2)
			BEGIN
				
				
					SET @link = 0
					
					SELECT @link =max(pp.link)
					FROM SA_SZV4_PACHKA pp
					INNER JOIN dbo.SZV4_SVEDENIA Ss ON ss.link_up = pp.link
					WHERE  pp.proverka = 1 AND pp.vid_kor = 1
										   and pp.link_dep = @DEP_LINK
										   and pp.year_begin =@year_edt
										   AND pp.PER =@per_edt
										   AND @LINK_pers = ss.link_pers
										   /*AND @link_kateg = ss.link_kateg*/
										   AND pp.date = (SELECT MAX(p1.[date]) FROM SA_SZV4_PACHKA p1
																INNER JOIN dbo.SZV4_SVEDENIA S1 ON s1.link_up = p1.link
																WHERE  p1.proverka = 1 AND p1.vid_kor = 1
																					   and p1.link_dep = @DEP_LINK
																					   and p1.year_begin =@year_edt
																					   AND p1.PER =@per_edt
																					   AND @LINK_pers = s1.link_pers
																					   /*AND @link_kateg = s1.link_kateg*/ )

					INSERT INTO #tmp_pers_kor_sum (link, [date], YEAR_degin, per, vid_kor, link_dep, proverka , CODE, link_pers,
										sum_doh, sum_str, sum_nak,sum_dop, pachka)
					SELECT pp.link, pp.[date], pp.YEAR_begin, pp.per, pp.vid_kor, pp.link_dep, pp.proverka, CODE = k.code, ss.link_pers,
										ss.sum_doh, ss.sum_str, ss.sum_nak,ss.sum_dop , pachka = @pachka
					FROM SA_SZV4_PACHKA pp
					INNER JOIN dbo.SZV4_SVEDENIA Ss ON ss.link_up = pp.link
					INNER JOIN dbo.SA_PFR_KATEG K ON K.LINK = ss.LINK_KATEG AND pp.YEAR_begin BETWEEN YBEG AND YEND		
					WHERE pp.link = @link and pp.proverka = 1
										  AND pp.vid_kor = 1
										  and pp.link_dep = @DEP_LINK
										  and pp.year_begin =@year_edt
										  AND pp.PER =@per_edt
										  AND ss.link_pers = @LINK_pers
										  /*AND ss.link_kateg = @link_kateg*/
										

			END

			FETCH NEXT FROM @Cur1 INTO @LINK_pers, @year_edt, @per_edt, @link_kateg, @pachka
		END

		CLOSE @Cur1
		DEALLOCATE @Cur1


		UPDATE t
			SEt t.[INSUR] =  t.[INSUR] + t1.[INSUR] ,
				t.[INSUR1] = t.[INSUR1] + t1.[INSUR1],
				t.[GAIN] = t.[GAIN] + t1.[GAIN] ,
				t.[GAIN1] = t.[GAIN1] + t1.[GAIN1] ,
				t.sd_str = t.sd_str + t1.sd_str,
				t.sud_str = t.sud_str + t1.sud_str,
				t.sd_nak = t.sd_nak + t1.sd_nak,
				t.sud_nak = t.sud_nak + t1.sud_nak
		FROM #TMP1 t inner join #TMP1_1 t1 ON t.LINK_PERS = t1.link_pers

---------->>>>>>>>>>
declare @SUM_DONACH_STR numeric(18,2),
		@SUM_DONACH_NAK numeric(18,2),
		@SUM_DONACH_STR_I numeric(18,2),
		@SUM_DONACH_NAK_I numeric(18,2)

select  @SUM_DONACH_STR = CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum WHERE CODE = 'НР' ) ,0)),

	    @SUM_DONACH_NAK = CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUM_nak) FROM #tmp_pers_kor_sum WHERE CODE = 'НР') ,0)),
	
		@SUM_DONACH_STR_I = CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum WHERE CODE = 'ООИ') ,0)),
	    @SUM_DONACH_NAK_I = CONVERT(numeric(18,2),ISNULL( (SELECT SUM(SUM_nak) FROM #tmp_pers_kor_sum WHERE CODE = 'ООИ') ,0))

	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 year_edt >= 2014 then SUM(INSUR) - /*(CASE WHEN CODE = 'НР' then*/ (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum WHERE CODE = 'НР' AND pachka = #TMP1.ngroup)
															/*else (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum WHERE CODE <> 'НР' AND pachka = #TMP1.ngroup) end)*/	
													  else 0 end),0),
			COL6 = ISNULL((case when year_edt < 2014 then SUM(INSUR) - /*(CASE WHEN CODE = 'НР' then */(SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum WHERE CODE = 'НР' AND pachka = #TMP1.ngroup)
															/*else (SELECT SUM(SUM_doh) FROM #tmp_pers_kor_sum WHERE CODE <> 'НР' AND pachka = #TMP1.ngroup) end)*/
														else 0 end),0),
			COL7 = ISNULL((case when year_edt < 2014 then SUM(GAIN) - /*(CASE WHEN CODE = 'НР' then */(SELECT SUM(SUM_nak) FROM #tmp_pers_kor_sum WHERE CODE = 'НР' AND pachka = #TMP1.ngroup)
															/*else (SELECT SUM(SUM_nak) FROM #tmp_pers_kor_sum WHERE CODE <> 'НР' AND pachka = #TMP1.ngroup) end)*/
														 else 0 end),0),
										
														
			COL8 = SUM(ISNULL(PERS_CNT, 0)),
			COL9 = isnull(fname,''),
			COL10 = CONVERT(VARCHAR(10), date_doc, 104),
			COL11 = [TYPE],
			COL12 = CONVERT(VARCHAR(1),PER),
			COL13 = CONVERT(VARCHAR(4),[YEAR]),
			COL14 = isnull((SUM(isnull(b_bef_m1,0)) + SUM(isnull(b_bef_m2,0)) + SUM(isnull(b_bef_m3,0))),0.00),
			COL15 = SUM(ISNULL([INSUR],0)),
			COL16 = [LINK_DOC]
		FROM
			#TMP1
		GROUP BY [NGROUP],CODE,per_edt,year_edt, fname , date_doc	, [TYPE] , PER , [YEAR] , [LINK_DOC]	
		ORDER BY
			NGROUP

		drop table #TMP1
		drop table #TMP1_1

	END
	
		drop table #docs_kor_otm
		drop table #docs

END




GO


GRANT EXECUTE ON dbo.[RSA_RSV_1_PERS_UCH] TO PUBLIC

GO


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

GO

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




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

SET NOCOUNT ON

CREATE TABLE #DOC(LINK INT)


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


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

CREATE TABLE #PROV_DOC (	
GP_LINK INT ,
GP_GUID UNIQUEIDENTIFIER,
GP_NUMBER VARCHAR (25),
GP_DATE DATETIME,
GP_OBJ INT,
GP_OBJ_CODE CHAR(30), 
GP_OBJ_NAME VARCHAR(254),
GP_DATE_PROV DATETIME,
GP_SUMMA NUMERIC(19,2),
GP_COMMENT VARCHAR(254),
GP_GET_STORE TINYINT,
GP_DEP INT,
GP_ACC INT,
GP_ACC_CODE VARCHAR(20),
GP_ACC_TYPE TINYINT, 

GP1_LINK INT,
GP1_LINK_UP INT,
GP1_OPER INT,
GP1_NAME_OPER VARCHAR(250),
GP1_ORDERS INT,

GP2_LINK INT,
GP2_LINK_UP INT,
GP2_SUMMA NUMERIC (19,2) ,
GP2_QUANTITY NUMERIC (19,4) ,
GP2_STORNO TINYINT,
GP2_LINK_SELF INT,
GP2_NAME VARCHAR(254),
GP2_ORDERS SMALLINT,
GP2_EC_OPER INT,
GP2_EC_OPER_CODE CHAR(5),
GP2_EC_OPER_NAME VARCHAR(254),


GPAP_D_LINK_UP INT,
GPAP_D_DB_KR TINYINT,
GPAP_D_ACC INT,
GPAP_D_KBK INT,
GPAP_D_EKR INT,
GPAP_D_DEP INT,
GPAP_D_SUB INT,
GPAP_D_EMP INT,
GPAP_D_NOMEN INT,
GPAP_D_INV INT,
GPAP_D_KAU INT,
GPAP_D_DEP_ACC INT,
GPAP_D_TMC INT,
GPAP_D_INDATE DATETIME,
GPAP_D_SGU INT,
GPAP_D_AP1 INT,
GPAP_D_AP2 INT,
GPAP_D_AP3 INT,


GPAP_K_LINK_UP INT,
GPAP_K_DB_KR INT,
GPAP_K_ACC INT,
GPAP_K_KBK INT,
GPAP_K_EKR INT,
GPAP_K_DEP INT, 
GPAP_K_SUB INT,
GPAP_K_EMP INT,
GPAP_K_NOMEN INT,
GPAP_K_INV INT,
GPAP_K_KAU INT,
GPAP_K_DEP_ACC INT,
GPAP_K_TMC INT,
GPAP_K_INDATE DATETIME,
GPAP_K_SGU INT,
GPAP_K_AP1 INT,
GPAP_K_AP2 INT,
GPAP_K_AP3 INT)





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


CREATE TABLE #G_PROV_AP_FULL	( GP_LINK INT,
	GPAP_D_LINK_UP INT,
	GPAP_D_DB_KR TINYINT,
	GPAP_D_ACC INT,
	GPAP_D_name VARCHAR(150),
	GPAP_D_CODE VARCHAR(13),
	GPAP_D_cSource VARCHAR(1),
	GPAP_D_cSinth VARCHAR(3),
	GPAP_D_cAnalit VARCHAR(2),
	
	GPAP_D_KBK INT,
	GPAP_D_KBK_type TINYINT,GPAP_D_KBK_code CHAR(30),GPAP_D_KBK_NAME VARCHAR(250),
	
	GPAP_D_EKR INT,
	GPAP_D_EKR_code CHAR(3),	GPAP_D_EKR_NAME VARCHAR(250), GPAP_D_EKR_ls_ekr TINYINT,

	GPAP_D_DEP INT,
	GPAP_D_DEP_CODE VARCHAR(10),
	GPAP_D_DEP_NAME varchar(256),
	GPAP_D_DEP_FNAME varchar(256),
	GPAP_D_DEP_INN VARCHAR(12),
	GPAP_D_DEP_KPP VARCHAR(9),
	
	GPAP_D_SUB INT,
	GPAP_D_SUB_code VARCHAR(5), 
	GPAP_D_SUB_NAME VARCHAR(254), 
	GPAP_D_SUB_lim int , 
	GPAP_D_SUB_obosob TINYINT, 
	GPAP_D_SUB_okato VARCHAR(14), 
	GPAP_D_SUB_okpp VARCHAR(9), 
	GPAP_D_SUB_oktmo  VARCHAR(11),
	
	GPAP_D_EMP INT,
	GPAP_D_EMP_tab VARCHAR(10), 
	GPAP_D_EMP_fm VARCHAR(100), 
	GPAP_D_EMP_im VARCHAR(100), 
	GPAP_D_EMP_ot VARCHAR(100), 
	GPAP_D_EMP_FIO VARCHAR(105), 
	GPAP_D_EMP_INSUR_NUM VARCHAR(14), 
	GPAP_D_EMP_INN VARCHAR(12), 
	GPAP_D_EMP_date_begin datetime, 
	GPAP_D_EMP_date_end DATETIME, 
	
	GPAP_D_NOMEN INT,
	GPAP_D_NOMEN_CODE VARCHAR(20),GPAP_D_NOMEN_NAME VARCHAR(254),
	
	GPAP_D_INV INT,
	GPAP_D_INV_code VARCHAR(20),	GPAP_D_INV_NAME VARCHAR(254),
	
	GPAP_D_KAU INT,
	GPAP_D_KAU_code VARCHAR(20), GPAP_D_KAU_name VARCHAR(100), GPAP_D_KAU_thema VARCHAR(50),
	
	GPAP_D_DEP_ACC INT,
	GPAP_D_DEP_ACC_code VARCHAR(20), GPAP_D_DEP_ACC_TYPE TINYINT,
	
	GPAP_D_TMC INT,
	GPAP_D_TMC_NAME VARCHAR(254),GPAP_D_TMC_code VARCHAR(20) ,
	
	GPAP_D_INDATE DATETIME,
	GPAP_D_SGU INT,
	GPAP_D_SGU_code CHAR(3) , GPAP_D_SGU_NAME VARCHAR(250), GPAP_D_SGU_ls_ekr tinyint , 
	
	GPAP_D_AP1 INT,
	GPAP_D_AP1_TYPE_LINK int , GPAP_D_AP1_doc_link  INT , GPAP_D_AP1_NUMBER VARCHAR (25), GPAP_D_AP1_DATE DATETIME, GPAP_D_AP1_CODE CHAR(30), GPAP_D_AP1_NAME VARCHAR(254),
					GPAP_D_AP1_DATE_PROV DATETIME, GPAP_D_AP1_SUMMA NUMERIC(19,2),
	
	GPAP_D_AP2 INT,
	GPAP_D_AP2_code VARCHAR(20), GPAP_D_AP2_NAME VARCHAR(150),
	GPAP_D_AP3 INT,


	GPAP_K_LINK_UP INT,
	GPAP_K_DB_KR TINYINT,
	GPAP_K_ACC INT,
	GPAP_K_name VARCHAR(150),
	GPAP_K_CODE VARCHAR(13),
	GPAP_K_cSource VARCHAR(1),
	GPAP_K_cSinth VARCHAR(3),
	GPAP_K_cAnalit VARCHAR(2),
	
	GPAP_K_KBK INT,
	GPAP_K_KBK_type TINYINT,GPAP_K_KBK_code CHAR(30),GPAP_K_KBK_NAME VARCHAR(250),
	
	GPAP_K_EKR INT,
	GPAP_K_EKR_code CHAR(3),	GPAP_K_EKR_NAME VARCHAR(250), GPAP_K_EKR_ls_ekr TINYINT,

	GPAP_K_DEP INT,
	GPAP_K_DEP_CODE VARCHAR(10),
	GPAP_K_DEP_NAME varchar(256),
	GPAP_K_DEP_FNAME varchar(256),
	GPAP_K_DEP_INN VARCHAR(12),
	GPAP_K_DEP_KPP VARCHAR(9),
	
	GPAP_K_SUB INT,
	GPAP_K_SUB_code VARCHAR(5), 
	GPAP_K_SUB_NAME VARCHAR(254), 
	GPAP_K_SUB_lim int , 
	GPAP_K_SUB_obosob TINYINT, 
	GPAP_K_SUB_okato VARCHAR(14), 
	GPAP_K_SUB_okpp VARCHAR(9), 
	GPAP_K_SUB_oktmo  VARCHAR(11),
	
	GPAP_K_EMP INT,
	GPAP_K_EMP_tab VARCHAR(10), 
	GPAP_K_EMP_fm VARCHAR(100), 
	GPAP_K_EMP_im VARCHAR(100), 
	GPAP_K_EMP_ot VARCHAR(100), 
	GPAP_K_EMP_FIO VARCHAR(105), 
	GPAP_K_EMP_INSUR_NUM VARCHAR(14), 
	GPAP_K_EMP_INN VARCHAR(12), 
	GPAP_K_EMP_date_begin datetime, 
	GPAP_K_EMP_date_end DATETIME, 
	
	GPAP_K_NOMEN INT,
	GPAP_K_NOMEN_CODE VARCHAR(20),GPAP_K_NOMEN_NAME VARCHAR(254),
	
	GPAP_K_INV INT,
	GPAP_K_INV_code VARCHAR(20),	GPAP_K_INV_NAME VARCHAR(254),
	
	GPAP_K_KAU INT,
	GPAP_K_KAU_code VARCHAR(20), GPAP_K_KAU_name VARCHAR(100), GPAP_K_KAU_thema VARCHAR(50),
	
	GPAP_K_DEP_ACC INT,
	GPAP_K_DEP_ACC_code VARCHAR(20), GPAP_K_DEP_ACC_TYPE TINYINT,
	
	GPAP_K_TMC INT,
	GPAP_K_TMC_NAME VARCHAR(254), GPAP_K_TMC_code VARCHAR(20) ,
	
	GPAP_K_INDATE DATETIME,
	GPAP_K_SGU INT,
	GPAP_K_SGU_code CHAR(3) , GPAP_K_SGU_NAME VARCHAR(250), GPAP_K_SGU_ls_ekr tinyint , 
	
	GPAP_K_AP1 INT,
	GPAP_K_AP1_TYPE_LINK int , GPAP_K_AP1_doc_link int  , GPAP_K_AP1_NUMBER VARCHAR (25), GPAP_K_AP1_DATE DATETIME, GPAP_K_AP1_CODE CHAR(30), GPAP_K_AP1_NAME VARCHAR(254),
	GPAP_K_AP1_DATE_PROV DATETIME, GPAP_K_AP1_SUMMA NUMERIC(19,2),
	
	GPAP_K_AP2 INT,
	GPAP_K_AP2_code VARCHAR(20), GPAP_K_AP2_NAME VARCHAR(150),
	GPAP_K_AP3 INT) 
	
INSERT into #PROV_DOC ( GP_LINK,GP_GUID,GP_NUMBER,GP_DATE,GP_OBJ,
								GP_OBJ_CODE,GP_OBJ_NAME,
						GP_DATE_PROV,GP_SUMMA,
						GP_COMMENT,GP_GET_STORE,GP_DEP,GP_ACC,
						GP_ACC_CODE, GP_ACC_TYPE,
						GP1_LINK,GP1_LINK_UP,GP1_OPER,GP1_NAME_OPER,GP1_ORDERS,
						GP2_LINK,GP2_LINK_UP,GP2_SUMMA,GP2_QUANTITY,GP2_STORNO,GP2_LINK_SELF,GP2_NAME,GP2_ORDERS,GP2_EC_OPER,
								GP2_EC_OPER_CODE,GP2_EC_OPER_NAME,
						GPAP_D_LINK_UP,GPAP_D_DB_KR,GPAP_D_ACC,GPAP_D_KBK,GPAP_D_EKR,GPAP_D_DEP,GPAP_D_SUB,GPAP_D_EMP,GPAP_D_NOMEN,
						GPAP_D_INV,GPAP_D_KAU,GPAP_D_DEP_ACC, GPAP_D_TMC,GPAP_D_INDATE,GPAP_D_SGU,GPAP_D_AP1,GPAP_D_AP2,GPAP_D_AP3,
						GPAP_K_LINK_UP,GPAP_K_DB_KR,GPAP_K_ACC,GPAP_K_KBK,GPAP_K_EKR,GPAP_K_DEP,GPAP_K_SUB,GPAP_K_EMP,GPAP_K_NOMEN,
						GPAP_K_INV,GPAP_K_KAU,GPAP_K_DEP_ACC,GPAP_K_TMC,GPAP_K_INDATE,GPAP_K_SGU,GPAP_K_AP1,GPAP_K_AP2,GPAP_K_AP3)

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

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


INSERT INTO #G_PROV_AP_FULL	(  GP_LINK,
	GPAP_D_LINK_UP,
	GPAP_D_DB_KR,
	GPAP_D_ACC,
	GPAP_D_name,
	GPAP_D_CODE,
	GPAP_D_cSource,
	GPAP_D_cSinth,
	GPAP_D_cAnalit,
	
	GPAP_D_KBK,
	GPAP_D_KBK_type,GPAP_D_KBK_code,GPAP_D_KBK_NAME,
	
	GPAP_D_EKR, 
	GPAP_D_EKR_code,GPAP_D_EKR_NAME, GPAP_D_EKR_ls_ekr,

	GPAP_D_DEP,
	GPAP_D_DEP_CODE,
	GPAP_D_DEP_NAME,
	GPAP_D_DEP_FNAME,
	GPAP_D_DEP_INN,
	GPAP_D_DEP_KPP,
	
	GPAP_D_SUB,
	GPAP_D_SUB_code, 
	GPAP_D_SUB_NAME, 
	GPAP_D_SUB_lim, 
	GPAP_D_SUB_obosob, 
	GPAP_D_SUB_okato, 
	GPAP_D_SUB_okpp, 
	GPAP_D_SUB_oktmo,
	
	GPAP_D_EMP,
	GPAP_D_EMP_tab, 
	GPAP_D_EMP_fm, 
	GPAP_D_EMP_im, 
	GPAP_D_EMP_ot, 
	GPAP_D_EMP_FIO, 
	GPAP_D_EMP_INSUR_NUM, 
	GPAP_D_EMP_INN, 
	GPAP_D_EMP_date_begin, 
	GPAP_D_EMP_date_end, 
	
	GPAP_D_NOMEN,
	GPAP_D_NOMEN_CODE,GPAP_D_NOMEN_NAME,
	
	GPAP_D_INV,
	GPAP_D_INV_code,	GPAP_D_INV_NAME,
	
	GPAP_D_KAU,
	GPAP_D_KAU_code, GPAP_D_KAU_name, GPAP_D_KAU_thema,
	
	GPAP_D_DEP_ACC,
	GPAP_D_DEP_ACC_code, GPAP_D_DEP_ACC_TYPE,
	
	GPAP_D_TMC,
	GPAP_D_TMC_NAME, GPAP_D_TMC_code,
	
	GPAP_D_INDATE,
	GPAP_D_SGU,
	GPAP_D_SGU_code, GPAP_D_SGU_NAME, GPAP_D_SGU_ls_ekr, 
	
	GPAP_D_AP1,
	GPAP_D_AP1_TYPE_LINK, GPAP_D_AP1_doc_link, GPAP_D_AP1_NUMBER, GPAP_D_AP1_DATE, GPAP_D_AP1_CODE, GPAP_D_AP1_NAME,
					GPAP_D_AP1_DATE_PROV, GPAP_D_AP1_SUMMA, 
	
	GPAP_D_AP2,
	GPAP_D_AP2_code, GPAP_D_AP2_NAME,
	GPAP_D_AP3,


	GPAP_K_LINK_UP,
	GPAP_K_DB_KR,
	GPAP_K_ACC,
	GPAP_K_name,
	GPAP_K_CODE,
	GPAP_K_cSource,
	GPAP_K_cSinth,
	GPAP_K_cAnalit,
	
	GPAP_K_KBK,
	GPAP_K_KBK_type,GPAP_K_KBK_code,GPAP_K_KBK_NAME,

	GPAP_K_EKR,
	GPAP_K_EKR_code,	GPAP_K_EKR_NAME, GPAP_K_EKR_ls_ekr,


	GPAP_K_DEP ,
	GPAP_K_DEP_CODE,
	GPAP_K_DEP_NAME,
	GPAP_K_DEP_FNAME,
	GPAP_K_DEP_INN,
	GPAP_K_DEP_KPP,


	GPAP_K_SUB,
	GPAP_K_SUB_code, 
	GPAP_K_SUB_NAME, 
	GPAP_K_SUB_lim, 
	GPAP_K_SUB_obosob, 
	GPAP_K_SUB_okato, 
	GPAP_K_SUB_okpp, 
	GPAP_K_SUB_oktmo,
	

	GPAP_K_EMP ,
	GPAP_K_EMP_tab, 
	GPAP_K_EMP_fm, 
	GPAP_K_EMP_im, 
	GPAP_K_EMP_ot, 
	GPAP_K_EMP_FIO, 
	GPAP_K_EMP_INSUR_NUM, 
	GPAP_K_EMP_INN, 
	GPAP_K_EMP_date_begin, 
	GPAP_K_EMP_date_end, 
	
	GPAP_K_NOMEN,
	GPAP_K_NOMEN_CODE,GPAP_K_NOMEN_NAME,
	
	GPAP_K_INV,
	GPAP_K_INV_code,GPAP_K_INV_NAME,
	
	GPAP_K_KAU,
	GPAP_K_KAU_code, GPAP_K_KAU_name, GPAP_K_KAU_thema,
	
	GPAP_K_DEP_ACC,
	GPAP_K_DEP_ACC_code, GPAP_K_DEP_ACC_TYPE,
	
	GPAP_K_TMC,
	GPAP_K_TMC_NAME, GPAP_K_TMC_code,
	
	GPAP_K_INDATE,
	GPAP_K_SGU,
	GPAP_K_SGU_code, GPAP_K_SGU_NAME, GPAP_K_SGU_ls_ekr, 
	
	GPAP_K_AP1,
	GPAP_K_AP1_TYPE_LINK, GPAP_K_AP1_doc_link, GPAP_K_AP1_NUMBER, GPAP_K_AP1_DATE, GPAP_K_AP1_CODE, GPAP_K_AP1_NAME,
	GPAP_K_AP1_DATE_PROV, GPAP_K_AP1_SUMMA,
	
	GPAP_K_AP2,
	GPAP_K_AP2_code, GPAP_K_AP2_NAME,
	GPAP_K_AP3)

SELECT G.GP_LINK,
	   G.GPAP_D_LINK_UP,
	   G.GPAP_D_DB_KR,
	   /*GPAP_D_ACCOUNT*/
	   G.GPAP_D_ACC, GPAP_D_name = s.NAME, GPAP_D_CODE = s.CODE, GPAP_D_cSource = s.cSource, GPAP_D_cSinth = s.cSinth, GPAP_D_cAnalit = s.cAnalit,
	   /*GPAP_D_KBK*/
	   G.GPAP_D_KBK, GPAP_D_KBK_type = K.[TYPE], GPAP_D_KBK_code = K.CODE,GPAP_D_KBK_NAME = k.NAME,
	   /*GPAP_D_EKR*/
	   G.GPAP_D_EKR, GP_AP_D_EKR_code = ko.CODE, GP_AP_D_EKR_NAME = ko.NAME, GP_AP_D_EKR_ls_ekr = ko.Is_Ekr,
	   /*GPAP_D_DEP*/
	   G.GPAP_D_DEP, GPAP_D_DEP_CODE = d.CODE, GPAP_D_DEP_NAME = d.NAME, GPAP_D_DEP_FNAME = d.FULL_NAME, GPAP_D_DEP_INN = d.INN, GPAP_D_DEP_KPP = d.KPP,
	   /*GPAP_D_SUB*/
	   G.GPAP_D_SUB, GPAP_D_SUB_code = su.CODE, GPAP_D_SUB_NAME = su.NAME, GPAP_D_SUB_lim = su.LIM, GPAP_D_SUB_obosob = su.OBOSOB, GPAP_D_SUB_okato = su.O_OKATO, GPAP_D_SUB_okpp = su.O_KPP, GPAP_D_SUB_oktmo = su.O_OKTMO,
	   /*GPAP_D_EMP*/
	   G.GPAP_D_EMP,  GPAP_D_EMP_tab = sd.TAB, GPAP_D_EMP_fm = sd.FM, GPAP_D_EMP_im = sd.IM, GPAP_D_EMP_ot = sd.OT, GPAP_D_EMP_FIO = sd.FIO, GPAP_D_EMP_INSUR_NUM = sd.INSUR_NUM, GPAP_D_EMP_INN = sd.INN, GPAP_D_EMP_date_begin = sd.DATE_BEGIN, GPAP_D_EMP_date_end = sd.DATE_END, 
	   /*GPAP_D_NOMEN*/
	   G.GPAP_D_NOMEN, GPAP_D_NOMEN_CODE = n.CODE, GPAP_D_NOMEN_NAME = n.NAME,
	   /*GPAP_D_INV*/
	   G.GPAP_D_INV, GPAP_D_INV_code = i.CODE, GPAP_D_INV_NAME = i.NAME,
	   /*GPAP_D_KAU*/
	   G.GPAP_D_KAU, GPAP_D_KAU_code = ka.CODE, GPAP_D_KAU_name = ka.NAME, GPAP_D_KAU_thema = KA.THEMA,
	   /*GPAP_D_DEP_ACC*/
	   G.GPAP_D_DEP_ACC, GPAP_D_DEP_ACC_code = da.CODE, GPAP_D_DEP_ACC_TYPE = da.[TYPE], 
	   /*GPAP_D_TMC*/
	   G.GPAP_D_TMC, GPAP_D_TMC_NAME = di.NAME, GPAP_D_TMC_code = di.CODE,
	   G.GPAP_D_INDATE, 
	   /*GPAP_D_SGU*/
	   G.GPAP_D_SGU, GPAP_D_SGU_code = KOO.CODE, GPAP_D_SGU_NAME = KOO.NAME, GPAP_D_SGU_ls_ekr = KOO.Is_Ekr, 
	   /*GPAP_D_AP1*/
	   G.GPAP_D_AP1, O.OSNOV_AP1_D_TYPE_LINK, O.OSNOV_AP1_D_doc_link, O.G_PROV_AP1_D_NUMBER, O.G_PROV_AP1_D_DATE, O.S_OBJECTS_AP1_D_CODE, O.S_OBJECTS_AP1_D_NAME,
							O.G_PROV_AP1_D_DATE_PROV, O.G_PROV_AP1_D_SUMMA,
	   /*GPAP_D_AP2*/
	   G.GPAP_D_AP2, GPAP_D_AP2_code = do.CODE, GPAP_D_AP2_NAME = do.NAME,
	   G.GPAP_D_AP3,
	
	   G.GPAP_K_LINK_UP,
	   G.GPAP_K_DB_KR,
	   /*GPAP_K_ACC*/
	   G.GPAP_K_ACC, GPAP_K_name = s1.NAME, GPAP_K_CODE = s1.CODE, GPAP_K_cSource = s1.cSource, GPAP_K_cSinth = s1.cSinth, GPAP_K_cAnalit = s1.cAnalit,
	   /*GPAP_K_KBK*/
	   G.GPAP_K_KBK, GPAP_K_KBK_type = K1.[TYPE], GPAP_K_KBK_code = K1.CODE,GPAP_K_KBK_NAME = k1.NAME,
	   /*GPAP_K_EKR*/
	   G.GPAP_K_EKR, GPAP_K_EKR_code = ko1.CODE, GPAP_K_EKR_NAME = ko1.NAME, GPAP_K_EKR_ls_ekr = ko1.Is_Ekr,
	   /*GPAP_K_DEP*/
	   G.GPAP_K_DEP, GPAP_K_DEP_CODE = d1.CODE, GPAP_K_DEP_NAME = d1.NAME, GPAP_K_DEP_FNAME = d1.FULL_NAME, GPAP_K_DEP_INN = d1.INN, GPAP_K_DEP_KPP = d1.KPP,
	   /*GPAP_K_SUB*/
	   G.GPAP_K_SUB, GPAP_K_SUB_code = su1.CODE, GPAP_K_SUB_NAME = su1.NAME, GPAP_K_SUB_lim = su1.LIM, GPAP_K_SUB_obosob = su1.OBOSOB, GPAP_K_SUB_okato = su1.O_OKATO, GPAP_K_SUB_okpp = su1.O_KPP, GPAP_K_SUB_oktmo = su1.O_OKTMO,
	   /*GPAP_K_EMP*/
	   G.GPAP_K_EMP,  GPAP_K_EMP_tab = sd1.TAB, GPAP_K_EMP_fm = sd1.FM, GPAP_K_EMP_im = sd1.IM, GPAP_K_EMP_ot = sd1.OT, GPAP_K_EMP_FIO = sd1.FIO, GPAP_K_EMP_INSUR_NUM = sd1.INSUR_NUM, GPAP_K_EMP_INN = sd1.INN, GPAP_K_EMP_date_begin = sd1.DATE_BEGIN, GPAP_K_EMP_date_end = sd1.DATE_END, 
	   /*GPAP_K_NOMEN*/
	   G.GPAP_K_NOMEN, GPAP_K_NOMEN_CODE = n1.CODE, GPAP_K_NOMEN_NAME = n1.NAME,
	   /*GPAP_K_INV*/
	   G.GPAP_K_INV, GPAP_K_INV_code = i1.CODE, GPAP_K_INV_NAME = i1.NAME,
	   /*GPAP_K_KAU*/
	   G.GPAP_K_KAU, GPAP_K_KAU_code = ka1.CODE, GPAP_K_KAU_name = ka1.NAME, GPAP_K_KAU_thema = KA1.THEMA,
	   /*GPAP_K_DEP_ACC*/
	   G.GPAP_K_DEP_ACC, GPAP_K_DEP_ACC_code = da1.CODE, GPAP_K_DEP_ACC_TYPE = da1.[TYPE], 
	   /*GPAP_K_TMC*/
	   G.GPAP_K_TMC, GPAP_K_TMC_NAME = di1.NAME, GPAP_K_TMC_code = di1.CODE,
	   G.GPAP_K_INDATE, 
	   /*GPAP_K_SGU*/
	   G.GPAP_K_SGU, GPAP_K_SGU_code = KOO1.CODE, GPAP_K_SGU_NAME = KOO1.NAME, GPAP_K_SGU_ls_ekr = KOO1.Is_Ekr, 
	   /*GPAP_K_AP1*/
	   G.GPAP_K_AP1, O1.OSNOV_AP1_K_TYPE_LINK, O1.OSNOV_AP1_K_doc_link, O1.G_PROV_AP1_K_NUMBER, O1.G_PROV_AP1_K_DATE, O1.S_OBJECTS_AP1_K_CODE, O1.S_OBJECTS_AP1_K_NAME,
							O1.G_PROV_AP1_K_DATE_PROV, O1.G_PROV_AP1_K_SUMMA , 
	   G.GPAP_K_AP2, GPAP_K_AP2_code = do1.CODE, GPAP_K_AP2_NAME = do1.NAME,
	   G.GPAP_K_AP3
FROM
	#PROV_DOC G
	LEFT JOIN dbo.S_ACCOUNTS		  S ON S.LINK = G.GPAP_D_ACC
	LEFT JOIN dbo.KL_KBK			  K ON  k.link = G.GPAP_D_KBK
	LEFT JOIN dbo.KOSGU				  KO ON KO.LINK = G.GPAP_D_EKR
	LEFT JOIN dbo.departments		  d ON d.link = G.GPAP_D_DEP
	LEFT JOIN dbo.SUBDIV			  su ON su.link =  G.GPAP_D_SUB
	LEFT JOIN dbo.SD_EMPL			  sd ON sd.link =  G.GPAP_D_EMP
	LEFT JOIN dbo.NOMENCLATURE		  N ON n.LINK = G.GPAP_D_NOMEN
	LEFT JOIN dbo.INVENTORY			  I ON   I.link =  G.GPAP_D_INV
	LEFT JOIN dbo.KAU				  KA ON ka.link = G.GPAP_D_KAU
	LEFT JOIN dbo.DEPARTMENT_ACCOUNTS da ON da.link = G.GPAP_D_DEP_ACC
	LEFT JOIN dbo.DICTION			  di ON di.link = G.GPAP_D_TMC
	LEFT JOIN dbo.KOSGU				  KOO ON  KOO.LINK = G.GPAP_D_SGU	
	LEFT JOIN (SELECT oo.link,
					  OSNOV_AP1_D_TYPE_LINK = oo.TYPE_LINK ,
					  OSNOV_AP1_D_doc_link = oo.DOC_LINK,
					  G_PROV_AP1_D_NUMBER = GP.NUMBER ,
					  G_PROV_AP1_D_DATE = GP.[DATE],
					  S_OBJECTS_AP1_D_CODE = s.CODE,
					  S_OBJECTS_AP1_D_NAME = S.NAME,
					  G_PROV_AP1_D_DATE_PROV = GP.DATE_PROV,
					  G_PROV_AP1_D_SUMMA = GP.SUMMA,
					  G_PROV_AP1_D_COMMENT = GP.COMMENT,
					  G_PROV_AP1_D_GET_STORE = GP.GET_STORE,
					  department_accounts_AP1_D_CODE = d_ACc.CODE
			   from dbo.OSNOV oo 
			   LEFT JOIN dbo.G_PROV GP ON GP.LINK = oo.DOC_LINK
			   LEFT JOIN dbo.S_OBJECTS S ON s.link = GP.[OBJECT]	
			   LEFT JOIN department_accounts d_ACc ON d_acc.LINK = GP.ACC  )o ON o.LINK = G.GPAP_D_AP1
	LEFT JOIN dbo.DOP_CLASSIF		  do ON do.LINK = G.GPAP_D_AP1
	
	LEFT JOIN dbo.S_ACCOUNTS		  S1 ON S1.LINK = G.GPAP_K_ACC
	LEFT JOIN dbo.KL_KBK			  K1 ON  k1.link = G.GPAP_K_KBK
	LEFT JOIN dbo.KOSGU				  KO1 ON KO1.LINK = G.GPAP_K_EKR
	LEFT JOIN dbo.departments		  d1 ON d1.link = G.GPAP_K_DEP
	LEFT JOIN dbo.SUBDIV			  su1 ON su1.link =  G.GPAP_K_SUB
	LEFT JOIN dbo.SD_EMPL			  sd1 ON sd1.link =  G.GPAP_K_EMP
	LEFT JOIN dbo.NOMENCLATURE		  N1 ON n1.LINK = G.GPAP_K_NOMEN
	LEFT JOIN dbo.INVENTORY			  I1 ON   I1.link =  G.GPAP_K_INV
	LEFT JOIN dbo.KAU				  KA1 ON ka1.link = G.GPAP_K_KAU
	LEFT JOIN dbo.DEPARTMENT_ACCOUNTS da1 ON da1.link = G.GPAP_K_DEP_ACC
	LEFT JOIN dbo.DICTION			  di1 ON di1.link = G.GPAP_K_TMC
	LEFT JOIN dbo.KOSGU				  KOO1 ON  KOO1.LINK = G.GPAP_K_SGU	
	LEFT JOIN (SELECT oo.link,
					  OSNOV_AP1_K_TYPE_LINK = oo.TYPE_LINK ,
					  OSNOV_AP1_K_doc_link = oo.DOC_LINK,
					  G_PROV_AP1_K_NUMBER = GP.NUMBER ,
					  G_PROV_AP1_K_DATE = GP.[DATE],
					  S_OBJECTS_AP1_K_CODE = s.CODE,
					  S_OBJECTS_AP1_K_NAME = S.NAME,
					  G_PROV_AP1_K_DATE_PROV = GP.DATE_PROV,
					  G_PROV_AP1_K_SUMMA = GP.SUMMA,
					  G_PROV_AP1_K_COMMENT = GP.COMMENT,
					  G_PROV_AP1_K_GET_STORE = GP.GET_STORE,
					  department_accounts_AP1_K_CODE = d_ACc.CODE
			   from dbo.OSNOV oo 
			   LEFT JOIN dbo.G_PROV GP ON GP.LINK = oo.DOC_LINK
			   LEFT JOIN dbo.S_OBJECTS S ON s.link = GP.[OBJECT]	
			   LEFT JOIN department_accounts d_ACc ON d_acc.LINK = GP.ACC  )  o1 ON o1.LINK = G.GPAP_K_AP1
	LEFT JOIN dbo.DOP_CLASSIF		  do1 ON do1.LINK = G.GPAP_K_AP1

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

INSERT INTO #TASK_PROP (VAL) 	
	SELECT   TOP 1  LTRIM(RTRIM(OV.Value)) 
	FROM object_values OV
	WITH (NOLOCK)
	WHERE Object = (SELECT link FROM s_objects WHERE code = 'PROJECT') AND property =  (SELECT link	FROM S_PROPERTY WHERE CODE ='VERSION_MAJOR')
INSERT INTO #TASK_PROP (VAL) 
	SELECT   TOP 1  LTRIM(RTRIM(OV.Value)) 
	FROM object_values OV
	WITH (NOLOCK)
	WHERE Object = (SELECT link FROM s_objects WHERE code = 'PROJECT') AND property =  (SELECT link	FROM S_PROPERTY WHERE CODE ='VERSION_MINOR')
INSERT INTO #TASK_PROP (VAL) 
	SELECT   TOP 1  LTRIM(RTRIM(OV.Value)) 
	FROM object_values OV
	WITH (NOLOCK)
	WHERE Object = (SELECT link FROM s_objects WHERE code = 'PROJECT') AND property =  (SELECT link	FROM S_PROPERTY WHERE CODE ='VERSION_FIX')

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

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

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

-- ШАПОЧНАЯ ЧАСТЬ ФАЙЛА
-----

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

WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN	
		
	SET @lcFNAME = (SELECT 'ZARPLATA_KS-PROV-C-'+LTRIM(RTRIM(DEP_CODE))+'-INN-'+(CASE when LTRIM(RTRIM(INN)) ='' THEN '000000000000' ELSE LTRIM(RTRIM(INN)) END )+'-KPP-'+(CASE when LTRIM(RTRIM(KPP)) ='' THEN '000000000' ELSE LTRIM(RTRIM(KPP)) END )+'.XML' FROM #DEP_INFO di WHERE DEP_LINK = @DEP_LINK  )


	INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
	SELECT @lcFNAME, 'OEM' --Имя файла 
		UNION ALL SELECT @lcFNAME, SPACE(0) + '<?xml version="1.0" encoding="Windows-1251" ?>' 
		UNION ALL SELECT @lcFNAME, SPACE(0) + '<Exchange version ="1.0">' 
		--UNION ALL SELECT @lcFNAME, SPACE(0) + '<File>' 
 		UNION ALL SELECT @lcFNAME, SPACE(1) + '<FileName>' + RTRIM(LTRIM(@lcFNAME)) + '</FileName>'
		 
	
		
		
		INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)			 
		 SELECT @lcFNAME, SPACE(1) + '<Org>'
		 UNION ALL SELECT @lcFNAME, SPACE(2) + '<INN>'+RTRIM(LTRIM(COALESCE(INN,'')))+'</INN>'
		 FROM #DEP_INFO WHERE dep_link = @DEP_LINK	
		 UNION ALL SELECT @lcFNAME, SPACE(2) + '<KPP>'+RTRIM(LTRIM(COALESCE(KPP,'')))+'</KPP>'
		 FROM #DEP_INFO WHERE dep_link = @DEP_LINK	
		 UNION ALL SELECT @lcFNAME, SPACE(2) + '<CODE>'+RTRIM(LTRIM(COALESCE(DEP_CODE,'')))+'</CODE>'
		 FROM #DEP_INFO WHERE dep_link = @DEP_LINK	
		 UNION ALL SELECT @lcFNAME, SPACE(2) + '<Name>'+RTRIM(LTRIM(COALESCE(DEP_FNAME,'')))+'</Name>'
		 FROM #DEP_INFO WHERE dep_link = @DEP_LINK	
	
	--
	-- ПЕРЕЧИСЛЕНИЕ ПРОВОДОК
	---
		
		SET @N_STR = 0 
		SET @Cur2 = CURSOR FORWARD_ONLY
		FOR select GP_LINK from #PROV_DOC WHERE GP_DEP = @DEP_LINK GROUP BY GP_LINK 
		
		OPEN @Cur2
		FETCH NEXT FROM @Cur2 INTO @GPROV_LINK

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


				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
					SELECT @lcFNAME,					
					/*таблица G_PROV*/
					+ SPACE(3) + '<G_PROV>' + CHAR(10)
					 + SPACE(4) + '<GUID>'+ ltrim(rtrim(P.GP_GUID)) +'</GUID>' + CHAR(10)
					 + SPACE(4) + '<NUMBER>'+ ltrim(rtrim(P.GP_NUMBER)) +'</NUMBER>' + CHAR(10)
					 + SPACE(4) + '<DATE>'+ convert(varchar(10),P.GP_DATE,104) +'</DATE>' + CHAR(10)
					 /*поле OBJECT - линк таблицы S_OBJECTS */
					 + SPACE(4) + '<OBJ_CODE>' + ltrim(rtrim(P.GP_OBJ_CODE)) + '</OBJ_CODE>' + CHAR(10) 
					 + SPACE(4) + '<DATE_PROV>'+ convert(varchar(10),P.GP_DATE_PROV,104) +'</DATE_PROV>' + CHAR(10)
					 + SPACE(4) + '<SUMMA>'+ RTRIM(LTRIM(STR(COALESCE(P.GP_SUMMA,0),18,2))) +'</SUMMA>' + CHAR(10)
					 + SPACE(4) + '<COMMENT>'+ RTRIM(LTRIM(COALESCE(P.GP_COMMENT,''))) +'</COMMENT>' + CHAR(10)
					 + SPACE(4) +  (case when RTRIM(LTRIM(STR(COALESCE(P.GP_GET_STORE,0)))) = 0 then ('<GET_STORE/>' + CHAR(10)) else  ('<GET_STORE>'+   RTRIM(LTRIM(STR(COALESCE(P.GP_GET_STORE,0)))) +'</GET_STORE>' + CHAR(10) ) END)
					 /*Поле DEP - линк таблицы #DEP_INFO*/
					 + SPACE(4) + '<DEP_CODE>' + (select RTRIM(LTRIM(COALESCE(DEP_CODE,''))) FROM #DEP_INFO WHERE DEP_LINK = P.GP_DEP ) + '</DEP_CODE>' + CHAR(10)
					 + SPACE(4) + '<DEP_INN>' + (select RTRIM(LTRIM(COALESCE(INN,''))) FROM #DEP_INFO WHERE DEP_LINK = P.GP_DEP ) + '</DEP_INN>' + CHAR(10)
					 + SPACE(4) + '<DEP_KPP>' + (select RTRIM(LTRIM(COALESCE(KPP,''))) FROM #DEP_INFO WHERE DEP_LINK = P.GP_DEP ) + '</DEP_KPP>' + CHAR(10)
					 /*поле ACC - линк таблицы department_accounts*/
					 + SPACE(4) + '<ACC_CODE>' + ltrim(rtrim(iSnULL(P.GP_ACC_CODE,''))) + '</ACC_CODE>' 
					FROM
						#PROV_DOC P
						--INNER JOIN #G_PROV_AP_FULL GP ON GP.GP_LINK = P.GP_LINK 
					WHERE 
						P.GP_LINK = @GPROV_LINK
					GROUP BY  GP_LINK,GP_GUID, GP_DATE, GP_NUMBER,GP_OBJ_CODE, GP_DATE_PROV , GP_SUMMA , GP_COMMENT , GP_GET_STORE , GP_DEP ,GP_ACC_CODE
					 
					
					
					SET @Cur3 = CURSOR FORWARD_ONLY
					FOR select gp1_link from #PROV_DOC WHERE GP_LINK = @GPROV_LINK  GROUP BY gp1_link
					
					OPEN @Cur3
					FETCH NEXT FROM @Cur3 INTO @GP1_LINK

					WHILE (@@fetch_status <> -1)
					BEGIN
						 INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
								SELECT @lcFNAME,				
								/*Таблица G_PROV1*/
								+ SPACE(4) + '<G_PROV1>' + CHAR(10)						
												
						IF (@@fetch_status <> -2)
						BEGIN
							

						    INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
							SELECT @lcFNAME,				
							--/*Таблица G_PROV1*/
							--+ SPACE(4) + '<G_PROV1>' + CHAR(10)
							/*Поле OPER - линк таблицы G_PROV1*/
									+ SPACE(5) + (case when RTRIM(LTRIM(isnull(P.GP1_NAME_OPER,''))) = '' then ('<OPER/>' + CHAR(10)) else  ('<OPER>' +   RTRIM(LTRIM(isnull(P.GP1_NAME_OPER,''))) + '</OPER>' + CHAR(10) ) END)
									+ SPACE(5) + '<ORDERS>' + RTRIM(LTRIM(ISNULL(P.GP1_ORDERS, 0))) + '</ORDERS>'  + CHAR(10)
									FROM
										#PROV_DOC P
										INNER JOIN #G_PROV_AP_FULL GP ON GP.GP_LINK = P.GP_LINK
									WHERE 
										P.GP1_LINK = @GP1_LINK
									group by p.GP1_ORDERS	, P.GP1_NAME_OPER ,isnull(P.GP1_OPER,0)
								

									SET @Cur4 = CURSOR FORWARD_ONLY
									FOR select gp2_link from #PROV_DOC WHERE GP1_LINK = @GP1_LINK  GROUP BY gp1_link, gp2_link
									
									OPEN @Cur4
									FETCH NEXT FROM @Cur4 INTO @GP2_LINK

									WHILE (@@fetch_status <> -1)
									BEGIN
											INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
											SELECT @lcFNAME,	
									
									
											/*Таблица G_PROV2*/
											+ SPACE(5) + '<G_PROV2>' + CHAR(10)
			
											IF (@@fetch_status <> -2)
											BEGIN
												INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
												SELECT @lcFNAME,	
									
									
															/*Таблица G_PROV2*/
															---+ SPACE(5) + '<G_PROV2>' + CHAR(10)
																	+ SPACE(6) + '<SUMMA>' + RTRIM(LTRIM(STR(COALESCE(P.[GP2_SUMMA],0),18,2))) + '</SUMMA>'  + CHAR(10)
																	+ SPACE(6) + (case when RTRIM(LTRIM(STR(COALESCE(P.[GP2_QUANTITY],0),18,4))) = '0.0000' then ('<QUANTITY/>' + CHAR(10)) else  ('<QUANTITY>'+   RTRIM(LTRIM(STR(COALESCE(P.[GP2_QUANTITY],0),18,4))) +'</QUANTITY>' + CHAR(10) ) END)
																	+ SPACE(6) + (case when RTRIM(LTRIM(STR(COALESCE(P.GP2_STORNO,'')))) = 0 then ('<STORNO/>' + CHAR(10)) else  ('<STORNO>'+   RTRIM(LTRIM(STR(COALESCE(P.GP2_STORNO,'')))) +'</STORNO>' + CHAR(10) ) END)
															/* ПОЛЕ LINK_SELF - link таблицы G_PROV2*/
																	+ SPACE(6) + '<ORDERS>' + RTRIM(LTRIM(STR(COALESCE(P.GP2_ORDERS,''))))+ '</ORDERS>'  + CHAR(10)
																/*поле ECON_OPER - линк таблицы XOZ_OPER*/
																	+ SPACE(6) + '<EC_OPER_CODE>' + RTRIM(LTRIM(ISNULL(P.GP2_EC_OPER_CODE, ''))) + '</EC_OPER_CODE>'  + CHAR(10)
																	FROM
																		#PROV_DOC P
																		INNER JOIN #G_PROV_AP_FULL GP ON GP.GP_LINK = P.GP_LINK AND GP.GPAP_D_LINK_UP = P.GP2_LINK
																	WHERE 
																		GP.GPAP_D_LINK_UP = @GP2_LINK
																	GROUP BY 	P.GP2_LINK , P.[GP2_SUMMA], P.[GP2_QUANTITY], P.GP2_STORNO, P.GP2_ORDERS , P.GP2_EC_OPER_CODE
																	
																	
																	/*Дебет , кредит*/
																	SET @Cur5 = CURSOR FORWARD_ONLY
																	FOR select GPAP_D_LINK_UP from #G_PROV_AP_FULL where GP_LINK = @GPROV_LINK AND GPAP_D_LINK_UP = @GP2_LINK

																	OPEN @Cur5
																	FETCH NEXT FROM @Cur5 INTO @d_LINK

																	WHILE (@@fetch_status <> -1)
																	BEGIN
																												
																			IF (@@fetch_status <> -2)
																			BEGIN
																				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
																				SELECT @lcFNAME,	

																				/*Дебет*/
																				
				 																+ SPACE(7) + (case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_DB_KR,'')))) = 0 then ('<D_DB_KR/>' + CHAR(10)) else  ('<D_DB_KR>'+   RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_DB_KR,'')))) +'/<D_DB_KR>'+ CHAR(10) ) END)
																				/*поле ACCOUNT - линк таблицы s_accounts*/
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_D_CODE, ''))) = '' then ('<D_ACC/>' + CHAR(10)) else  ('<D_ACC>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_CODE, ''))) +'</D_ACC>'+ CHAR(10) ) END)
																				/*поле KBK - линк таблицы KL_KBK*/
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_D_KBK_code, ''))) = '' then ('<D_KBK/>' + CHAR(10)) else  ('<D_KBK>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_KBK_code, ''))) +'</D_KBK>'+ CHAR(10) ) END)
																				/*поле EKR - линк таблицы KOSGU*/
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_D_EKR_code, ''))) = '' then ('<D_EKR/>' + CHAR(10)) else  ('<D_EKR>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_EKR_code, ''))) +'</D_EKR>'+ CHAR(10) ) END)
																				/*поле DEP - линк таблицы DEPARTMENTS*/
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_d_DEP_CODE, ''))) = '' then ('<D_DEP_CODE/>' + CHAR(10)) else  ('<D_DEP_CODE>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_DEP_CODE, ''))) +'</D_DEP_CODE>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_d_DEP_INN, ''))) = ''  then ('<D_DEP_INN/>' + CHAR(10)) else  ('<D_DEP_INN>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_DEP_INN, ''))) +'</D_DEP_INN>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_d_DEP_KPP, ''))) = '' then ('<D_DEP_KPP/>' + CHAR(10)) else  ('<D_DEP_KPP>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_DEP_KPP, ''))) +'</D_DEP_KPP>'+ CHAR(10) ) END)
																				 /*поле SUB - линк таблицы SUBDIV*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_SUB_code, '')))= '' then ('<D_SUB_code/>' + CHAR(10)) else  ('<D_SUB_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_SUB_code, ''))) +'</D_SUB_code>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_SUB_lim,0),18,2)))= '0.00' then ('<D_SUB_lim/>' + CHAR(10)) else  ('<D_SUB_lim>'+  RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_SUB_lim,0),18,2))) +'</D_SUB_lim>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_SUB_obosob,''))))= 0 then ('<D_SUB_obosob/>' + CHAR(10)) else  ('<D_SUB_obosob>'+ RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_SUB_obosob,'')))) +'</D_SUB_obosob>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_SUB_okato, '')))= '' then ('<D_SUB_okato/>' + CHAR(10)) else  ('<D_SUB_okato>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_SUB_okato, ''))) +'</D_SUB_okato>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_SUB_okpp, '')))= '' then ('<D_SUB_okpp/>' + CHAR(10)) else  ('<D_SUB_okpp>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_SUB_okpp, ''))) +'</D_SUB_okpp>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_SUB_oktmo, '')))= '' then ('<D_SUB_oktmo/>' + CHAR(10)) else  ('<D_SUB_oktmo>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_SUB_oktmo, ''))) +'</D_SUB_oktmo>'+ CHAR(10) ) END)
																				/*поле EMP - линк таблицы SD_EMPL*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_EMP_tab, '')))= '' then ('<D_EMPL_tab/>' + CHAR(10)) else  ('<D_EMPL_tab>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_EMP_tab, ''))) +'</D_EMPL_tab>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_EMP_INSUR_NUM,'')))= '' then ('<D_EMPL_INSUR_NUM/>' + CHAR(10)) else  ('<D_EMPL_INSUR_NUM>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_EMP_INSUR_NUM, ''))) +'</D_EMPL_INSUR_NUM>'+ CHAR(10) ) END)
																				/*поле NOMEN - линк таблицы NOMENCLATURE*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_NOMEN_CODE, '')))= '' then ('<D_NOMEN_CODE/>' + CHAR(10)) else  ('<D_NOMEN_CODE>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_NOMEN_CODE, ''))) +'</D_NOMEN_CODE>'+ CHAR(10) ) END)
																				/*поле INV - линк таблицы INVENTORY*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_INV_code, '')))= '' then ('<D_INVENT_code/>' + CHAR(10)) else  ('<D_INVENT_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_INV_code, ''))) +'</D_INVENT_code>'+ CHAR(10) ) END)
																				/*поле KAU - линк таблицы KAU*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_KAU_code, '')))= '' then ('<D_KAU_code/>' + CHAR(10)) else  ('<D_KAU_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_KAU_code, ''))) +'</D_KAU_code>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_KAU_thema, '')))= '' then ('<D_KAU_thema/>' + CHAR(10)) else  ('<D_KAU_thema>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_KAU_thema, ''))) +'</D_KAU_thema>'+ CHAR(10) ) END)
																				/*поле DEP_ACC - линк таблицы DEPARTMENT_ACCOUNTS*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_DEP_ACC_code, '')))= '' then ('<D_DEP_ACC_code/>' + CHAR(10)) else  ('<D_DEP_ACC_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_DEP_ACC_code, ''))) +'</D_DEP_ACC_code>'+ CHAR(10) ) END)
																				/*поле TMC - линк таблицы DICTION*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_TMC_code,'')))) = 0 then ('<D_TMC_code/>' + CHAR(10)) else  ('<D_TMC_code>'+ RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_TMC_code,'')))) +'</D_TMC_code>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when convert(varchar(10),ISNULL(GP.GPAP_D_INDATE,''),104) = '01.01.1900' then ('<D_INDATE/>' + CHAR(10)) else  ('<D_INDATE>'+ convert(varchar(10),ISNULL(GP.GPAP_D_INDATE,''),104) +'</D_INDATE>'+ CHAR(10) ) END)
																				 /*поле SGU - линк таблицы KOSGU*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_SGU_code, ''))) = 0 then ('<D_SGU_code/>' + CHAR(10)) else  ('<D_SGU_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_SGU_code, ''))) +'</D_SGU_code>'+ CHAR(10) ) END)
																				/*поле AP1 - линк таблицы OSNOV*/
																				/*таблица OSNOV*/
																				--+ SPACE(4) + '<D_AP1_TYPE_LINK>' + case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_AP1_TYPE_LINK,'')))) = 0 THEN '' ELSE RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_AP1_TYPE_LINK,'')))) end  + '</D_AP1_TYPE_LINK>'  + CHAR(10)
																				--+ SPACE(4) + '<D_AP1_doc_link>' +  RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_AP1_doc_link,'')))) + '</D_AP1_doc_link>'  + CHAR(10)
																				/*поле LINK_G_PROV - линк таблицы G_PROV*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_AP1_NUMBER, '')))= '' then ('<D_AP1_NUMBER/>' + CHAR(10)) else  ('<D_AP1_NUMBER>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_AP1_NUMBER, ''))) +'</D_AP1_NUMBER>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when convert(varchar(10),ISNULL(GP.GPAP_D_AP1_DATE,''),104) = '01.01.1900'then ('<D_AP1_DATE/>' + CHAR(10)) else  ('<D_AP1_DATE>'+ convert(varchar(10),ISNULL(GP.GPAP_D_AP1_DATE,''),104) +'</D_AP1_DATE>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_AP1_CODE, ''))) = '' then ('<D_AP1_CODE/>' + CHAR(10)) else  ('<D_AP1_CODE>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_AP1_CODE, ''))) +'</D_AP1_CODE>'+ CHAR(10) ) END)
																				+ SPACE(7) +  (case when convert(varchar(10),ISNULL(GP.GPAP_D_AP1_DATE_PROV,''),104) = '01.01.1900'then ('<D_AP1_DATE_PROV/>' + CHAR(10)) else  ('<D_AP1_DATE_PROV>'+ convert(varchar(10),ISNULL(GP.GPAP_D_AP1_DATE_PROV,''),104) +'</D_AP1_DATE_PROV>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_AP1_SUMMA,0),18,4))) = '0.0000' then ('<D_AP1_SUMMA/>' + CHAR(10)) else  ('<D_AP1_SUMMA>'+ RTRIM(LTRIM(STR(COALESCE(GP.GPAP_D_AP1_SUMMA,0),18,4))) +'</D_AP1_SUMMA>'+ CHAR(10) ) END)
																				 /*поле AP2 - линк таблицы DOP_CLASSIF*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_D_AP2_code, ''))) = '' then ('<D_AP2_code/>' + CHAR(10)) else  ('<D_AP2_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_AP2_code, ''))) +'</D_AP2_code>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_D_AP3, ''))) = 0 then ('<D_AP3/>' + CHAR(10)) else  ('<D_AP3>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_D_AP3, ''))) +'</D_AP3>'+ CHAR(10) ) END)

	
																			/*Кредит*/

				 																+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_K_DB_KR, ''))) = '' then ('<K_DB_KR/>' + CHAR(10)) else  ('<K_DB_KR>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_DB_KR, ''))) +'</K_DB_KR>'+ CHAR(10) ) END)
																				/*поле ACCOUNT - линк таблицы s_accounts*/
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_K_CODE, ''))) = '' then ('<K_ACC/>' + CHAR(10)) else  ('<K_ACC>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_CODE, ''))) +'</K_ACC>'+ CHAR(10) ) END)
																				/*поле KBK - линк таблицы KL_KBK*/
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_K_KBK_code, ''))) = '' then ('<K_KBK/>' + CHAR(10)) else  ('<K_KBK>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_KBK_code, ''))) +'</K_KBK>'+ CHAR(10) ) END)
																				/*поле EKR - линк таблицы KOSGU*/
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_K_EKR_code, ''))) = '' then ('<K_EKR/>' + CHAR(10)) else  ('<K_EKR>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_EKR_code, ''))) +'</K_EKR>'+ CHAR(10) ) END)
																				 /*поле DEP - линк таблицы DEPARTMENTS*/
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_K_DEP_CODE, ''))) = '' then ('<K_DEP_CODE/>' + CHAR(10)) else  ('<K_DEP_CODE>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_DEP_CODE, ''))) +'</K_DEP_CODE>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_K_DEP_INN, ''))) = ''  then ('<K_DEP_INN/>' + CHAR(10)) else  ('<K_DEP_INN>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_DEP_INN, ''))) +'</K_DEP_INN>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when  RTRIM(LTRIM(ISNULL(GP.GPAP_K_DEP_KPP, ''))) = '' then ('<K_DEP_KPP/>' + CHAR(10)) else  ('<K_DEP_KPP>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_DEP_KPP, ''))) +'</K_DEP_KPP>'+ CHAR(10) ) END)
																				 /*поле SUB - линк таблицы SUBDIV*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_SUB_code, '')))= '' then ('<K_SUB_code/>' + CHAR(10)) else  ('<K_SUB_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_SUB_code, ''))) +'</K_SUB_code>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when  RTRIM(LTRIM(STR(COALESCE(GP.GPAP_k_SUB_lim,0),18,2))) = '0.00' then ('<K_SUB_lim/>' + CHAR(10)) else  ('<K_SUB_lim>'+ RTRIM(LTRIM(STR(COALESCE(GP.GPAP_k_SUB_lim,0),18,2))) +'</K_SUB_lim>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_K_SUB_obosob,'')))) = 0 then ('<K_SUB_obosob/>' + CHAR(10)) else  ('<K_SUB_obosob>'+ RTRIM(LTRIM(STR(COALESCE(GP.GPAP_K_SUB_obosob,'')))) +'</K_SUB_obosob>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_SUB_okato, '')))= '' then ('<K_SUB_okato/>' + CHAR(10)) else  ('<K_SUB_okato>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_SUB_okato, ''))) +'</K_SUB_okato>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_SUB_okpp, '')))= '' then ('<K_SUB_okpp/>' + CHAR(10)) else  ('<K_SUB_okpp>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_SUB_okpp, ''))) +'</K_SUB_okpp>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_SUB_oktmo, '')))= '' then ('<K_SUB_oktmo/>' + CHAR(10)) else  ('<K_SUB_oktmo>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_SUB_oktmo, ''))) +'</K_SUB_oktmo>'+ CHAR(10) ) END)
																				/*поле EMP - линк таблицы SD_EMPL*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_EMP_tab, '')))= '' then ('<K_EMPL_tab/>' + CHAR(10)) else  ('<K_EMPL_tab>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_EMP_tab, ''))) +'</K_EMPL_tab>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_EMP_INSUR_NUM,'')))= '' then ('<K_EMPL_INSUR_NUM/>' + CHAR(10)) else  ('<K_EMPL_INSUR_NUM>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_EMP_INSUR_NUM, ''))) +'</K_EMPL_INSUR_NUM>'+ CHAR(10) ) END)
																				/*поле NOMEN - линк таблицы NOMENCLATURE*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_NOMEN_CODE, '')))= '' then ('<K_NOMEN_CODE/>' + CHAR(10)) else  ('<K_NOMEN_CODE>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_NOMEN_CODE, ''))) +'</K_NOMEN_CODE>'+ CHAR(10) ) END)
																				/*поле INV - линк таблицы INVENTORY*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_INV_code, '')))= '' then ('<K_INVENT_code/>' + CHAR(10)) else  ('<K_INVENT_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_INV_code, ''))) +'</K_INVENT_code>'+ CHAR(10) ) END)
																				/*поле KAU - линк таблицы KAU*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_KAU_code, '')))= '' then ('<K_KAU_code/>' + CHAR(10)) else  ('<K_KAU_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_KAU_code, ''))) +'</K_KAU_code>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_KAU_thema, '')))= '' then ('<K_KAU_thema/>' + CHAR(10)) else  ('<K_KAU_thema>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_KAU_thema, ''))) +'</K_KAU_thema>'+ CHAR(10) ) END)
																				/*поле DEP_ACC - линк таблицы DEPARTMENT_ACCOUNTS*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_DEP_ACC_code, '')))= '' then ('<K_DEP_ACC_code/>' + CHAR(10)) else  ('<K_DEP_ACC_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_DEP_ACC_code, ''))) +'</K_DEP_ACC_code>'+ CHAR(10) ) END)						/*поле TMC - линк таблицы DICTION*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_K_TMC_code,'')))) = 0 then ('<K_TMC_code/>' + CHAR(10)) else  ('<K_TMC_code>'+  RTRIM(LTRIM(STR(COALESCE(GP.GPAP_K_TMC_code,'')))) +'</K_TMC_code>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when convert(varchar(10),ISNULL(GP.GPAP_K_INDATE,''),104) = '01.01.1900' then ('<K_INDATE/>' + CHAR(10)) else  ('<K_INDATE>'+ convert(varchar(10),ISNULL(GP.GPAP_K_INDATE,''),104) +'</K_INDATE>'+ CHAR(10) ) END)
																				 /*поле SGU - линк таблицы KOSGU*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_SGU_code, ''))) = 0 then ('<K_SGU_code/>' + CHAR(10)) else  ('<K_SGU_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_SGU_code, ''))) +'</K_SGU_code>'+ CHAR(10) ) END)
																				/*поле AP1 - линк таблицы OSNOV*/
																				/*таблица OSNOV*/
																				/*поле LINK_G_PROV - линк таблицы G_PROV*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_AP1_NUMBER, '')))= '' then ('<K_AP1_NUMBER/>' + CHAR(10)) else  ('<K_AP1_NUMBER>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_AP1_NUMBER, ''))) +'</K_AP1_NUMBER>'+ CHAR(10) ) END)	
																				+ SPACE(7) + (case when convert(varchar(10),ISNULL(GP.GPAP_K_AP1_DATE,''),104) = '01.01.1900' then ('<K_AP1_DATE/>' + CHAR(10)) else  ('<K_AP1_DATE>'+ convert(varchar(10),ISNULL(GP.GPAP_K_AP1_DATE,''),104) +'</K_AP1_DATE>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_AP1_CODE, ''))) = '' then ('<K_AP1_CODE/>' + CHAR(10)) else  ('<K_AP1_CODE>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_AP1_CODE, ''))) +'</K_AP1_CODE>'+ CHAR(10) ) END)
																				+ SPACE(7) +  (case when convert(varchar(10),ISNULL(GP.GPAP_K_AP1_DATE_PROV,''),104) = '01.01.1900'then ('<K_AP1_DATE_PROV/>' + CHAR(10)) else  ('<K_AP1_DATE_PROV>'+ convert(varchar(10),ISNULL(GP.GPAP_K_AP1_DATE_PROV,''),104) +'</K_AP1_DATE_PROV>'+ CHAR(10) ) END)
																				+ SPACE(7) + (case when RTRIM(LTRIM(STR(COALESCE(GP.GPAP_K_AP1_SUMMA,0),18,4))) = '0.0000' then ('<K_AP1_SUMMA/>' + CHAR(10)) else  ('<K_AP1_SUMMA>'+ RTRIM(LTRIM(STR(COALESCE(GP.GPAP_K_AP1_SUMMA,0),18,4))) +'</K_AP1_SUMMA>'+ CHAR(10) ) END)
																				/*поле AP2 - линк таблицы DOP_CLASSIF*/
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_AP2_code, ''))) = '' then ('<K_AP2_code/>' + CHAR(10)) else  ('<K_AP2_code>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_AP2_code, ''))) +'</D_AP2_code>'+ CHAR(10) ) END)
																				
																				+ SPACE(7) + (case when RTRIM(LTRIM(ISNULL(GP.GPAP_K_AP3, ''))) = 0 then ('<K_AP3/>' + CHAR(10)) else  ('<K_AP3>'+ RTRIM(LTRIM(ISNULL(GP.GPAP_K_AP3, ''))) +'</K_AP3>'+ CHAR(10) ) END)
																				FROM
																				#PROV_DOC P
																				INNER JOIN #G_PROV_AP_FULL GP ON GP.GP_LINK = P.GP_LINK AND GP.GPAP_D_LINK_UP = P.GP2_LINK
																			WHERE 
																				GP.GPAP_D_LINK_UP = @d_LINK
																		
																							
															--+ SPACE(5) + '</G_PROV2>' + CHAR(10)

																		END
																		
																		FETCH NEXT FROM @Cur5 INTO @d_LINK
																
																	END
																	CLOSE @Cur5
																	DEALLOCATE @Cur5									
								
													

															
										END
										INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
										SELECT @lcFNAME,
											+ SPACE(5) + '</G_PROV2>' + CHAR(10)
										FETCH NEXT FROM @Cur4 INTO @GP2_LINK
									
									END
									CLOSE @Cur4
									DEALLOCATE @Cur4									
							
								
						END
						INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
						SELECT @lcFNAME,
							+ SPACE(4) + '</G_PROV1>' + CHAR(10)

						FETCH NEXT FROM @Cur3 INTO @GP1_LINK
					
					END
					CLOSE @Cur3
					DEALLOCATE @Cur3
						
					

			END
				INSERT INTO #OUTPUT (F_NAME, OUT_TEXT)
				SELECT @lcFNAME,	
					+ SPACE(3) + '</G_PROV>' + CHAR(10)

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

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

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

	
END

CLOSE @Cur1
DEALLOCATE @Cur1




SET NOCOUNT OFF


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






GO


GRANT EXECUTE ON dbo.[SS_PROV_EXPORT] TO PUBLIC

GO



GO

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

GO

--- ФОРМИРОВАНИЕ АКТА ЗА ВЫПОЛНЕННЫЕ РАБОТЫ ИЗ ВЫДАННОЙ СЧЕТ-ФАКТУРЫ () --- 
CREATE PROCEDURE dbo.BK_SAVE_AKT_EXEC_FROM_INVOICE
	@parm_intINVOICE	INT,
	@parm_intLINK_DOC	INT	OUTPUT
AS
BEGIN
	DECLARE
		@intOBJ_REF	INT,
		@intACC_LINK	INT,
		@intDEP_LINK	INT,
		@strDOC_NUMBER	VARCHAR (25),
		@strINVOICE_NUMBER	VARCHAR (25),
		@dDOC_DATE	DATETIME,
		@intDOG_TYPE	INT,
		@intLINK_OSNOV	INT,
		@intERROR	INT,

		@cINV_TYPE	VARCHAR (30),
		@intLINK_MC	INT,
		@cSFIN_CODE	CHAR (1),
		@intORDERS INT,
		@intUM_LINK INT, 
		@PRICE NUMERIC (18,4), 
		@TAX_RATE NUMERIC(5,2),
		@SFIN_NAME VARCHAR(30), 
		@intLINK_ROW	INT,
		@SUM		NUMERIC (28,4),
		@SUM_NALOG	NUMERIC (28,4),
		@SUMMA_ALL	NUMERIC (28,4),
		@LINK_EKR	INT,

	-- 20080827 ---
		@strOBJ_REF_CODE	VARCHAR (30),
		@strDOC_REF_CODE	VARCHAR (30),
		@strCOMMENT	VARCHAR (254),
		@intCLIENT_LN	INT,
		@lnTAX_RATE	NUMERIC (4,2),
		@QTY		NUMERIC (28,4),
		@intTYPE_NUMBER		INT -- 0 - номер док-та генерируется, 1 - номер равен номеру СЧФК

	SELECT @strOBJ_REF_CODE	= 'DOC_REF_INVOICE_OUT_AKT_EXEC',
		@strDOC_REF_CODE = 'DOCUMENTS_AKT_EXEC_SERVICES'

	EXEC @intOBJ_REF = dbo.X_GET_OBJ_LINK @strOBJ_REF_CODE 

	/* -- ДАННЫЕ ИЗ СЧЕТ ФАКТУРЫ -- */
	SELECT 	@intDEP_LINK	=	G.DEP_LINK,
		@dDOC_DATE	=	G.[DATE],
		@strINVOICE_NUMBER = G.NUMBER,
--		@intACC_LINK	=	COALESCE (G.ACC, T1.MAIN_LINK),
		@intACC_LINK	=	T1.MAIN_LINK,
		@intCLIENT_LN	=	G.BUY_LINK,
		@intLINK_OSNOV	=	G.OSNOV,
		@lnTAX_RATE		=	G.TAX_RATE
	FROM dbo.DOCUMENTS_INVOICE_ISSUED G 
	INNER JOIN dbo.DICTIONARY_DEPARTMENT T1 ON (T1.LINK = G.DEP_LINK)
	WHERE G.LINK = @parm_intINVOICE

	--- ФОРМИРОВАНИЕ ДОКУМЕНТА --- 
	--- Создание ---
	IF @intTYPE_NUMBER = 1
		SET @strDOC_NUMBER = @strINVOICE_NUMBER
	ELSE
		EXEC dbo.X_DOCUMENT_GET_NEXT_NUMBER @strDOC_REF_CODE, @strDOC_NUMBER output, @intDEP_LINK
	
	SET @parm_intLINK_DOC = (SELECT LINK FROM dbo.XK_GetTable_Doc_FOREIGN (@parm_intINVOICE)
					WHERE DOC_CODE = @strDOC_REF_CODE)

	SELECT @strCOMMENT = 'Автосформирован из с\ф выданной № ' + RTRIM (@strINVOICE_NUMBER) + 
		' от ' + CONVERT (VARCHAR (10), @dDOC_DATE, 104)

	EXEC @intERROR = dbo.X_SAVE_DOCUMENTS_AKT_EXEC_SERVICES @parm_intLINK_DOC OUTPUT, @strDOC_NUMBER,
		@dDOC_DATE, DEFAULT, DEFAULT, @strCOMMENT, @intDEP_LINK, @intACC_LINK,
		@intCLIENT_LN, @intLINK_OSNOV, @lnTAX_RATE

	IF @intERROR <> 0
		RETURN @intERROR
	
	IF @parm_intLINK_DOC IS NULL
	BEGIN
		RAISERROR ('Документ не сформирован!', 11, 1)
		RETURN 1
	END

	EXEC dbo.X_UPDATE_G_PROV_REF @parm_intINVOICE, @intOBJ_REF, @parm_intLINK_DOC

	--- !!!СОХРАНЯЕМ ТАБЛИЧНУЮ ЧАСТЬ!!! --- 
	-- Табличная часть СЧ-Фактуры --
	DECLARE #DATA_CURSOR CURSOR LOCAL STATIC	
		FOR SELECT 
				ORDERS,
				INV_TYPE,
				INV_LINK,
				UM_LINK,
				QTY,
				PRICE,
				SUMMA,
				STAVKA_NDS,
				SUMMA_NDS,
				SUMMA_ALL,
				EKR_LINK,
				SFIN_CODE,
				SFIN_NAME
			FROM dbo.BK_DOC_TABLE_MZ_NDS_FN (@parm_intINVOICE) T1
			WHERE INV_TYPE = 'DICTIONARY_SERV'
			ORDER BY ORDERS

	OPEN #DATA_CURSOR
	FETCH FROM #DATA_CURSOR
		INTO @intORDERS, @cINV_TYPE, @intLINK_MC, @intUM_LINK, @QTY, @PRICE, @SUM,
			@TAX_RATE, @SUM_NALOG, @SUMMA_ALL, @LINK_EKR, @cSFIN_CODE, @SFIN_NAME

	WHILE @@FETCH_STATUS = 0
	BEGIN
		SET @intLINK_ROW = NULL

		EXEC @intERROR = dbo.BK_SAVE_DOC_TABLE_MZ_NDS
			@intLINK_ROW OUTPUT,
			@parm_intLINK_DOC,
			@intORDERS,
			@cINV_TYPE,
			@intLINK_MC,
			@PRICE,
			DEFAULT,
			DEFAULT,
			@QTY,
			@SUM,
			@TAX_RATE,
			@SUM_NALOG,
			@SUMMA_ALL,
			@LINK_EKR,
			@cSFIN_CODE 

		IF @intERROR <> 0
			RETURN @intERROR

		FETCH NEXT FROM #DATA_CURSOR
			INTO @intORDERS, @cINV_TYPE, @intLINK_MC, @intUM_LINK, @QTY, @PRICE, @SUM,
				@TAX_RATE, @SUM_NALOG, @SUMMA_ALL, @LINK_EKR, @cSFIN_CODE, @SFIN_NAME
	END

	CLOSE #DATA_CURSOR
	DEALLOCATE #DATA_CURSOR

RETURN 0
END


GO


GRANT EXECUTE ON dbo.[BK_SAVE_AKT_EXEC_FROM_INVOICE] TO PUBLIC

GO




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

GO

CREATE PROCEDURE [dbo].KU_HOLIDAY_COUNT
	@Count int OUTPUT,
	@dDate1 datetime,
	@ndays int
AS  
DECLARE @oldCount int
SELECT @oldCount = 366, @Count = 0
WHILE @Count<>@oldCount
BEGIN
	SET @oldCount = @Count
	SELECT @Count = count(t1.DATE)
	FROM dbo.KU_DAY(@dDate1, @ndays) T1, KD_HOLIDAYS DH
	WHERE day(t1.DATE) = DH.DAY and month(t1.DATE) = DH.MONTH AND YEAR(t1.DATE) = DH.YEAR AND TYPE_HOL = 1
	SET @ndays = @ndays+@Count-@oldCount
END


GO


GRANT EXECUTE ON dbo.[KU_HOLIDAY_COUNT] TO PUBLIC

GO



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

GO





/*
© Кейсистемс (Keysystems), 2006
Выгрузки Лимитов БО и Ассигнований 
*/




CREATE          PROCEDURE dbo.FB_EXPORT_BR_12
		@cBuffId	varchar(30) = '',
		@cObjCode	varchar(30) = ''
AS
DECLARE @iDepLink	int,
	@iPeriod	tinyint,
	@iPeriodType	tinyint


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


-- Блок FROM
SELECT	budg 	as KOD_BP, 
		name 	as NM_BP, 
		0 as link,
		0 as link_up
FROM DICTIONARY_DEPARTMENT 
WHERE  link = @iDepLink

-- Блок TO
SELECT '' as KOD_BP,
		'' as NM_BP,
		0 as link,
		0 as link_up
FROM dbo.DICTIONARY_DEPARTMENT 
WHERE  link = @iDepLink
	

if @cObjCode like '%LIMIT%'
	select  @iPeriod = MAX(FIN_LIM_PER) - 1, @iPeriodType = MAX(FIN_LIM_TYPE) from workmode 
else
begin	
	select  @iPeriod = FIN_SMETA_PER - 1 from workmode
	set @iPeriodType = 0
end

-- Блок RL

select 	PERIOD		= case @iPeriod when 2 then 'M' when 1 then 'Q' else 'Y' end,
	TYPE_RL 	= convert(varchar(1),case  when F.F2=1 then 2 else F.CHANGE end),
	VID_RL		= case  when F.SVOD = 1 then '0' else '1' end,
	NUMBER		= F.NUMBER,
	DATE		= F.DATE,
	DATE_EXEC	= F.DATE_PROV,
	KOD_RBS		= F.DEP_CODE,
	NAME_RBS	= F.DEP_NAME,
	ACC_NUM		= F.BUDG_ACC,
	ACC_SEND	= F.ACC_CODE,
	KOD_BP		= case F.SVOD when 0 then F.FDEP_CODE else '' end,
	NAME_BP		= case F.SVOD when 0 then F.FDEP_NAME else '' end,
	ACC_RCP		= case F.SVOD when 0 then F.FACC_CODE else '' end,
	ACC_SEND_KIND = '',
	ACC_RCP_KIND = '',
	IST		= '',
	S.SUM_YEAR01,
	S.SUM_YEAR02,
	S.SUM_YEAR03,
	PRIM		= '',
	VID_IZM		= '',
	NAME_BUD	= D.BUDG_NAME,
	DOP_UKAZ	= '',
	DATE_SIGN	= null,
	LINK		= F.LINK,
	LINK_UP		= F.LINK

from dbo.FINANS_LIMIT_AND_ASSIGN F
left join dbo.BB_DEP_ACC_DOP(null) D on D.ACC_LINK = F.FACC_LINK
inner join (select LINK_UP, SUM_YEAR01 = SUM(P1 + P2 + P3 + P4 + P5 + P6 + P7 + P8 + P9 + P10 + P11 + P12), SUM_YEAR02 = SUM(Y2),  SUM_YEAR03 = SUM(Y3) from FINANSE GROUP BY LINK_UP) S on S.LINK_UP = F.LINK
where F.link in (select LINK from BUFFER where ID = @cBuffId and SID = SUSER_SID())


select 	LINK		= F.LINK,
		LINK_UP		= F.LINK,
		NOM_OSNOV	= O.NUMBER,
		DATE_OSNOV	= O.DATE,
		OSNOV		= O.[TYPE],
		PRIM		= O.COMMENT
from dbo.FINANSE_HEAD F
inner join dbo.BD_OSNOV O on F.LINK_OSNOV = O.LINK
where exists (select * from dbo.BufferGetTableByID(@cBuffId) where LINK = F.link)


-- Блок RLST
select	TYPE_KBK = case KBK.TYPE when 1 then '10'
								 when 2 then '20'
								 when 4 then '31'
								 when 8 then '32'
								 else '' end,
		KBK = left(rtrim(replace(KBK.CODE,'.','')) + EKR.CODE,30),
		KBK_IST_RF = '',
		ADD_KLASS	= DCL.CODE,
		[LOCAL]		= REG.CODE,
		[SERVICE] = '',
		PURPOSE = '',
		PROGRAM = '',

		SUM1		= case when @iPeriodType = 1 and FH.PER_NUM = 1 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					when @iPeriod = 1 and @iPeriodType = 0 then FT.P1 + FT.P2 + FT.P3
					when @iPeriod = 2 and @iPeriodType = 0 then FT.P1
					else 0 end,
		SUM2		= case  when @iPeriod = 1 and @iPeriodType = 0 then FT.P4 + FT.P5 + FT.P6
					when @iPeriod = 2 and @iPeriodType = 0 then FT.P2
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 2 or @iPeriod = 1 and @iPeriodType = 1 and FH.PER_NUM = 4 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM3		= case  when @iPeriod = 1 and @iPeriodType = 0 then FT.P7 + FT.P8 + FT.P9
					when @iPeriod = 2 and @iPeriodType = 0 then FT.P3
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 3 or @iPeriod = 1 and @iPeriodType = 1 and FH.PER_NUM = 7 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM4		= case  when @iPeriod = 1 and @iPeriodType = 0 then FT.P10 + FT.P11 + FT.P12
					when @iPeriod = 2 and @iPeriodType = 0 then FT.P4
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 4 or @iPeriod = 1 and @iPeriodType = 1 and FH.PER_NUM = 10 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM5		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P5 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 5 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM6		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P6 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 6 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM7		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P7 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 7 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM8		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P8 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 8 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM9		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P9 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 9 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM10		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P10 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 10 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM11		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P11
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 11 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM12		= case  when @iPeriod = 2 and @iPeriodType = 0 then FT.P12 
					when @iPeriod = 2 and @iPeriodType = 1 and FH.PER_NUM = 12 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12
					else 0 end,
		SUM_YEAR01	= case @iPeriod when 0 then FT.P1 + FT.P2 + FT.P3 + FT.P4 + FT.P5 + FT.P6 + FT.P7 + FT.P8 + FT.P9 + FT.P10 + FT.P11 + FT.P12 else 0 end,
		SUM_YEAR02	= FT.Y2,
		SUM_YEAR03	= FT.Y3,
		LINK		= FT.LINK,
		LINK_UP		= FT.LINK_UP
from dbo.FINANSE FT
inner join dbo.FINANSE_HEAD FH on FH.LINK = FT.LINK_UP
left join dbo.BI_DICTION_VKR VKR on VKR.LINK_KBK = FT.VKR 
left join dbo.KL_KBK KBK on KBK.LINK = FT.VKR --and KBK.TYPE <> 1 
left join dbo.DOP_CLASSIF DCL on DCL.LINK = FT.DOP_CL 
left join dbo.KL_REG REG on REG.LINK = FT.REG 
left join dbo.KOSGU EKR on EKR.LINK = FT.EKR 
where FT.LINK_UP in (select LINK from BUFFER where ID = @cBuffId and SID = SUSER_SID())




GO


GRANT EXECUTE ON dbo.[FB_EXPORT_BR_12] TO PUBLIC

GO



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

GO
CREATE PROCEDURE dbo.BK_TEST_EXP_F1152027 (@Res tinyint output, @link int, @m int) 
AS
BEGIN
	DECLARE @INN VARCHAR (12),
			@KPP VARCHAR (10),
			@IMNS	INT,
			@OKATO VARCHAR (20),
			@OKVED	VARCHAR (10),
			@iLINK_TABLE INT,
			@KBK VARCHAR (30)

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


	SELECT 	@INN = INN,
			@KPP = KPP,
			@IMNS = IMNS_LINK,
			@OKATO = OKATO,
			@OKVED = RTRIM (REPLACE (OKVED, '.', ''))
	FROM dbo.DEPARTMENTS D
	INNER JOIN dbo.REPORT_SAVED_FORMS R ON R.LINK_ORGANIZATION = D.LINK
	WHERE LINK_SAVED_FORM = @link


	--- !!!РАСЧЕТ!!! ---
	SELECT @iLINK_TABLE = LINK_TABLE
	FROM 	(select *, CASE WHEN ORDERS = 1 THEN 2 WHEN ORDERS = 2 THEN 1 END AS REAL_ORD
		from report_tables
		where link_form = (select link_form
							from report_saved_forms
							where link_saved_form = @link)) AS T
	WHERE REAL_ORD = 1

	SELECT @KBK = KBK, @OKATO = ISNULL (@OKATO, OKATO)
	FROM
	(SELECT (SELECT CONVERT (VARCHAR (30), Str_Val) FROM dbo.REPORT_STRING
				WHERE LINK_SAVED_FORM = @link
				AND LINK_COL = (SELECT RC1.LINK_COL FROM dbo.REPORT_COLOUMNS RC1 WHERE RC1.LINK_TABLE = @iLINK_TABLE
									AND UPPER (RC1.[NAME]) = 'КОД ДОХОДА')
				) AS KBK,
		(SELECT CONVERT (VARCHAR (20), Str_Val) FROM dbo.REPORT_STRING
					WHERE LINK_SAVED_FORM = @link
					AND LINK_COL = (SELECT RC1.LINK_COL FROM dbo.REPORT_COLOUMNS RC1 WHERE RC1.LINK_TABLE = @iLINK_TABLE
										AND UPPER (RC1.[NAME]) = 'КОД ПО ОКАТО')
					) AS OKATO
	FROM dbo.REPORT_ROWS RR
	WHERE RR.LINK_TABLE = @iLINK_TABLE) AS T


	IF ISNULL (@INN, '') = '' OR ISNULL (@KPP, '') = '' OR ISNULL (@IMNS, 0) = 0
			 OR ISNULL (@OKATO, '') = '' OR ISNULL (@KBK, '') = '' OR ISNULL (@OKVED, '') = ''
		SET @Res = 0
	ELSE
		SET @Res = 1

	SELECT MSG_BEFORE = 'Не указаны следующие реквизиты:', Msg = 'Не указан ИНН организации.',
			msg_after  = 'Необходимо указать ИНН в настройках организации.'
	WHERE ISNULL (@INN, '') = '' 
	UNION
	SELECT MSG_BEFORE = 'Не указаны следующие реквизиты:', Msg = 'Не указан КПП организации.',
			msg_after  = 'Необходимо указать КПП в настройках организации.'
	WHERE ISNULL (@KPP, '') = '' 
	UNION
	SELECT MSG_BEFORE = 'Не указаны следующие реквизиты:', Msg = 'Не указан ОКАТО организации.',
			msg_after  = 'Необходимо указать ОКАТО в настройках организации.'
	WHERE ISNULL (@OKATO, '') = '' 
	UNION
	SELECT MSG_BEFORE = 'Не указаны следующие реквизиты:', Msg = 'Не указан код налогового органа.',
			msg_after  = 'Укажите налоговый орган в настройках организации на вкладке реквизиты "ИМНС".'
	WHERE ISNULL (@IMNS, '') = '' 
	UNION
	SELECT MSG_BEFORE = 'Не указаны следующие реквизиты:', Msg = 'Не указан ОКВЭД.',
			msg_after  = 'Укажите ОКВЭД в настройках организации на вкладке Прочие "ОКВЭД".'
	WHERE ISNULL (@OKVED, '') = '' 
	UNION
	SELECT MSG_BEFORE = 'Не указаны следующие реквизиты:', Msg = 'Не указан КБК.',
			msg_after  = 'Укажите КБК в расчитанной форме на вкладке Раздел1 или в настройках деклараций.'
	WHERE ISNULL (@KBK, '') = '' 
END





GO


GRANT EXECUTE ON dbo.[BK_TEST_EXP_F1152027] TO PUBLIC

GO



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

GO



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

CREATE	PROCEDURE dbo.BI_SAVE_KBK_KD
	@varKSparLINK	int	OUTPUT,
	@varKSparNAME	VARCHAR(250) = '',
	@varKSLink_Adm	int = null,
	@varKSLink_KD	int,
	@iLinkProg		int,
	@varKSLink_SGU  INT,
	@iUsed			int,
	@cDelim			char(1) = '.'
AS
DECLARE @varKSERROR	tinyint,
	@varKSRowCount	INT,
	@varKSstrVALUE	varchar(7000),
	@varKStrancount	int,
	@varKSEventText	varchar(254),
	@varKSintObj	int,
	@varKSCode	char(30)
SET LOCK_TIMEOUT 30000
SET @varKStrancount = @@TRANCOUNT
SET IMPLICIT_TRANSACTIONS ON
BEGIN TRAN
COMMIT TRAN


	IF @varKSparNAME IS NULL OR @varKSparNAME = ''
	BEGIN
		ROLLBACK
		RETURN 5
	END
	IF @varKSLink_KD IS NULL OR @varKSLink_KD = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END
	IF @iLinkProg IS NULL OR @iLinkProg = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END
	IF @varKSLink_Adm IS NULL OR @varKSLink_Adm = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END
/*	IF @varKSLink_SGU IS NULL OR @varKSLink_SGU = 0
	BEGIN
		ROLLBACK
		RETURN 5
	END*/

	if (select count(*) from KL_KD where link = @varKSLink_KD)<>1
	OR (select count(*) from KL_ADMIN_BS where link = @varKSLink_Adm)<>1
	OR (select count(*) from KL_PROG where link = @iLinkProg)<>1
	BEGIN
		ROLLBACK
		RETURN 5
	END
	
	SET @varKSCode = coalesce ((SELECT code FROM KL_ADMIN_BS WHERE link = @varKSLink_Adm),'000') + @cDelim +
			coalesce ((SELECT code FROM KL_KD WHERE link = @varKSLink_KD),'0000000000') + --@cDelim +
			coalesce ((SELECT code FROM KL_PROG WHERE link = @iLinkProg),'0000')+ 
			coalesce ((SELECT code FROM KOSGU WHERE link = @varKSLink_SGU),'')
	
	If (select count(*) from KL_KBK where link <> @varKSparLINK and CODE = @varKSCode AND TYPE = 2) <> 0 
	BEGIN
		ROLLBACK
		RETURN 4
	END
	
	If (Select count(*) from KL_KBK where link = @varKSparLINK) > 0
	BEGIN
		UPDATE KL_KBK
		SET 	TYPE = 2,
			CODE = @varKSCode,
			NAME = @varKSparNAME,
			Link_Adm = @varKSLink_Adm,
			USED = @iUsed
		WHERE LINK = @varKSparLINK
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
		DELETE FROM KL_KBK_IVF WHERE LINK_KBK = @varKSparLINK
		DELETE FROM KL_VKR WHERE LINK_KBK = @varKSparLINK
	END
	ELSE
	BEGIN
		INSERT INTO KL_KBK(Type, code, name, link_adm, USED)
			VALUES(2, @varKSCode, @varKSparNAME, @varKSLink_Adm, @iUsed)
		SELECT @varKSERROR = @@ERROR, @varKSparLINK = @@IDENTITY
		IF @varKSERROR <> 0 or coalesce(@varKSparLINK,0) <= 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END

	IF (select count(*) from KL_KBK_KD where link_kbk = @varKSparLINK) = 1
	BEGIN
		UPDATE KL_KBK_KD
			SET LINK_KD = @varKSLink_KD,
				LINK_PROG = @iLinkProg,
				LINK_SGU = @varKSLink_SGU
			WHERE LINK_KBK = @varKSparLINK
		
		SELECT @varKSERROR = @@ERROR
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	ELSE
	BEGIN
		INSERT INTO KL_KBK_KD 
			(Link_KBK, Link_KD, LINK_PROG,LINK_SGU)
		VALUES (@varKSparLINK, @varKSLink_KD, @iLinkProg,@varKSLink_SGU)
		SELECT @varKSERROR = @@ERROR
		IF @varKSERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END
	END
	
	SELECT @varKSEventText = 'КБК. Классификатор доходов ' + @varKSCode + ' ' + @varKSparNAME, @varKSintObj = LINK FROM S_OBJECTS WHERE CODE = 'BI_DICTION_KBK'
	EXECUTE WF_GENERATEEVENT 'Сохранение строки справочника', @varKSEventText, @varKSintObj, 'KL_KBK', @varKSparLINK
IF @@TRANCOUNT > @varKStrancount
	COMMIT TRAN
RETURN 0





GO


GRANT EXECUTE ON dbo.[BI_SAVE_KBK_KD] TO PUBLIC

GO


GO

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


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

CREATE             

PROCEDURE dbo.BB_SAVE_REPORT_CALC_ROW
	@iLink		int	OUTPUT,
	@iLinkCalc	int,
	@iOrder		tinyint,
	@cSign		char(4),
	@cDtMask	varchar(100),
	@cKtMask	varchar(100),
	@cDtEKR		varchar(1000),
	@cKtEKR		varchar(1000),
	@iTypeKBK	tinyint,
	@cType		varchar(100),
	@cMaskKBK	varchar(100),
	@cDtKt		char(6),
	@cOper		varchar(1000)


as
set lock_timeout 30000
set implicit_transactions on
declare @iERROR		tinyint,
		@iTrancount	int,
		@iRowCount	int,
		@iSign		tinyint,
		@iType		tinyint,
		@iDtKt		tinyint
	


set @iTrancount = @@TRANCOUNT
set @iSign = case when @cSign = '+' then 1 when @cSign = '-' then 2 else 3 end
set @iType = case when UPPER(@cType) = 'ПРОВОДКА' then 1 when CHARINDEX('начало', @cType) > 0 then 2 else 3 end
set @iDtKt = case when @cDtKt = 'Дебет' then 0 else 1 end
set @cMaskKBK = replace(replace(replace(replace(replace(replace(rtrim(@cMaskKBK),'х','x'),'Х','X'),'О','0'),'о','0'),'O','0'),'o','0')
set @cMaskKBK = replace(replace(replace(@cMaskKBK, '0К','ОК'),'Т0','ТО'),'М0','МО') -- вертаем в зад О вместо нолей для окато
set @cDtMask = replace(rtrim(ltrim(@cDtMask)),',','.')
set @cKtMask = replace(rtrim(ltrim(@cKtMask)),',','.')
if @iType > 1
begin
	if isnull(@cDtMask,'') <> '' and isnull(@cKtMask,'') <> ''
		if @iDtKt = 0
			set @cKtMask = ''
		else
			set @cDtMask = ''
	if isnull(@cDtEKR,'') <> '' and isnull(@cKtEKR,'') <> ''
		if @iDtKt = 0
			set @cKtEKR = ''
		else
			set @cDtEKR = ''
end		
	
	
		
set implicit_transactions on
begin tran
commit tran
	
		UPDATE dbo.REPORT_CALC_ROWS
		SET Link_Calc = @iLinkCalc,
			Orders = @iOrder,
			[Sign] = @iSign,
			DT_Mask = @cDtMask,
			KT_Mask = @cKtMask,
			DT_EKR = @cDtEKR,
			KT_EKR = @cKtEKR,
			Type_KBK = @iTypeKBK,
			[Type] = @iType,
			Mask_KBK = @cMaskKBK,
			DT_KT = @iDtKt,
			OPER = @cOper
		WHERE LINK = @iLink
		
		SELECT @iRowCount = @@ROWCOUNT, @iERROR = @@ERROR
		IF @iERROR <> 0
		BEGIN
			ROLLBACK
			RETURN 7
		END

		IF @iRowCount = 0
		BEGIN
			INSERT INTO dbo.REPORT_CALC_ROWS (Link_Calc, Orders, [Sign], DT_Mask, KT_Mask, DT_EKR, KT_EKR, Type_KBK, [Type], Mask_KBK, DT_KT, OPER)
			VALUES (@iLinkCalc, @iOrder, @iSign, @cDtMask, @cKtMask, @cDtEKR, @cKtEKR, @iTypeKBK, @iType, @cMaskKBK, @iDtKt, @cOper)
			SELECT @iERROR = @@ERROR, @iLink = @@IDENTITY
			IF @iERROR <> 0
			BEGIN
				ROLLBACK
				RETURN 7
			END
		END	
	

if @@trancount > @iTrancount
	Commit tran
return 0

GO



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

GO

CREATE PROCEDURE dbo.SA_CALENDAR_DAYS_ALLYEAR_INFO (@linkEmpl int, @Year int)
AS

DECLARE @INFO TABLE (
	ORD TINYINT, 
	NAME VARCHAR(254), 
	DATE_BEG DATETIME, 
	DATE_END DATETIME, 
	COMMENT VARCHAR(254), 
	LINK_OBJ INT, 
	CODE_OBJ VARCHAR(254)
)

/* Расшифровка рассчёта календарных дней */

declare @DateBegin datetime, @DateEnd datetime

--SET @DateBegin = dbo.ConvertDMY2Date(1,@Month,@Year) 
--SET @DateEnd 	= dbo.DateEndOfMonth(@DateBegin)

SET @DateBegin = dbo.ConvertDMY2Date(1,1,@Year) 
SET @DateEND = dbo.ConvertDMY2Date(1,12,@Year)
SET @DateEnd 	= dbo.DateEndOfMonth(@DateEND)

DECLARE @DateAccept datetime, @DateSack datetime
SET @DateAccept = ISNULL(dbo.kd_DateBeginWork(@linkEmpl,@DateEnd),'19000101')
SET @DateSack   = ISNULL(dbo.kd_DateEndWork(@linkEmpl,@DateEnd),'30000101')

SET @DateBegin = (case when @DateAccept < @DateBegin then @DateBegin else @DateAccept end)
SET @DateEnd = (case when @DateSack < @DateEnd then @DateSack else @DateEnd end)  

DECLARE @RealCount NUMERIC(18,2)
SET @RealCount = DBO.SA_CALENDAR_DAYS_AllYear_FN(@linkEmpl,@Year)

INSERT INTO @INFO (ORD, NAME, DATE_BEG, DATE_END, COMMENT, LINK_OBJ, CODE_OBJ)
SELECT 
	1, 'Период работы', @DateBegin, @DateEnd, 'Приказ о приёме/увольнениии',
	(SELECT ORDER_LINK FROM ITEM_MOVE WHERE NEW_FACE = 1 AND EMPL_LINK = @linkEmpl AND ACTIVE = 1),
	'ORDERS_REESTR'

UPDATE @INFO
SET LINK_OBJ = (SELECT TOP 1 ORDER_LINK FROM ITEM_DIS_FACE IM WHERE EMPL_LINK = @linkEmpl AND  ACTIVE = 1)
WHERE @DateSack = @DateEnd

DECLARE @S TABLE 
([TYPE] int,
 [PRIOR] int,
 [HOUR]  numeric(6,2),
 [DATE_1] datetime,
 [DATE_2] datetime,
 [DOC]	int,
 [H] int,
 LINK_DOC INT 	 	
)


--Учёт периодов с предыдущих мест работы, которые не должны включаться в расчёт календарных дней
DECLARE @TYPE_OTHER_DEP_PERIOD INT, @PRIOR_OTHER_DEP_PERIOD INT, @HOUR_OTHER_DEP_PERIOD NUMERIC(18,2)
SELECT TOP 1 @TYPE_OTHER_DEP_PERIOD = N.LINK, @PRIOR_OTHER_DEP_PERIOD = TD.PRIORITET, @HOUR_OTHER_DEP_PERIOD = TD.[HOUR]
FROM 
	dbo.NETRUD N
	INNER JOIN dbo.TYP_DAYS TD ON TD.LINK = N.TYPE_LINK
ORDER BY
	(CASE WHEN WORK_D = 13 THEN 1 ELSE 2 END), N.CODE

IF @TYPE_OTHER_DEP_PERIOD IS NOT NULL
	INSERT INTO @S ([TYPE],[PRIOR],[HOUR],[DATE_1],[DATE_2],[DOC], [H], LINK_DOC)
	SELECT 
		[TYPE] = @TYPE_OTHER_DEP_PERIOD, 
		[PRIOR] = @PRIOR_OTHER_DEP_PERIOD, 
		[HOUR] = @HOUR_OTHER_DEP_PERIOD,
		[DATE_1] = (CASE WHEN P.DATE1 < @DateBegin THEN @DateBegin ELSE P.DATE1 END),
		[DATE_2] = (CASE WHEN P.DATE2 > @DateEnd  THEN @DateEnd ELSE P.DATE2 END),
		[DOC]	= 4,--периоды с предыдущих мест работы
		[H] = 0,
		D.LINK
	FROM
		dbo.SAL_OTHER_DEP D
		INNER JOIN dbo.SAL_OTHER_DEP_PERIOD_DATES P ON D.LINK = P.LINK_DOC
	WHERE
		LINK_EMPL = @linkEmpl
		AND
		(
			P.DATE1 BETWEEN @DateBegin AND @DateEnd 
			OR P.DATE2 BETWEEN @DateBegin AND @DateEnd 
			OR (P.DATE1 < @DateBegin AND P.DATE2 > @DateEnd)
		)		
-----------------------------------------------------------------------

INSERT INTO @S ([TYPE],[PRIOR],[HOUR],[DATE_1],[DATE_2],[DOC], [H], LINK_DOC)
--больничные
SELECT [TYPE],[PRIOR],[HOUR],[DATE_1],[DATE_2],[DOC], H, LINK FROM 
(SELECT 
	[TYPE] = SD.[TYPE],
	[PRIOR] = TD.PRIORITET,
	[HOUR] = TD.[HOUR],
	[DATE_1] = (CASE WHEN SD.DATE1 < @DateBegin THEN @DateBegin ELSE SD.DATE1 END),
	[DATE_2] = (CASE WHEN SD.DATE2 > @DateEnd  THEN @DateEnd ELSE SD.DATE2 END),
	[DOC]	= 1,
	[H] = 0,
	LINK = SD.LINK_UP 
FROM 
	dbo.SDOC_DIS SD
	INNER JOIN dbo.NETRUD N ON SD.[TYPE] = N.LINK
	INNER JOIN dbo.TYP_DAYS TD ON TD.LINK = N.TYPE_LINK
WHERE 
	SD.LINK_EMPL = @linkEmpl
	AND
	(SD.DATE1 BETWEEN @DateBegin AND @DateEnd OR SD.DATE2 BETWEEN @DateBegin AND @DateEnd OR
	  ((SD.DATE1 < @DateBegin) AND(SD.DATE2 > @DateEnd)))
  
UNION
--отпускные
SELECT 	
	[TYPE] = VV.TYPE_LINK,
	[PRIOR] = TD.PRIORITET,
	[HOUR] 	= TD.[HOUR],
	[DATE_1] = (CASE WHEN DATE_BEGIN < @DateBegin THEN @DateBegin ELSE IV.DATE_BEGIN END),
	[DATE_2] = (CASE WHEN ISNULL((

					SELECT top 1 (CASE WHEN IVB.DATE_BREAK - 1 > (ISNULL((

                    SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  
 					FROM dbo.ITEM_VACATION_DIS IVD
                    WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc),IV.DATE_END)) 
					
                    THEN (ISNULL((

					SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  
 					FROM dbo.ITEM_VACATION_DIS IVD
					WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc),IV.DATE_END)) 
					
					ELSE IVB.DATE_BREAK - 1 END) 

					FROM dbo.ITEM_VACATION_BREAK IVB
					WHERE IVB.VAC_LINK = IV.LINK AND IVB.ACTIVE = 1 order by IVB.DATE_BREAK desc), 
					
                    (ISNULL((

					SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  
 					FROM dbo.ITEM_VACATION_DIS IVD 
					WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc ),IV.DATE_END))) >@DateEnd 

					THEN @DateEnd  
                    ELSE ISNULL((

                    SELECT top 1 (CASE WHEN IVB.DATE_BREAK - 1 > (ISNULL((

					SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  
 					FROM ITEM_VACATION_DIS IVD
        				WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc ),IV.DATE_END)) 
					
                    THEN (ISNULL((

					SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  

 					FROM dbo.ITEM_VACATION_DIS IVD
					WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc),IV.DATE_END)) 

					ELSE IVB.DATE_BREAK - 1 END)  
					
					FROM dbo.ITEM_VACATION_BREAK IVB
					WHERE IVB.VAC_LINK = IV.LINK AND IVB.ACTIVE = 1 order by IVB.DATE_BREAK desc),
					
					ISNULL((
					
					SELECT top 1 (CASE WHEN IVD.NEW_DATE_END > IV.DATE_END THEN IVD.NEW_DATE_END ELSE  IV.DATE_END END)  
 					FROM dbo.ITEM_VACATION_DIS IVD 
					WHERE  IVD.VAC_LINK = IV.LINK AND IVD.ACTIVE = 1 order by IVD.NEW_DATE_END desc),IV.DATE_END)) END),
	[DOC] = (case when coalesce(TD.WORK_D,1) = 7 then 22 else 2 end),
	H = VV.HOLIDAY,
	LINK = IV.LINK
FROM 
	dbo.item_vacation iv
	INNER JOIN dbo.vacation_vid VV ON VV.LINK = iv.type_link
	INNER JOIN dbo.TYP_DAYS TD ON TD.LINK = VV.TYPE_LINK
WHERE 
	IV.EMPL_LINK = @linkEmpl 
	AND IV.ACTIVE = 1
	AND COALESCE(VV.TIME_ARCHE,0) = 0 
	AND (IV.DATE_BEGIN BETWEEN @DateBegin AND @DateEnd 
		OR IV.DATE_END BETWEEN @DateBegin AND @DateEnd 
		OR ((IV.DATE_BEGIN<@DateBegin) AND (IV.DATE_END>@DateEnd))
		OR IV.LINK IN (SELECT VAC_LINK FROM dbo.VACATION_DIS WHERE EMPL_LINK = @linkEmpl AND ACTIVE = 1 AND NEW_DATE_END > @DateBegin)
	    )
	AND IV.LINK NOT IN (SELECT VAC_LINK FROM dbo.item_vacation_break ivb WHERE EMPL_LINK = @linkEmpl AND ACTIVE = 1 AND ivb.DATE_BREAK < @DateBegin)
--командировочные
UNION
SELECT 
	[TYPE] 	= it.type_link, 
	[PRIOR] = TD.PRIORITET,
	[HOUR] = TD.[HOUR], 
	[DATE_1] = (CASE WHEN IT.[DATE_BEGIN]<@DateBegin THEN @DateBegin ELSE IT.[DATE_BEGIN] END),
	[DATE_2] = (CASE WHEN (ISNULL((SELECT (CASE WHEN ITL.NEW_DATE_END > IT.DATE_END THEN ITL.NEW_DATE_END ELSE IT.DATE_END END)
				 FROM dbo.ITEM_TRAVEL_LONG ITL WHERE ITL.TRAVEL_LINK = IT.LINK AND ITL.ACTIVE = 1),IT.DATE_END))> @DateEnd 
				 THEN @DateEnd ELSE 
				(ISNULL((SELECT (CASE WHEN ITL.NEW_DATE_END > IT.DATE_END THEN ITL.NEW_DATE_END ELSE IT.DATE_END END)
				 FROM dbo.ITEM_TRAVEL_LONG ITL WHERE ITL.TRAVEL_LINK = IT.LINK AND ITL.ACTIVE = 1),IT.DATE_END)) END),
	[DOC]= 3,
	[H] = 0,
	LINK = IT.LINK
FROM 
	dbo.item_travel IT
	INNER JOIN dbo.komand_vid KV ON KV.LINK = IT.type_link
	INNER JOIN dbo.TYP_DAYS TD ON TD.LINK = KV.TYPE_LINK
WHERE  
	IT.EMPL_LINK = @linkEmpl 
	AND IT.ACTIVE = 1 
	AND COALESCE(KV.TIME_ARCHE,0) = 0 
	AND (IT.DATE_BEGIN BETWEEN @DateBegin AND @DateEnd 
		OR IT.DATE_END BETWEEN @DateBegin AND @DateEnd 
		OR ((IT.DATE_BEGIN<@DateBegin) AND(IT.DATE_END>@DateEnd))
	 )
)  TAB

DELETE FROM @S
WHERE DATE_1 > DATE_2

INSERT INTO @INFO (ORD, NAME, DATE_BEG, DATE_END, COMMENT, LINK_OBJ, CODE_OBJ)
	SELECT 2, 'Больничный лист', DATE_1, DATE_2, 'Больничный лист', LINK_DOC, 'ORDER_DISABILITY_SHEET'
	FROM @S WHERE DOC = 1
UNION 
	SELECT 3, 'Отпуск, учитывающий праздники', DATE_1, DATE_2, 'Приказ на отпуск', LINK_DOC, 'VACATION'
	FROM @S WHERE DOC IN (2,22) AND coalesce(H,0) = 1
UNION 
	SELECT 4, 'Отпуск, не учитывающий праздники', DATE_1, DATE_2, 'Приказ на отпуск', LINK_DOC, 'VACATION'
	FROM @S WHERE DOC IN (2,22) AND coalesce(H,0) <> 1
UNION 
	SELECT 5, 'Командировка', DATE_1, DATE_2, 'Приказ на командировку', LINK_DOC, 'TRAVEL'
	FROM @S WHERE DOC = 3
UNION 
	SELECT 6, 'Заработок у другого работодателя', DATE_1, DATE_2, 'Заработок у другого работодателя', LINK_DOC, 'DOC_SAL_OTHER_DEP'
	FROM @S WHERE DOC = 4	

INSERT INTO @INFO (ORD, NAME, DATE_BEG, DATE_END, COMMENT, LINK_OBJ, CODE_OBJ)
	SELECT 7, 'Праздничные дни', t1.DATE, t1.DATE, TYPE_HOL_STR, LINK, 'KD_HOLIDAYS'
	FROM
		dbo.SD_DAY(@DateBegin,@DateEnd) T1 
		INNER JOIN KD_HOLIDAYS DH ON day(t1.DATE) = DH.DAY and month(t1.DATE) = DH.MONTH AND YEAR(t1.DATE) = DH.YEAR
	WHERE 
		(DH.WORK_D = 14 or DH.WORK_D = 11) AND TYPE_HOL = 1
		AND
		EXISTS (SELECT * FROM @INFO I WHERE ORD = 3 AND T1.DATE BETWEEN DATE_BEG AND DATE_END)

SELECT ORD, [NAME] AS NAME_PER, DATE_BEG, DATE_END, 
	CNT_DAYS = CASE WHEN ORD BETWEEN 2 AND 6 THEN -1 ELSE 1 END * (datediff(day,DATE_BEG,DATE_END) + 1 ), 
	RealCount = @RealCount, COMMENT AS COM , LINK_OBJ, CODE_OBJ 
FROM @INFO ORDER BY ORD, DATE_BEG

RETURN 0


GO


GRANT EXECUTE ON dbo.[SA_CALENDAR_DAYS_ALLYEAR_INFO] TO PUBLIC

GO





GO

--AFTER CODE 31.12.2015
-- Измение плана счетов по 124Н --
DECLARE
	@BUF_NAME	VARCHAR (100)

SET @BUF_NAME = '157N_CHANGE_124N_2015'

IF dbo.BS_GetWorkMode (@BUF_NAME) = 0
BEGIN
	--- Формирование плана счетов при переходе на новый учет ---
	EXEC dbo.XK_CREATE_NEW_PLAN_ACCOUNTS @BUF_NAME

	--- Настройка плана счетов при переходе на новый учет ---
	EXEC dbo.XK_NASTR_NEW_PLAN_ACCOUNTS @BUF_NAME

	--- Настройка счетов на КОСГУ ---
	EXEC dbo.XK_NASTR_S_ACCOUNTS_KOSGU
		@intLINK_ACCT	= NULL,
		@BUF_NAME	= @BUF_NAME,
		@iTYPE_REC	= 3,
		@intDEP_LINK = NULL

	-- Установка флага завершения перехода --
	EXEC dbo.BS_SetWorkMode
		@WORK_MODE = @BUF_NAME,
	  	@WORK_STATUS =	1		
END

GO


GO
UPDATE dbo.HOLIDAYS SET [DAY] = 4 WHERE NAME LIKE '4%МА%' OR (DAY1 = 4 AND MONTH1 = 1)
GO

--DELETE FROM dbo.GRAPHICS WHERE YEAR(PERIOD) = 2015 AND MONTH(PERIOD) = 5

--/*Формирование всех используемых графиков на 2015 год*/
--DECLARE @Cur1 CURSOR, @LinkGrophik int, @VID_LINK int, @NAME_GR varchar(254)
--DECLARE @Cur2 CURSOR, @DAY tinyint, @HOUR numeric(18,2), @TD_LINK int

--DECLARE @MONTH INT, @YEAR INT
--DECLARE @LINK INT, @LINK2 INT, @gDayNorm INT, @gHourNorm numeric(18,2)

--DECLARE @ISMINUTES TINYINT
--SET @ISMINUTES = DBO.SA_GET_OPTION_BY_CODE('TABEL_OPT10') --УЧЕТ ВРЕМЕНИ В ЧАСАХ И МИНУТАХ

--SET @Cur1 = CURSOR FORWARD_ONLY

--FOR select LINK, VID_LINK, [NAME] from GRAPH order by link
--OPEN @Cur1
--FETCH NEXT FROM @Cur1 INTO @LinkGrophik, @VID_LINK, @NAME_GR
--WHILE (@@fetch_status <> -1)
--BEGIN
--	IF (@@fetch_status <> -2)
--	BEGIN

--		SELECT @YEAR = 2015, @MONTH = 5
--		WHILE @MONTH = 5
--		BEGIN
	
--			IF NOT EXISTS(SELECT @LinkGrophik FROM dbo.KD_GRAPH_TABLE WHERE [YEAR] = @YEAR AND [MONTH] = @MONTH AND LINK_GR = @LinkGrophik)
--			BEGIN
--				IF object_id('tempdb..#sa_tmp_graph') is not null
--				drop table #sa_tmp_graph
				
--				CREATE TABLE #sa_tmp_graph(CHECKED tinyint, UPD tinyint, DEL tinyint, [DAY] tinyint, [HOUR] numeric(18,2), TD_LINK int, TD_CODE varchar(10),
--						TD_NAME varchar(254), PRIORITET tinyint )
				
--				INSERT INTO #sa_tmp_graph(CHECKED, UPD, DEL, [DAY], [HOUR], TD_LINK, TD_CODE, TD_NAME, PRIORITET)
--				exec dbo.KD_GRAPH_FILL @VID_LINK, @MONTH, @YEAR
				
--				Select @gHourNorm = DBO.MINUTES_TO_NUM(SUM(DBO.NUM_TO_MINUTES([HOUR],@ISMINUTES)),@ISMINUTES) from #sa_tmp_graph where [HOUR] > 0
--				Select @gDayNorm = COUNT(DISTINCT [DAY]) from #sa_tmp_graph where [HOUR] > 0
				
--				IF COALESCE(@gHourNorm,0) > 0 AND coalesce(@gDayNorm,0) > 0
--				BEGIN
				
--					EXEC dbo.KD_GRAPH_SAVE @LinkGrophik OUT, @LINK2 OUT, @NAME_GR, @MONTH, @YEAR, @VID_LINK, @gDayNorm, @gHourNorm
		
--					SET @Cur2 = CURSOR FORWARD_ONLY
					
--					FOR select [DAY], [HOUR], [TD_LINK] from #sa_tmp_graph order by [DAY]
--					OPEN @Cur2
--					FETCH NEXT FROM @Cur2 INTO @DAY, @HOUR, @TD_LINK
--					WHILE (@@fetch_status <> -1)
--					BEGIN
--						IF (@@fetch_status <> -2)
--						BEGIN
--							exec dbo.KD_GRAPH_TABLE_SAVE @LINK2, @DAY, @HOUR, @TD_LINK
--						END
					
--						FETCH NEXT FROM @Cur2 INTO @DAY, @HOUR, @TD_LINK
--					END
					
--					CLOSE @Cur2
--					DEALLOCATE @Cur2
--				END
--			END

--			Set @MONTH = @MONTH + 1
--		END
		
--	END
--	FETCH NEXT FROM @Cur1 INTO @LinkGrophik, @VID_LINK, @NAME_GR
--END

--CLOSE @Cur1
--DEALLOCATE @Cur1
--GO

GO
EXEC X_SET_PROP 'BA_DOCUMENTS_MZ_INCOME', 'PRINT_OBJECT_METHOD', 'km_print_f0504207()'
GO
EXEC X_SET_PROP 'BA_DOCUMENTS_MZ_INCOME', 'QUERY_REPORT', 'F0504207.XLT'
GO
EXEC X_SET_PROP 'BA_DOCUMENTS_MZ_INCOME', 'QUERY_REPMAKER', 'KirRepMaker.xls'
GO
EXEC X_SET_PROP 'BA_DOCUMENTS_MZ_INCOME', 'QUERY_ADD_MODULE', 'KirRepCommon.bas'
GO

GO
update EXPORT_MODELS set DATE_END   = '20150331' WHERE MODEL_VER = '2012.02' AND CODE = 'BR'
GO

GO
update EXPORT_MODELS set DATE_END   = '31.03.2015' where MODEL_VER = '2012.02' AND CODE = 'BR'
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = '2015.04' AND CODE = 'BR'
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 'BR','Роспись','2015.04',0,'','XXXXXDNN.TTM','fb_file_name_doc','FB_EXPORT_BR_15','cObjCode','KOD_BP','bb_import_br()',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   = 'FB_EXPORT_BR_15',
		PROC_DOP_PARAM   = 'cObjCode',
		PROG_SAVE   = 'bb_import_br()',
		DEP_NAME   = 'KOD_BP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'KS'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'KS',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'сылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','сылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код бюджетополучателя – отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP'
else		
	INSERT INTO EXPORT_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_BP','Код бюджетополучателя – отправителя','STRING',5,0,0,0,'KOD_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование бюджетополучателя – отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NM_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP'
else		
	INSERT INTO EXPORT_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_BP','Наименование бюджетополучателя – отправителя','STRING',512,0,0,0,'NM_BP','',''
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_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код бюджетополучателя - получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP'
else		
	INSERT INTO EXPORT_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_BP','Код бюджетополучателя - получателя','STRING',5,1,0,0,'KOD_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование бюджетополучателя  - получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NM_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP'
else		
	INSERT INTO EXPORT_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_BP','Наименование бюджетополучателя  - получателя','STRING',512,0,0,0,'NM_BP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'RL'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'RL',4,2,'Общая информация по ЛБО',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 2,
			NAME   = 'Общая информация по ЛБО',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Уникальный идентификатор документа',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'GUID','Уникальный идентификатор документа','GUID',36,1,0,0,'GUID','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PERIOD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Периодичность документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'PERIOD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PERIOD'
else		
	INSERT INTO EXPORT_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,'PERIOD','Периодичность документа','STRING',1,1,1,1,'PERIOD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_RL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Формат документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'TYPE_RL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_RL'
else		
	INSERT INTO EXPORT_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,'TYPE_RL','Формат документа','STRING',1,1,1,1,'TYPE_RL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_RL')
	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_RL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_RL'
else		
	INSERT INTO EXPORT_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_RL','Вид документа','STRING',1,1,1,1,'VID_RL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUMBER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Номер документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NUMBER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUMBER'
else		
	INSERT INTO EXPORT_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,'NUMBER','Номер документа','STRING',15,0,0,0,'NUMBER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Дата',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		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, 6,'DATE','Дата','DATE',NULL,1,1,1,'DATE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_EXEC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Дата введения в действие',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_EXEC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_EXEC'
else		
	INSERT INTO EXPORT_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,'DATE_EXEC','Дата введения в действие','DATE',NULL,1,1,0,'DATE_EXEC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_RBS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Код РБС',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_RBS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_RBS'
else		
	INSERT INTO EXPORT_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,'KOD_RBS','Код РБС','STRING',5,1,0,0,'KOD_RBS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RBS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Наименование РБС',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_RBS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RBS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'NAME_RBS','Наименование РБС','STRING',512,0,0,0,'NAME_RBS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_NUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Номер счета бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'ACC_NUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_NUM'
else		
	INSERT INTO EXPORT_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,'ACC_NUM','Номер счета бюджета','STRING',20,0,0,1,'ACC_NUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_SEND')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Номер счета отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ACC_SEND',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_SEND'
else		
	INSERT INTO EXPORT_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,'ACC_SEND','Номер счета отправителя','STRING',20,0,0,0,'ACC_SEND','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_SEND_KIND')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Вид средств счета отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ACC_SEND_KIND',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_SEND_KIND'
else		
	INSERT INTO EXPORT_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,'ACC_SEND_KIND','Вид средств счета отправителя','STRING',1,1,0,0,'ACC_SEND_KIND','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Код ПБС',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP'
else		
	INSERT INTO EXPORT_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,'KOD_BP','Код ПБС','STRING',5,1,0,0,'KOD_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Наименование ПБС',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'NAME_BP','Наименование ПБС','STRING',512,0,0,0,'NAME_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Номер счета получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ACC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_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,'ACC_RCP','Номер счета получателя','STRING',20,0,0,0,'ACC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP_KIND')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Вид средств счета получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ACC_RCP_KIND',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP_KIND'
else		
	INSERT INTO EXPORT_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,'ACC_RCP_KIND','Вид средств счета получателя','STRING',1,1,0,0,'ACC_RCP_KIND','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'IST')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Источник финансирования',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'IST',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'IST'
else		
	INSERT INTO EXPORT_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,'IST','Источник финансирования','STRING',20,0,0,0,'IST','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR01')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Сумма 1-го года',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_YEAR01',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR01'
else		
	INSERT INTO EXPORT_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,'SUM_YEAR01','Сумма 1-го года','NUMBER2',NULL,0,1,2,'SUM_YEAR01','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR02')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Сумма 2-го года',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_YEAR02',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR02'
else		
	INSERT INTO EXPORT_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,'SUM_YEAR02','Сумма 2-го года','NUMBER2',0,0,1,2,'SUM_YEAR02','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR03')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'Сумма 3-го года',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_YEAR03',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR03'
else		
	INSERT INTO EXPORT_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,'SUM_YEAR03','Сумма 3-го года','NUMBER2',0,0,1,2,'SUM_YEAR03','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Примечание к документу',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PRIM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIM'
else		
	INSERT INTO EXPORT_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,'PRIM','Примечание к документу','STRING',512,0,0,0,'PRIM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_IZM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Вид изменения',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'VID_IZM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_IZM'
else		
	INSERT INTO EXPORT_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,'VID_IZM','Вид изменения','STRING',10,0,0,0,'VID_IZM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Наименование бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BUD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 23,'NAME_BUD','Наименование бюджета','STRING',512,0,0,0,'NAME_BUD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOP_UKAZ')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Дополнительные указания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOP_UKAZ',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOP_UKAZ'
else		
	INSERT INTO EXPORT_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,'DOP_UKAZ','Дополнительные указания','STRING',512,0,0,0,'DOP_UKAZ','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_SIGN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Дата подписания руководителем',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_SIGN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_SIGN'
else		
	INSERT INTO EXPORT_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,'DATE_SIGN','Дата подписания руководителем','DATE',0,0,0,0,'DATE_SIGN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BOSS_DOL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'Должность руководителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BOSS_DOL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BOSS_DOL'
else		
	INSERT INTO EXPORT_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,'BOSS_DOL','Должность руководителя','STRING',100,0,0,0,'BOSS_DOL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BOSS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'ФИО руководителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BOSS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BOSS'
else		
	INSERT INTO EXPORT_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,'BOSS','ФИО руководителя','STRING',50,0,0,0,'BOSS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_DOL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Должность исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ISP_DOL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_DOL'
else		
	INSERT INTO EXPORT_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,'ISP_DOL','Должность исполнителя','STRING',100,0,0,0,'ISP_DOL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_FIO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 29,
		NAME   		= 'ФИО исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ISP_FIO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_FIO'
else		
	INSERT INTO EXPORT_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,'ISP_FIO','ФИО исполнителя','STRING',50,0,0,0,'ISP_FIO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_PHONE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 30,
		NAME   		= 'Телефон исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ISP_PHONE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_PHONE'
else		
	INSERT INTO EXPORT_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,'ISP_PHONE','Телефон исполнителя','STRING',20,0,0,0,'ISP_PHONE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CORRECTION')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 31,
		NAME   		= 'Номер уточнения',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'CORRECTION',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CORRECTION'
else		
	INSERT INTO EXPORT_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,'CORRECTION','Номер уточнения','NUMBER',2,0,0,0,'CORRECTION','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ANALITICS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'Аналитические признаки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ANALITICS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ANALITICS'
else		
	INSERT INTO EXPORT_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,'ANALITICS','Аналитические признаки','STRING',250,0,0,0,'ANALITICS','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'RLO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'RLO',5,2,'Основания документа',0
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Основания документа',
			OBLIGATORY = 0
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_OSNOV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер основания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 30,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_OSNOV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_OSNOV'
else		
	INSERT INTO EXPORT_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_OSNOV','Номер основания','STRING',30,0,1,1,'NOM_OSNOV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_OSNOV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Дата основания',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_OSNOV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_OSNOV'
else		
	INSERT INTO EXPORT_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_OSNOV','Дата основания','DATE',0,0,0,1,'DATE_OSNOV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OSNOV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Наименование документа-основания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'OSNOV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OSNOV'
else		
	INSERT INTO EXPORT_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,'OSNOV','Наименование документа-основания','STRING',254,0,0,1,'OSNOV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Примечание',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PRIM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIM'
else		
	INSERT INTO EXPORT_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,'PRIM','Примечание','STRING',254,0,0,0,'PRIM','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'RLST'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'RLST',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 = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'TYPE_KBK','Тип КБК','STRING',2,1,1,1,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KBK','КБК','STRING',20,1,1,1,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK_IST_RF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код источника резервного фонда',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK_IST_RF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK_IST_RF'
else		
	INSERT INTO EXPORT_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,'KBK_IST_RF','Код источника резервного фонда','STRING',10,0,0,0,'KBK_IST_RF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	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',
		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, 4,'ADD_KLASS','Доп. классификация','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LOCAL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Региональная БК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LOCAL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LOCAL'
else		
	INSERT INTO EXPORT_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,'LOCAL','Региональная БК','STRING',20,0,0,0,'LOCAL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SERVICE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Работы, услуги',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SERVICE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SERVICE'
else		
	INSERT INTO EXPORT_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,'SERVICE','Работы, услуги','STRING',20,0,0,0,'SERVICE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Стратегические цели и задачи',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'PURPOSE','Стратегические цели и задачи','STRING',20,0,0,0,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PROGRAM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Программы и непрограммная деятельность',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PROGRAM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PROGRAM'
else		
	INSERT INTO EXPORT_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,'PROGRAM','Программы и непрограммная деятельность','STRING',20,0,0,0,'PROGRAM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM1')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Сумма за январь',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM1',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM1'
else		
	INSERT INTO EXPORT_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,'SUM1','Сумма за январь','NUMBER2',NULL,1,0,0,'SUM1','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM2')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Сумма за февраль',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM2',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM2'
else		
	INSERT INTO EXPORT_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,'SUM2','Сумма за февраль','NUMBER2',NULL,1,0,0,'SUM2','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM3')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Сумма за март',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM3',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM3'
else		
	INSERT INTO EXPORT_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,'SUM3','Сумма за март','NUMBER2',NULL,1,0,0,'SUM3','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM4')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Сумма за апрель',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM4',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM4'
else		
	INSERT INTO EXPORT_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,'SUM4','Сумма за апрель','NUMBER2',NULL,1,0,0,'SUM4','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM5')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Сумма за май',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM5',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM5'
else		
	INSERT INTO EXPORT_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,'SUM5','Сумма за май','NUMBER2',NULL,1,0,0,'SUM5','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM6')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Сумма за июнь',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM6',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM6'
else		
	INSERT INTO EXPORT_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,'SUM6','Сумма за июнь','NUMBER2',NULL,1,0,0,'SUM6','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM7')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Сумма за июль',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM7',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM7'
else		
	INSERT INTO EXPORT_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,'SUM7','Сумма за июль','NUMBER2',NULL,1,0,0,'SUM7','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM8')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'Сумма за август',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM8',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM8'
else		
	INSERT INTO EXPORT_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,'SUM8','Сумма за август','NUMBER2',NULL,1,0,0,'SUM8','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM9')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Сумма за сентябрь',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM9',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM9'
else		
	INSERT INTO EXPORT_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,'SUM9','Сумма за сентябрь','NUMBER2',NULL,1,0,0,'SUM9','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM10')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Сумма за октябрь',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM10',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM10'
else		
	INSERT INTO EXPORT_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,'SUM10','Сумма за октябрь','NUMBER2',NULL,1,0,0,'SUM10','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM11')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Сумма за ноябрь',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM11',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM11'
else		
	INSERT INTO EXPORT_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,'SUM11','Сумма за ноябрь','NUMBER2',NULL,1,0,0,'SUM11','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM12')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Сумма за декабрь',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM12',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM12'
else		
	INSERT INTO EXPORT_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,'SUM12','Сумма за декабрь','NUMBER2',NULL,1,0,0,'SUM12','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR01')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Сумма на первый год',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_YEAR01',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR01'
else		
	INSERT INTO EXPORT_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,'SUM_YEAR01','Сумма на первый год','NUMBER2',0,1,0,0,'SUM_YEAR01','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR02')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'Сумма на второй год',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_YEAR02',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR02'
else		
	INSERT INTO EXPORT_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,'SUM_YEAR02','Сумма на второй год','NUMBER2',NULL,1,0,0,'SUM_YEAR02','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR03')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'Сумма на третий год',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_YEAR03',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR03'
else		
	INSERT INTO EXPORT_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,'SUM_YEAR03','Сумма на третий год','NUMBER2',NULL,1,0,0,'SUM_YEAR03','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Код УБП получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP'
else		
	INSERT INTO EXPORT_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,'KOD_BP','Код УБП получателя','STRING',5,1,1,1,'KOD_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 29,
		NAME   		= 'Наименование получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP'
else		
	INSERT INTO EXPORT_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,'NAME_BP','Наименование получателя','STRING',512,0,1,1,'NAME_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 30,
		NAME   		= 'Номер счета получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'ACC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_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, 30,'ACC_RCP','Номер счета получателя','STRING',20,0,1,1,'ACC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP_KIND')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 31,
		NAME   		= 'Вид средств счета получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ACC_RCP_KIND',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP_KIND'
else		
	INSERT INTO EXPORT_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,'ACC_RCP_KIND','Вид средств счета получателя','STRING',1,1,0,0,'ACC_RCP_KIND','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SRO_CODE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'Код Расходного полномочия',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SRO_CODE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SRO_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, 32,'SRO_CODE','Код Расходного полномочия','STRING',100,0,0,0,'SRO_CODE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SRO_NAME')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 33,
		NAME   		= 'Наименование Расходного полномочия',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 6000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SRO_NAME',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SRO_NAME'
else		
	INSERT INTO EXPORT_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,'SRO_NAME','Наименование Расходного полномочия','STRING',6000,0,0,0,'SRO_NAME','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'STR_TYPE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 34,
		NAME   		= 'Тип строки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'STR_TYPE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'STR_TYPE'
else		
	INSERT INTO EXPORT_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,'STR_TYPE','Тип строки','STRING',2,1,0,0,'STR_TYPE','',''
GO

GO
update EXPORT_MODELS set DATE_END   = '20150331' WHERE MODEL_VER = '2008.08' AND CODE = 'LB'
GO

GO
update EXPORT_MODELS set DATE_END   = '20150331' WHERE MODEL_VER = '2012.02' AND CODE = 'LB'
GO

GO
update EXPORT_MODELS set DATE_END   = '31.03.2015' where MODEL_VER = '2012.02' AND CODE = 'LB'
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = '2015.04' AND CODE = 'LB'
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 'LB','Лимиты бюджетных обязательств','2015.04',0,'','XXXXXDNN.TTM','fb_file_name_doc','FB_EXPORT_BR_15','cObjCode','KOD_BP','bb_import_br()',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   = 'FB_EXPORT_BR_15',
		PROC_DOP_PARAM   = 'cObjCode',
		PROG_SAVE   = 'bb_import_br()',
		DEP_NAME   = 'KOD_BP',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'KS'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'KS',1,0,'Маркер',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 1,
			ISONCE = 0,
			NAME   = 'Маркер',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер версии формата',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NUM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'NUM_VER','Номер версии формата','STRING',10,0,1,1,'NUM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование программного продукта, сформировавшего файл',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORMER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORMER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'FORMER','Наименование программного продукта, сформировавшего файл','STRING',50,0,0,1,'FORMER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Версия программного продукта',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'FORM_VER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'FORM_VER'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 3,'FORM_VER','Версия программного продукта','STRING',10,0,0,1,'FORM_VER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'сылка на документ, утверждающий формат файла',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NORM_DOC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NORM_DOC'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 4,'NORM_DOC','сылка на документ, утверждающий формат файла','STRING',250,0,0,0,'NORM_DOC','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'FROM'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'FROM',2,0,'Почтовая информация об отправителях файла',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Почтовая информация об отправителях файла',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код бюджетополучателя – отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP'
else		
	INSERT INTO EXPORT_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_BP','Код бюджетополучателя – отправителя','STRING',5,0,0,0,'KOD_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование бюджетополучателя – отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NM_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP'
else		
	INSERT INTO EXPORT_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_BP','Наименование бюджетополучателя – отправителя','STRING',512,0,0,0,'NM_BP','',''
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_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код бюджетополучателя - получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP'
else		
	INSERT INTO EXPORT_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_BP','Код бюджетополучателя - получателя','STRING',5,1,0,0,'KOD_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Наименование бюджетополучателя  - получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NM_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP'
else		
	INSERT INTO EXPORT_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_BP','Наименование бюджетополучателя  - получателя','STRING',512,0,0,0,'NM_BP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'RL'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'RL',4,2,'Общая информация по ЛБО',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 2,
			NAME   = 'Общая информация по ЛБО',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Уникальный идентификатор документа',
		VAL_TYPE 	= 'GUID',
		VAL_LEN 	= 36,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'GUID',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'GUID'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'GUID','Уникальный идентификатор документа','GUID',36,1,0,0,'GUID','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PERIOD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Периодичность документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'PERIOD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PERIOD'
else		
	INSERT INTO EXPORT_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,'PERIOD','Периодичность документа','STRING',1,1,1,1,'PERIOD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_RL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Формат документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'TYPE_RL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_RL'
else		
	INSERT INTO EXPORT_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,'TYPE_RL','Формат документа','STRING',1,1,1,1,'TYPE_RL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_RL')
	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_RL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_RL'
else		
	INSERT INTO EXPORT_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_RL','Вид документа','STRING',1,1,1,1,'VID_RL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NUMBER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Номер документа',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 15,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NUMBER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NUMBER'
else		
	INSERT INTO EXPORT_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,'NUMBER','Номер документа','STRING',15,0,0,0,'NUMBER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Дата',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		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, 6,'DATE','Дата','DATE',NULL,1,1,1,'DATE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_EXEC')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Дата введения в действие',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_EXEC',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_EXEC'
else		
	INSERT INTO EXPORT_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,'DATE_EXEC','Дата введения в действие','DATE',NULL,1,1,0,'DATE_EXEC','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_RBS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Код РБС',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_RBS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_RBS'
else		
	INSERT INTO EXPORT_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,'KOD_RBS','Код РБС','STRING',5,1,0,0,'KOD_RBS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RBS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Наименование РБС',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_RBS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_RBS'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 9,'NAME_RBS','Наименование РБС','STRING',512,0,0,0,'NAME_RBS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_NUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Номер счета бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'ACC_NUM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_NUM'
else		
	INSERT INTO EXPORT_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,'ACC_NUM','Номер счета бюджета','STRING',20,0,0,1,'ACC_NUM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_SEND')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Номер счета отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ACC_SEND',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_SEND'
else		
	INSERT INTO EXPORT_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,'ACC_SEND','Номер счета отправителя','STRING',20,0,0,0,'ACC_SEND','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_SEND_KIND')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'Вид средств счета отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ACC_SEND_KIND',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_SEND_KIND'
else		
	INSERT INTO EXPORT_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,'ACC_SEND_KIND','Вид средств счета отправителя','STRING',1,1,0,0,'ACC_SEND_KIND','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Код ПБС',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP'
else		
	INSERT INTO EXPORT_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,'KOD_BP','Код ПБС','STRING',5,1,0,0,'KOD_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Наименование ПБС',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'NAME_BP','Наименование ПБС','STRING',512,0,0,0,'NAME_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Номер счета получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ACC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_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,'ACC_RCP','Номер счета получателя','STRING',20,0,0,0,'ACC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP_KIND')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Вид средств счета получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ACC_RCP_KIND',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP_KIND'
else		
	INSERT INTO EXPORT_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,'ACC_RCP_KIND','Вид средств счета получателя','STRING',1,1,0,0,'ACC_RCP_KIND','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'IST')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Источник финансирования',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'IST',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'IST'
else		
	INSERT INTO EXPORT_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,'IST','Источник финансирования','STRING',20,0,0,0,'IST','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR01')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Сумма 1-го года',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_YEAR01',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR01'
else		
	INSERT INTO EXPORT_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,'SUM_YEAR01','Сумма 1-го года','NUMBER2',NULL,0,1,2,'SUM_YEAR01','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR02')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Сумма 2-го года',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_YEAR02',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR02'
else		
	INSERT INTO EXPORT_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,'SUM_YEAR02','Сумма 2-го года','NUMBER2',0,0,1,2,'SUM_YEAR02','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR03')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'Сумма 3-го года',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 2,
		ALIAS_CODE	= 'SUM_YEAR03',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR03'
else		
	INSERT INTO EXPORT_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,'SUM_YEAR03','Сумма 3-го года','NUMBER2',0,0,1,2,'SUM_YEAR03','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Примечание к документу',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PRIM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIM'
else		
	INSERT INTO EXPORT_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,'PRIM','Примечание к документу','STRING',512,0,0,0,'PRIM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_IZM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Вид изменения',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'VID_IZM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID_IZM'
else		
	INSERT INTO EXPORT_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,'VID_IZM','Вид изменения','STRING',10,0,0,0,'VID_IZM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Наименование бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'NAME_BUD',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BUD'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 23,'NAME_BUD','Наименование бюджета','STRING',512,0,0,0,'NAME_BUD','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DOP_UKAZ')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Дополнительные указания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DOP_UKAZ',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DOP_UKAZ'
else		
	INSERT INTO EXPORT_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,'DOP_UKAZ','Дополнительные указания','STRING',512,0,0,0,'DOP_UKAZ','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_SIGN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Дата подписания руководителем',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_SIGN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_SIGN'
else		
	INSERT INTO EXPORT_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,'DATE_SIGN','Дата подписания руководителем','DATE',0,0,0,0,'DATE_SIGN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BOSS_DOL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'Должность руководителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BOSS_DOL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BOSS_DOL'
else		
	INSERT INTO EXPORT_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,'BOSS_DOL','Должность руководителя','STRING',100,0,0,0,'BOSS_DOL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BOSS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'ФИО руководителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BOSS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BOSS'
else		
	INSERT INTO EXPORT_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,'BOSS','ФИО руководителя','STRING',50,0,0,0,'BOSS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_DOL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Должность исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ISP_DOL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_DOL'
else		
	INSERT INTO EXPORT_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,'ISP_DOL','Должность исполнителя','STRING',100,0,0,0,'ISP_DOL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_FIO')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 29,
		NAME   		= 'ФИО исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 50,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ISP_FIO',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_FIO'
else		
	INSERT INTO EXPORT_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,'ISP_FIO','ФИО исполнителя','STRING',50,0,0,0,'ISP_FIO','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_PHONE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 30,
		NAME   		= 'Телефон исполнителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ISP_PHONE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ISP_PHONE'
else		
	INSERT INTO EXPORT_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,'ISP_PHONE','Телефон исполнителя','STRING',20,0,0,0,'ISP_PHONE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CORRECTION')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 31,
		NAME   		= 'Номер уточнения',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'CORRECTION',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CORRECTION'
else		
	INSERT INTO EXPORT_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,'CORRECTION','Номер уточнения','NUMBER',2,0,0,0,'CORRECTION','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ANALITICS')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'Аналитические признаки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 250,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ANALITICS',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ANALITICS'
else		
	INSERT INTO EXPORT_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,'ANALITICS','Аналитические признаки','STRING',250,0,0,0,'ANALITICS','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'RLO'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'RLO',5,2,'Основания документа',0
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 5,
			ISONCE = 2,
			NAME   = 'Основания документа',
			OBLIGATORY = 0
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_OSNOV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Номер основания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 30,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NOM_OSNOV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NOM_OSNOV'
else		
	INSERT INTO EXPORT_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_OSNOV','Номер основания','STRING',30,0,1,1,'NOM_OSNOV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_OSNOV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Дата основания',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'DATE_OSNOV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_OSNOV'
else		
	INSERT INTO EXPORT_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_OSNOV','Дата основания','DATE',0,0,0,1,'DATE_OSNOV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'OSNOV')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Наименование документа-основания',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'OSNOV',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'OSNOV'
else		
	INSERT INTO EXPORT_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,'OSNOV','Наименование документа-основания','STRING',254,0,0,1,'OSNOV','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Примечание',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PRIM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PRIM'
else		
	INSERT INTO EXPORT_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,'PRIM','Примечание','STRING',254,0,0,0,'PRIM','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'RLST'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'RLST',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 = 'TYPE_KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Тип КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'TYPE_KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'TYPE_KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 1,'TYPE_KBK','Тип КБК','STRING',2,1,1,1,'TYPE_KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'КБК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KBK',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 2,'KBK','КБК','STRING',20,1,1,1,'KBK','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK_IST_RF')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Код источника резервного фонда',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KBK_IST_RF',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KBK_IST_RF'
else		
	INSERT INTO EXPORT_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,'KBK_IST_RF','Код источника резервного фонда','STRING',10,0,0,0,'KBK_IST_RF','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ADD_KLASS')
	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',
		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, 4,'ADD_KLASS','Доп. классификация','STRING',20,0,0,0,'ADD_KLASS','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LOCAL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Региональная БК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LOCAL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'LOCAL'
else		
	INSERT INTO EXPORT_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,'LOCAL','Региональная БК','STRING',20,0,0,0,'LOCAL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SERVICE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Работы, услуги',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SERVICE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SERVICE'
else		
	INSERT INTO EXPORT_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,'SERVICE','Работы, услуги','STRING',20,0,0,0,'SERVICE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Стратегические цели и задачи',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PURPOSE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PURPOSE'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 7,'PURPOSE','Стратегические цели и задачи','STRING',20,0,0,0,'PURPOSE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PROGRAM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Программы и непрограммная деятельность',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PROGRAM',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PROGRAM'
else		
	INSERT INTO EXPORT_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,'PROGRAM','Программы и непрограммная деятельность','STRING',20,0,0,0,'PROGRAM','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM1')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'Сумма за январь',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM1',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM1'
else		
	INSERT INTO EXPORT_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,'SUM1','Сумма за январь','NUMBER2',NULL,1,0,0,'SUM1','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM2')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'Сумма за февраль',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM2',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM2'
else		
	INSERT INTO EXPORT_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,'SUM2','Сумма за февраль','NUMBER2',NULL,1,0,0,'SUM2','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM3')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'Сумма за март',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM3',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM3'
else		
	INSERT INTO EXPORT_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,'SUM3','Сумма за март','NUMBER2',NULL,1,0,0,'SUM3','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM4')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 16,
		NAME   		= 'Сумма за апрель',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM4',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM4'
else		
	INSERT INTO EXPORT_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,'SUM4','Сумма за апрель','NUMBER2',NULL,1,0,0,'SUM4','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM5')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 17,
		NAME   		= 'Сумма за май',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM5',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM5'
else		
	INSERT INTO EXPORT_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,'SUM5','Сумма за май','NUMBER2',NULL,1,0,0,'SUM5','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM6')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 18,
		NAME   		= 'Сумма за июнь',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM6',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM6'
else		
	INSERT INTO EXPORT_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,'SUM6','Сумма за июнь','NUMBER2',NULL,1,0,0,'SUM6','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM7')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 19,
		NAME   		= 'Сумма за июль',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM7',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM7'
else		
	INSERT INTO EXPORT_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,'SUM7','Сумма за июль','NUMBER2',NULL,1,0,0,'SUM7','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM8')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 20,
		NAME   		= 'Сумма за август',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM8',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM8'
else		
	INSERT INTO EXPORT_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,'SUM8','Сумма за август','NUMBER2',NULL,1,0,0,'SUM8','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM9')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 21,
		NAME   		= 'Сумма за сентябрь',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM9',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM9'
else		
	INSERT INTO EXPORT_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,'SUM9','Сумма за сентябрь','NUMBER2',NULL,1,0,0,'SUM9','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM10')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 22,
		NAME   		= 'Сумма за октябрь',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM10',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM10'
else		
	INSERT INTO EXPORT_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,'SUM10','Сумма за октябрь','NUMBER2',NULL,1,0,0,'SUM10','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM11')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 23,
		NAME   		= 'Сумма за ноябрь',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM11',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM11'
else		
	INSERT INTO EXPORT_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,'SUM11','Сумма за ноябрь','NUMBER2',NULL,1,0,0,'SUM11','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM12')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 24,
		NAME   		= 'Сумма за декабрь',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM12',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM12'
else		
	INSERT INTO EXPORT_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,'SUM12','Сумма за декабрь','NUMBER2',NULL,1,0,0,'SUM12','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR01')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 25,
		NAME   		= 'Сумма на первый год',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= 0,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_YEAR01',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR01'
else		
	INSERT INTO EXPORT_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,'SUM_YEAR01','Сумма на первый год','NUMBER2',0,1,0,0,'SUM_YEAR01','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR02')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 26,
		NAME   		= 'Сумма на второй год',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_YEAR02',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR02'
else		
	INSERT INTO EXPORT_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,'SUM_YEAR02','Сумма на второй год','NUMBER2',NULL,1,0,0,'SUM_YEAR02','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR03')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 27,
		NAME   		= 'Сумма на третий год',
		VAL_TYPE 	= 'NUMBER2',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SUM_YEAR03',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM_YEAR03'
else		
	INSERT INTO EXPORT_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,'SUM_YEAR03','Сумма на третий год','NUMBER2',NULL,1,0,0,'SUM_YEAR03','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 28,
		NAME   		= 'Код УБП получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 5,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'KOD_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_BP'
else		
	INSERT INTO EXPORT_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,'KOD_BP','Код УБП получателя','STRING',5,1,1,1,'KOD_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 29,
		NAME   		= 'Наименование получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 512,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME_BP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME_BP'
else		
	INSERT INTO EXPORT_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,'NAME_BP','Наименование получателя','STRING',512,0,1,1,'NAME_BP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 30,
		NAME   		= 'Номер счета получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 1,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'ACC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_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, 30,'ACC_RCP','Номер счета получателя','STRING',20,0,1,1,'ACC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP_KIND')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 31,
		NAME   		= 'Вид средств счета получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ACC_RCP_KIND',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ACC_RCP_KIND'
else		
	INSERT INTO EXPORT_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,'ACC_RCP_KIND','Вид средств счета получателя','STRING',1,1,0,0,'ACC_RCP_KIND','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SRO_CODE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 32,
		NAME   		= 'Код Расходного полномочия',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 100,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SRO_CODE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SRO_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, 32,'SRO_CODE','Код Расходного полномочия','STRING',100,0,0,0,'SRO_CODE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SRO_NAME')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 33,
		NAME   		= 'Наименование Расходного полномочия',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 6000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'SRO_NAME',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SRO_NAME'
else		
	INSERT INTO EXPORT_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,'SRO_NAME','Наименование Расходного полномочия','STRING',6000,0,0,0,'SRO_NAME','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'STR_TYPE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 34,
		NAME   		= 'Тип строки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'STR_TYPE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'STR_TYPE'
else		
	INSERT INTO EXPORT_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,'STR_TYPE','Тип строки','STRING',2,1,0,0,'STR_TYPE','',''
GO

GO
DECLARE @varKSModelLink INT,
	@varKSBlockLink INT
SELECT @varKSModelLink = LINK_MODEL FROM dbo.EXPORT_MODELS WHERE MODEL_VER = '2013.03' AND CODE = 'SPR'
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 'SPR','Справочники','2013.03',0,'','','fb_file_name_spr','BB_EXPORT_SPR','cObjCode','','fb_save_spr()',NULL 
	SET @varKSModelLink = @@IDENTITY
end
else
	update EXPORT_MODELS
	set 	ISONCE = 0,
		NAME   = 'Справочники',
		NORM_DOC   = '',
		FILE_NAME_MASK   = '',
		FILE_NAME_PROC   = 'fb_file_name_spr',
		PROC_EXP   = 'BB_EXPORT_SPR',
		PROC_DOP_PARAM   = 'cObjCode',
		PROG_SAVE   = 'fb_save_spr()',
		DEP_NAME   = '',
		DATE_END   = NULL
	where LINK_MODEL = @varKSModelLink
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'KS'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'KS',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	= 0,
		OBLIGATORY	= 0,
		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,0,0,'NUM_VER','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TYPE'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TYPE',2,0,'Тип справочника',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 2,
			ISONCE = 0,
			NAME   = 'Тип справочника',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_SPR')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код справочника',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 25,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'KOD_SPR',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'KOD_SPR'
else		
	INSERT INTO EXPORT_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_SPR','Код справочника','STRING',25,0,0,0,'KOD_SPR','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'BK'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'BK',3,2,'Строки справочника',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 3,
			ISONCE = 2,
			NAME   = 'Строки справочника',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CODE')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Код строки',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'CODE',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = '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, 1,'CODE','Код строки','STRING',20,0,0,1,'CODE','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SNAME')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 2,
		NAME   		= 'Краткое наименование',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'SNAME',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'SNAME'
else		
	INSERT INTO EXPORT_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,'SNAME','Краткое наименование','STRING',254,0,0,1,'SNAME','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 3,
		NAME   		= 'Наименование',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 2000,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 1,
		ALIAS_CODE	= 'NAME',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'NAME'
else		
	INSERT INTO EXPORT_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','Наименование','STRING',2000,0,0,1,'NAME','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_BEGIN')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 4,
		NAME   		= 'Дата напчала',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_BEGIN',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_BEGIN'
else		
	INSERT INTO EXPORT_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,'DATE_BEGIN','Дата напчала','DATE',NULL,0,0,0,'DATE_BEGIN','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_END')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 5,
		NAME   		= 'Дата анулирования',
		VAL_TYPE 	= 'DATE',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'DATE_END',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'DATE_END'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 5,'DATE_END','Дата анулирования','DATE',NULL,0,0,0,'DATE_END','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'LEVEL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 6,
		NAME   		= 'Уровень',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'LEVEL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = '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, 6,'LEVEL','Уровень','NUMBER',10,0,0,0,'LEVEL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDGET')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 7,
		NAME   		= 'Наименование бюджета',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 254,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'BUDGET',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'BUDGET'
else		
	INSERT INTO EXPORT_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,'BUDGET','Наименование бюджета','STRING',254,0,0,0,'BUDGET','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 8,
		NAME   		= 'Порядок',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= 10,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'ORDER',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'ORDER'
else		
	INSERT INTO EXPORT_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,'ORDER','Порядок','NUMBER',10,0,0,0,'ORDER','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PARENT')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 9,
		NAME   		= 'Вышестоящий код',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PARENT',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PARENT'
else		
	INSERT INTO EXPORT_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,'PARENT','Вышестоящий код','STRING',20,0,0,0,'PARENT','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'VID')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 10,
		NAME   		= 'Вид обеспечения',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 3,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'VID',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'VID'
else		
	INSERT INTO EXPORT_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,'VID','Вид обеспечения','STRING',3,0,0,0,'VID','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'CONTROL')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 11,
		NAME   		= 'Контроль ОрФК',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 1,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'CONTROL',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'CONTROL'
else		
	INSERT INTO EXPORT_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,'CONTROL','Контроль ОрФК','STRING',1,1,0,0,'CONTROL','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYCINCOME')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 12,
		NAME   		= 'КБК доходов',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'PAYCINCOME',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'PAYCINCOME'
else		
	INSERT INTO EXPORT_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,'PAYCINCOME','КБК доходов','STRING',20,1,0,0,'PAYCINCOME','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'INC_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 13,
		NAME   		= 'КБК доходов получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 1,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'INC_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'INC_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, 13,'INC_RCP','КБК доходов получателя','STRING',20,1,0,0,'INC_RCP','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'EXP_PAY')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 14,
		NAME   		= 'КБК расходов отправителя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'EXP_PAY',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'EXP_PAY'
else		
	INSERT INTO EXPORT_FIELDS (LINK_BLOCK, ORDERS, CODE, NAME, VAL_TYPE, VAL_LEN, VAL_LEN_EQ, NEED_CHECK, OBLIGATORY, ALIAS_CODE, CHECK_PROC, VAL_LIST)
	SELECT @varKSBlockLink, 14,'EXP_PAY','КБК расходов отправителя','STRING',20,0,0,0,'EXP_PAY','',''
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'EXP_RCP')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 15,
		NAME   		= 'КБК расходов получателя',
		VAL_TYPE 	= 'STRING',
		VAL_LEN 	= 20,
		VAL_LEN_EQ	= 0,
		NEED_CHECK	= 0,
		OBLIGATORY	= 0,
		ALIAS_CODE	= 'EXP_RCP',
		CHECK_PROC	= '',
		VAL_LIST	= ''
	where LINK_BLOCK = @varKSBlockLink and CODE = 'EXP_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,'EXP_RCP','КБК расходов получателя','STRING',20,0,0,0,'EXP_RCP','',''
set @varKSBlockLink = NULL
select 	@varKSBlockLink = LINK_BLOCK from dbo.EXPORT_BLOCKS where LINK_MODEL = @varKSModelLink and CODE = 'TOTAL'
if @varKSBlockLink is null
begin
	INSERT INTO EXPORT_BLOCKS(LINK_MODEL,CODE, ORDERS, ISONCE, NAME, OBLIGATORY)
	SELECT @varKSModelLink,'TOTAL',4,0,'Контроль',1
	SET @varKSBlockLink = @@IDENTITY
end
else
	update EXPORT_BLOCKS
	set 	ORDERS = 4,
			ISONCE = 0,
			NAME   = 'Контроль',
			OBLIGATORY = 1
	where LINK_BLOCK = @varKSBlockLink
if exists(select * from EXPORT_FIELDS where LINK_BLOCK = @varKSBlockLink and CODE = 'SUM')
	UPDATE EXPORT_FIELDS
	SET 	ORDERS 		= 1,
		NAME   		= 'Количество строк',
		VAL_TYPE 	= 'NUMBER',
		VAL_LEN 	= NULL,
		VAL_LEN_EQ	= 0,
		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, 1,'SUM','Количество строк','NUMBER',NULL,0,1,1,'SUM','',''
GO

GO

IF EXISTS(SELECT * FROM S_OBJECTS WHERE CODE = 'BB_UVED_817_69N_NASTR_OKATO')
BEGIN 
	DECLARE @a int, @b INT , @c int 
	 SET @a =	(SELECT link FROM s_objects WHERE code= 'BB_UVED_817_69N_NASTR_OKATO')
	 SET @b =	(SELECT link FROM s_objects WHERE code= 'BB_UVED_817_69N_NASTR_REST')
	 SET @c =	(SELECT link FROM s_objects WHERE code= 'BB_UVED_817_69N_NASTR')

	exec w_eso_DeleteObject  @a

	declare @p2 varchar(8000)  
	set @p2='BB_UVED_817_69N_NASTR_REST    '
	exec X_GET_OBJ_CODE @b,@p2 output
	select @p2

	exec w_eso_EnumObjects     @c
END 
GO
GO
---  изменение наименования 104 строки в ЗКР
EXEC X_SET_PROP 'BB_ZAYAVKA_KR_DOHOD_NAME', 'TITLE', '104. Код по КБК'
GO

EXEC X_SET_PROP 'BB_ZAYAVKA_KR_DOHOD_CODE', 'TYPE_FIELD_DICT', 'Char(30)'
GO

EXEC X_SET_PROP 'BB_ZAYAVKA_KR_DOHOD_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("BI_DICTION_KBK", oForm.ALIAS, "LINK,CODE,NAME", "DOH_LINK,DOH_CODE,DOH_NAME", "", "", "", .T., 1, oForm, oObj)
'
GO

GO

EXEC X_SET_PROP 'BI_DICTION_CSR_CODE', 'TYPE_FIELD_DICT', 'char(10)'
GO

GO

EXEC X_SET_PROP 'BI_DICTION_KBK', 'TYPE_COLUMN_LENGTH', '30'
GO

EXEC X_SET_PROP 'BI_DICTION_EXP_CODE_1', 'TYPE_FIELD_DICT', 'char(30)'
GO

EXEC X_SET_PROP 'COL_DICTION_IVNESHF_SGU_1_1_1', 'TYPE_FIELD_DICT', 'char(10)'
GO

/****** Объект: Ссылка на ОСГУ******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COL_DICTION_OSGU_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 = 'COL_DICTION_OSGU_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 = 'COL_DICTION_OSGU_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 = 'COL_DICTION_OSGU_LINK')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COL_DICTION_OSGU_LINK'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COL_DICTION_OSGU_LINK')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COL_DICTION_OSGU_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COL_DICTION_OSGU_LINK', 'Ссылка на ОСГУ', 26, (SELECT LINK FROM S_OBJECTS WHERE CODE='BI_DICTION_KBK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COL_DICTION_OSGU_LINK', NAME = 'Ссылка на ОСГУ', ORDERS = '26', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BI_DICTION_KBK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COL_DICTION_OSGU_LINK'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_LINK', 'CONTROLSOURCE', 'm.cAlias + ".SGU_LINK"'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_LINK', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_LINK', 'REFERENCE_TO_DICT', 'KOSGU'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_LINK', 'SHORT_CODE_OBJ', 'SGU_LINK'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SGU_LINK"'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_LINK', 'FIELD_DATA', 'SGU_LINK'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_LINK', 'FIELD_KEY', 'SGU_LINK'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'COL_DICTION_OSGU_LINK', 'Кадры-КС (чтение)', 5,26
GO
EXEC DBO.W_SPERM_WRITE 'COL_DICTION_OSGU_LINK', 'Главный бухгалтер', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'COL_DICTION_OSGU_LINK', 'Смета-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'COL_DICTION_OSGU_LINK', 'Свод-КС', 5,0
GO
EXEC DBO.W_SPERM_WRITE 'COL_DICTION_OSGU_LINK', 'Зарплата-КС', 5,0
GO
EXEC DBO.W_SPERM_WRITE 'COL_DICTION_OSGU_LINK', 'Кадры-КС', 4,0
GO
EXEC DBO.W_SPERM_WRITE 'COL_DICTION_OSGU_LINK', 'public', 4,0
GO


/****** Объект: ОСГУ******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COL_DICTION_OSGU')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'COL_DICTION_OSGU')
	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 = 'COL_DICTION_OSGU')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'COL_DICTION_OSGU')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COL_DICTION_OSGU'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COL_DICTION_OSGU')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COL_DICTION_OSGU')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COL_DICTION_OSGU', 'ОСГУ', 27, (SELECT LINK FROM S_OBJECTS WHERE CODE='BI_DICTION_KBK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COL_DICTION_OSGU', NAME = 'ОСГУ', ORDERS = '27', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BI_DICTION_KBK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COL_DICTION_OSGU'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU', 'TITLE', 'Код ОСГУ'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_KOSGU",oForm.ALIAS, "LINK, CODE, NAME", "SGU_LINK,SGU_CODE,SGU_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU', 'CONTROLSOURCE', 'm.cAlias+".SGU_CODE"'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU', 'STORAGE', 'KOSGU'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU', 'TYPE_FIELD_DICT', 'char(3)'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU', 'SHORT_CODE_OBJ', 'SGU_CODE'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU', 'CONTROLSOURCE_EDIT', 'm.cAlias+".SGU_CODE"'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU', 'CONTROL_NAME_EDIT', 'ASel_Spr8'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU', 'REFERENCE_TO_FIELD', 'SGU_CODE'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU', 'FIELD_DATA', 'SGU_CODE'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU', 'FIELD_KEY', 'SGU_CODE'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/



/****** Объект: Наименование ОСГУ******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COL_DICTION_OSGU_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 = 'COL_DICTION_OSGU_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 = 'COL_DICTION_OSGU_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 = 'COL_DICTION_OSGU_NAME')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COL_DICTION_OSGU_NAME'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COL_DICTION_OSGU_NAME')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COL_DICTION_OSGU_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COL_DICTION_OSGU_NAME', 'Наименование ОСГУ', 28, (SELECT LINK FROM S_OBJECTS WHERE CODE='BI_DICTION_KBK'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COL_DICTION_OSGU_NAME', NAME = 'Наименование ОСГУ', ORDERS = '28', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BI_DICTION_KBK'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COL_DICTION_OSGU_NAME'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_NAME', 'NAME', 'AtxtN8'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_NAME', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_NAME', 'CONTROLSOURCE', 'm.cAlias+".SGU_NAME"'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_NAME', 'REFERENCE_TO_DICT', 'KOSGU'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_NAME', 'TYPE_FIELD_DICT', 'VARCHAR(250)'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_NAME', 'SHORT_CODE_OBJ', 'SGU_NAME'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias+".SGU_NAME"'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_NAME', 'CONTROL_NAME_EDIT', 'AtxtN8'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_NAME', 'FIELD_DATA', 'SGU_NAME'
GO
EXEC X_SET_PROP 'COL_DICTION_OSGU_NAME', 'FIELD_KEY', 'SGU_NAME'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


EXEC X_SET_PROP 'BI_DICTION_KBK', 'SAVE_OBJECT_METHOD', 'X_SAVE(''BI_SAVE_KBK'', m.cAlias," TYPE,NAME,Adm_Link,KD_link,IVF_Link,prog_Link,div_link,csr_link,exp_link,sgu_link,sqlnull(KBKL_LINK),sqlnull(KBK14_LINK),USED,USED_ALL,OSN","BI_DICTION_KBK")'
GO

GO

GO
/****** Объект: Код старого КБК******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'BK_CHANGE_ANALIT_CODE_KBK1')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'BK_CHANGE_ANALIT_CODE_KBK1')
	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 = 'BK_CHANGE_ANALIT_CODE_KBK1')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'BK_CHANGE_ANALIT_CODE_KBK1')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'BK_CHANGE_ANALIT_CODE_KBK1'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'BK_CHANGE_ANALIT_CODE_KBK1')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BK_CHANGE_ANALIT_CODE_KBK1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BK_CHANGE_ANALIT_CODE_KBK1', 'Код старого КБК', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='BK_CHANGE_ANALIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BK_CHANGE_ANALIT_CODE_KBK1', NAME = 'Код старого КБК', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BK_CHANGE_ANALIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BK_CHANGE_ANALIT_CODE_KBK1'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK1', 'TITLE', 'Старый КБК'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK1', 'EDIT_OBJECT_METHOD', 'X_VALID_HEAD_AP(A_VIBOR_01 ("BI_DICTION_KBK", oForm.ALIAS, "LINK,NAME,CODE", "LN_KBK_OLD, NM_KBK_OLD, CD_KBK_OLD", "", "", "", .T., 1, oForm, oObj), oForm, oObj)'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK1', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK1', 'CONTROLSOURCE', 'm.cAlias+''.CD_KBK_OLD'''
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK1', 'STORAGE', 'KL_KBK'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK1', 'REFERENCE_TO_DICT', 'BK_CHANGE_ANALIT_LINK_KBK1'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK1', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK1', 'SHORT_CODE_OBJ', 'CD_KBK_OLD'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK1', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.CD_KBK_OLD'''
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK1', 'CONTROL_NAME_EDIT', 'ASel_Spr1'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK1', 'REFERENCE_TO_FIELD', 'CODE'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/

/****** Объект: Код нового КБК******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'BK_CHANGE_ANALIT_CODE_KBK2')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'BK_CHANGE_ANALIT_CODE_KBK2')
	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 = 'BK_CHANGE_ANALIT_CODE_KBK2')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'BK_CHANGE_ANALIT_CODE_KBK2')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'BK_CHANGE_ANALIT_CODE_KBK2'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'BK_CHANGE_ANALIT_CODE_KBK2')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='BK_CHANGE_ANALIT_CODE_KBK2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'BK_CHANGE_ANALIT_CODE_KBK2', 'Код нового КБК', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='BK_CHANGE_ANALIT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'BK_CHANGE_ANALIT_CODE_KBK2', NAME = 'Код нового КБК', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='BK_CHANGE_ANALIT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='BK_CHANGE_ANALIT_CODE_KBK2'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK2', 'TITLE', 'Новый КБК'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK2', 'EDIT_OBJECT_METHOD', 'X_VALID_HEAD_AP(A_VIBOR_01 ("BI_DICTION_KBK", oForm.ALIAS, "LINK,NAME,CODE", "LN_KBK_NEW, NM_KBK_NEW, CD_KBK_NEW", "", "", "", .T., 1, oForm, oObj), oForm, oObj)'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK2', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK2', 'CONTROLSOURCE', 'm.cAlias+''.CD_KBK_NEW'''
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK2', 'STORAGE', 'KL_KBK'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK2', 'REFERENCE_TO_DICT', 'BK_CHANGE_ANALIT_LINK_KBK2'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK2', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK2', 'SHORT_CODE_OBJ', 'CD_KBK_NEW'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK2', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.CD_KBK_NEW'''
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK2', 'CONTROL_NAME_EDIT', 'ASel_Spr2'
GO
EXEC X_SET_PROP 'BK_CHANGE_ANALIT_CODE_KBK2', 'REFERENCE_TO_FIELD', 'CODE'
GO

/**************** Формирование *************/

EXECUTE BK_FORM_VIEW_DOCUMENT_ZB 'BK_CHANGE_ANALIT', 'BK_CHANGE_ANALIT', 0, 0, 0

GO

GO
---- Изменение наименование 104 строки в Платежном поручении
EXEC X_SET_PROP 'COLUMN_DOC_PAY_DOHOD_NAME', 'TITLE', '104. Код по КБК'
GO

EXEC X_SET_PROP 'COLUMN_DOC_PAY_DOHOD_CODE', 'TYPE_FIELD_DICT', 'Char(30)'
GO

EXEC X_SET_PROP 'COLUMN_DOC_PAY_DOHOD_CODE', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("BI_DICTION_KBK", oForm.Pages.Page3.ALIAS, "LINK,CODE,NAME", "DOH_LINK,DOH_CODE,DOH_NAME", "", "", "type in (2, 1)", .T., 1, oForm, oObj)
'
GO

GO

EXEC X_SET_PROP 'COLUMN_DOC_PAY_STATUS', 'ROWSOURCE', '" ,,01,Налогоплательщик,02,Налоговый агент,08,Плательщик иных платежей,14,НП производящий выплаты ФЛ,15,Кредитная организация,19,Платеж на основании исполнит. докум.,20,Кредит. орг. с переводом по платежу ФЛ"'
GO

GO

EXEC X_SET_PROP 'COLUMN_KASSA_BOOK_G_SALARY_V', 'TITLE', ''
GO

EXEC X_SET_PROP 'COLUMN_KASSA_BOOK_EDIT_BUDIN_2', 'TITLE', 'Приход
(ден. средства)'
GO

EXEC X_SET_PROP 'COLUMN_KASSA_BOOK_EDIT_BUDOU_2', 'TITLE', 'Расход
(ден. средства)'
GO

EXEC X_SET_PROP 'COLUMN_KASSA_BOOK_EDIT_VNEIN_2', 'TITLE', 'Приход
(средства во врем. расп.)'
GO

EXEC X_SET_PROP 'COLUMN_KASSA_BOOK_EDIT_VNEOU_2', 'TITLE', 'Расход
(средства во врем. расп.)'
GO

EXEC X_SET_PROP 'COLUMN_KASSA_BOOK_EDIT_BUDIN_1', 'TITLE', 'Приход
(ден. средства)'
GO

EXEC X_SET_PROP 'COLUMN_KASSA_BOOK_EDIT_BUDOU_1', 'TITLE', 'Расход
(ден. средства)'
GO

EXEC X_SET_PROP 'COLUMN_KASSA_BOOK_EDIT_VNEIN_1', 'TITLE', 'Приход
(средства во врем. расп.)'
GO

EXEC X_SET_PROP 'COLUMN_KASSA_BOOK_EDIT_VNEOU_1', 'TITLE', 'Расход
(средства во врем. расп.)'
GO

EXEC X_SET_PROP 'COLUMN_DOC_NUMBER_2_1_1_1_1_1', 'TITLE', 'Средства во врем. расп.'
GO

EXEC X_SET_PROP 'COLUMN_DOC_NUMBER_2_1_1_1_1__1', 'TITLE', 'Средства во врем. расп.'
GO

if exists(SELECT * FROM S_ACCOUNTS sa 
inner join kassa_book_acc kba ON kba.link_acc=sa.link
where cSinth = '201' and (cAnalit = '34' or cAnalit = '04') and cSource <> ''
 and dbo.AccountsHasNoChild(SA.LINK) = 1 AND CODE = '3.201.34' )
BEGIN 
	UPDATE  kba
	SET TYPE = CASE WHEN kba.link_acc IN (SELECT kb.link_acc  FROM S_ACCOUNTS sa 
												inner join kassa_book_acc kb ON kb.link_acc=sa.link
												where cSinth = '201' and (cAnalit = '34' or cAnalit = '04') and cSource <> ''
												 and dbo.AccountsHasNoChild(SA.LINK) = 1 AND CODE = '3.201.34')
					THEN 1 
					ELSE 0 end							 
	from kassa_book_acc kba 
end	

GO

GO
/****** Объект: Статус передачи в Смету-Смарт******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_PROV_STATUS_EXCHANGE')
	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_PROV_STATUS_EXCHANGE')
	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_PROV_STATUS_EXCHANGE')
	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_PROV_STATUS_EXCHANGE')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_PROV_STATUS_EXCHANGE'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_PROV_STATUS_EXCHANGE')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_PROV_STATUS_EXCHANGE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_PROV_STATUS_EXCHANGE', 'Статус передачи в Смету-Смарт', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_PROV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_PROV_STATUS_EXCHANGE', NAME = 'Статус передачи в Смету-Смарт', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_PROV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_PROV_STATUS_EXCHANGE'
GO
EXEC X_SET_PROP 'COLUMN_PROV_STATUS_EXCHANGE', 'TITLE', 'Статус передачи в Смету-Смарт'
GO
EXEC X_SET_PROP 'COLUMN_PROV_STATUS_EXCHANGE', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'COLUMN_PROV_STATUS_EXCHANGE', 'CONTROLSOURCE', 'm.cAlias + ".STATUS_EX_NAME"'
GO

/****** Объект: Передача в Смету-Смарт Комментарий******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_PROV_ST_EX_COMM')
	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_PROV_ST_EX_COMM')
	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_PROV_ST_EX_COMM')
	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_PROV_ST_EX_COMM')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_PROV_ST_EX_COMM'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_PROV_ST_EX_COMM')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_PROV_ST_EX_COMM')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_PROV_ST_EX_COMM', 'Передача в Смету-Смарт Комментарий', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_PROV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_PROV_ST_EX_COMM', NAME = 'Передача в Смету-Смарт Комментарий', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_PROV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_PROV_ST_EX_COMM'
GO
EXEC X_SET_PROP 'COLUMN_PROV_ST_EX_COMM', 'TITLE', 'Комм. передачи в Смету-Смарт'
GO
EXEC X_SET_PROP 'COLUMN_PROV_ST_EX_COMM', 'VISIBLE', '3'
GO
EXEC X_SET_PROP 'COLUMN_PROV_ST_EX_COMM', 'CONTROLSOURCE', 'm.cAlias + ".ST_EX_COMMENT"'
GO




GO
/****** Объект: Расчет отпускных за счет резерва******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_RESERV')
	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_RESERV')
	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_RESERV')
	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_RESERV')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_RESERV'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COLUMN_RESERV')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_RESERV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_RESERV', 'Расчет отпускных за счет резерва', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_MROT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_RESERV', NAME = 'Расчет отпускных за счет резерва', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_MROT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_RESERV'
GO
EXEC X_SET_PROP 'COLUMN_RESERV', 'TITLE', 'Расчет отпускных за счет резерва'
GO
EXEC X_SET_PROP 'COLUMN_RESERV', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_RESERV', 'CONTROLSOURCE', 'm.cAlias+".RESERV"'
GO
EXEC X_SET_PROP 'COLUMN_RESERV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_RESERV', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_RESERV', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'COLUMN_RESERV', 'CONTROLSOURCE_EDIT', 'm.cAlias+".RESERV"'
GO
EXEC X_SET_PROP 'COLUMN_RESERV', 'CONTROL_NAME_EDIT', 'acheckbox8'
GO
EXEC X_SET_PROP 'COLUMN_RESERV', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'COLUMN_RESERV', 'ATTRIBUTES', 'style="Z-INDEX: 148; LEFT: 288px; POSITION: absolute; TOP: 112px""
Width="424px"'
GO
EXEC X_SET_PROP 'COLUMN_RESERV', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 116; LEFT: 16px; POSITION: absolute; TOP: 112px"'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
EXECUTE dbo.X_CREATE_ANALIT
EXECUTE dbo.X_CREATE_X_SELECT_PROV_AP
EXEC dbo.BX_CREATE_G_PROV_AP_EDIT_TABLE
GO

GO
declare @p1 FLOAT, @maxCode VARCHAR(10)
set @p1=(SELECT link FROM DICTIONARY_SKLON WHERE im = 'Нина' and DAT = 'Нине' AND TVOR = 'Ниной' AND  PRED = 'Нине' )
SET @maxCode = CASE WHEN ISNULL(@p1,0)<>0 THEN (SELECT CODE FROM DICTIONARY_SKLON WHERE link = @p1) 
					ELSE (SELECT MAX(convert(int,CODE)) FROM DICTIONARY_SKLON)+1 end
exec X_SAVE_DICTIONARY_SKLON @p1 output,@maxCode,'Нина','Нины','Нине','Нину','Ниной','Нине','20151224'

GO


GO
/****** Объект: Количество дней основного отпуска******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'DAYS_VAC_OSN')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'DAYS_VAC_OSN')
	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 = 'DAYS_VAC_OSN')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'DAYS_VAC_OSN')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DAYS_VAC_OSN'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DAYS_VAC_OSN')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DAYS_VAC_OSN')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DAYS_VAC_OSN', 'Количество дней основного отпуска', 49, (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 = 'DAYS_VAC_OSN', NAME = 'Количество дней основного отпуска', ORDERS = '49', 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 ='DAYS_VAC_OSN'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN', 'TITLE', 'Количество дней основного отпуска'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN', 'CONTROLSOURCE', 'm.cAlias+".DAY_VAC_O"'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN', 'TYPE_FIELD_DICT', 'NUMERIC(2,0)'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN', 'SHORT_CODE_OBJ', 'DAY_VAC_O'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DAY_VAC_O"'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN', 'CONTROL_NAME_EDIT', 'pgf.page1.atxt14'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN', 'INPUT_MASK', '99'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN', 'REFERENCE_TO_FIELD', 'VALUE'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN', 'COMMENTARY', 'Количество дней основного отпуска'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN', 'ATTRIBUTES', 'style="Z-INDEX: 106; LEFT: 208px; POSITION: absolute; TOP: 112px""
Width="104px"'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 111; LEFT: 16px; POSITION: absolute; TOP: 112px"'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN', 'FIELD_DATA', 'DAY_VAC_O'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/

/****** Объект: Количество дней дополнительного отпуска******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'DAYS_VAC_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 = 'DAYS_VAC_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 = 'DAYS_VAC_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 = 'DAYS_VAC_DOP')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DAYS_VAC_DOP'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DAYS_VAC_DOP')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DAYS_VAC_DOP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DAYS_VAC_DOP', 'Количество дней дополнительного отпуска', 50, (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 = 'DAYS_VAC_DOP', NAME = 'Количество дней дополнительного отпуска', ORDERS = '50', 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 ='DAYS_VAC_DOP'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP', 'TITLE', 'Количество дней дополнительного отпуска'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP', 'CONTROLSOURCE', 'm.cAlias+".DAY_VAC_D"'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP', 'TYPE_FIELD_DICT', 'numeric(2,0)'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP', 'SHORT_CODE_OBJ', 'DAY_VAC_D'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DAY_VAC_D"'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP', 'CONTROL_NAME_EDIT', 'pgf.page1.Atxt15'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP', 'INPUT_MASK', '99'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP', 'REFERENCE_TO_FIELD', 'VALUE'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP', 'COMMENTARY', 'Количество дней дополнительного отпуска'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP', 'ATTRIBUTES', 'style="Z-INDEX: 106; LEFT: 208px; POSITION: absolute; TOP: 112px""
Width="104px"'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 111; LEFT: 16px; POSITION: absolute; TOP: 112px"'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP', 'FIELD_DATA', 'DAY_VAC_D'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/

/****** Объект: Количество дней основного отпуска******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'DAYS_VAC_OSN_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 = 'DAYS_VAC_OSN_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 = 'DAYS_VAC_OSN_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 = 'DAYS_VAC_OSN_1')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DAYS_VAC_OSN_1'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DAYS_VAC_OSN_1')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DAYS_VAC_OSN_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DAYS_VAC_OSN_1', 'Количество дней основного отпуска', 43, (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 = 'DAYS_VAC_OSN_1', NAME = 'Количество дней основного отпуска', ORDERS = '43', 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 ='DAYS_VAC_OSN_1'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN_1', 'TITLE', 'Кол. дн. О.О.'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN_1', 'CONTROLSOURCE', 'm.cAlias+".DAY_VAC_O"'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN_1', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN_1', 'TYPE_FIELD_DICT', 'NUMERIC(2,0)'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN_1', 'SHORT_CODE_OBJ', 'DAY_VAC_O'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DAY_VAC_O"'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN_1', 'CONTROL_NAME_EDIT', 'pgf.page1.atxt14'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN_1', 'INPUT_MASK', '99'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN_1', 'REFERENCE_TO_FIELD', 'VALUE'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN_1', 'COMMENTARY', 'Количество дней основного отпуска'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN_1', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN_1', 'ATTRIBUTES', 'style="Z-INDEX: 106; LEFT: 208px; POSITION: absolute; TOP: 112px""
Width="104px"'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN_1', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 111; LEFT: 16px; POSITION: absolute; TOP: 112px"'
GO
EXEC X_SET_PROP 'DAYS_VAC_OSN_1', 'FIELD_DATA', 'DAY_VAC_O'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
/****** Объект: Количество дней дополнительного отпуска******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'DAYS_VAC_DOP_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 = 'DAYS_VAC_DOP_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 = 'DAYS_VAC_DOP_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 = 'DAYS_VAC_DOP_1')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DAYS_VAC_DOP_1'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DAYS_VAC_DOP_1')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DAYS_VAC_DOP_1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DAYS_VAC_DOP_1', 'Количество дней дополнительного отпуска', 44, (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 = 'DAYS_VAC_DOP_1', NAME = 'Количество дней дополнительного отпуска', ORDERS = '44', 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 ='DAYS_VAC_DOP_1'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP_1', 'TITLE', 'Кол. дн. Д.О.'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP_1', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP_1', 'CONTROLSOURCE', 'm.cAlias+".DAY_VAC_D"'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP_1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP_1', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP_1', 'TYPE_FIELD_DICT', 'numeric(2,0)'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP_1', 'SHORT_CODE_OBJ', 'DAY_VAC_D'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP_1', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DAY_VAC_D"'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP_1', 'CONTROL_NAME_EDIT', 'pgf.page1.Atxt15'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP_1', 'INPUT_MASK', '99'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP_1', 'REFERENCE_TO_FIELD', 'VALUE'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP_1', 'COMMENTARY', 'Количество дней дополнительного отпуска'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP_1', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP_1', 'ATTRIBUTES', 'style="Z-INDEX: 106; LEFT: 208px; POSITION: absolute; TOP: 112px""
Width="104px"'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP_1', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 111; LEFT: 16px; POSITION: absolute; TOP: 112px"'
GO
EXEC X_SET_PROP 'DAYS_VAC_DOP_1', 'FIELD_DATA', 'DAY_VAC_D'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
DECLARE @LINK_DICT INT,
		@OBJ_DEDUCT INT,
		@OBJ_DEDUCT_APP INT
SET @OBJ_DEDUCT = (select dbo.GetObjLink('DICTIONARY_TYP_DEDUCTION'))		
SET @OBJ_DEDUCT_APP = (select top 1 link from s_objects where code = 'COLUMN_CODE_T_D')		


IF NOT EXISTS(SELECT * FROM DICTIONARY_TYP_DEDUCTION WHERE code = '320')
	INSERT INTO dbo.DICTIONARY_TYP_DEDUCTION (SNAME,NAME,CODE,NUMBER,SUMMA)
	VALUES('320','Сумма, уплаченная налогоплательщиком за свое обучение в образовательных учреждениях, за обучение брата(сестры) в возрасте до 24 лет по очной форме обучения','320',11,0.00)
IF NOT EXISTS(SELECT * FROM s_objects o 
						INNER JOIN diction d ON  o.code = 'DICTIONARY_TYP_DEDUCTION'  
						AND	o.link = d.object 
			  WHERE d.code = '320')
BEGIN			  
	INSERT INTO dbo.diction (NAME,[OBJECT],CODE)
	VALUES(LEFT('Сумма, уплаченная налогоплательщиком за свое обучение в образовательных учреждениях, за обучение брата(сестры) в возрасте до 24 лет по очной форме обучения', 254), @OBJ_DEDUCT,'320')
	SET @LINK_DICT = (SELECT LINK FROM dbo.DICTION WHERE  [OBJECT] =  @OBJ_DEDUCT AND CODE = '320')
	INSERT INTO dbo.diction_APP (link_up,[OBJECT],VALUE)
	VALUES(@LINK_DICT, @OBJ_DEDUCT_APP,'320')	
	SET @LINK_DICT = 0
END 
	
IF NOT EXISTS(SELECT * FROM DICTIONARY_TYP_DEDUCTION WHERE code = '321')
	INSERT INTO dbo.DICTIONARY_TYP_DEDUCTION (SNAME,NAME,CODE,NUMBER,SUMMA)
	VALUES('321',LEFT('Сумма, уплаченная налогоплательщиком-родителем за обуч. своих детей в возрасте до 24 лет, налогоплательщиком-опекуном/попечителем за обучение своих подопечных в возрасте до 18 лет по очной форме обучения,или после прекращения опеки или попечительства в случаях оплаты обучения граждан в возрасте до 24 лет по очной форме обучения ', 254),'321',11,0.00)
IF NOT EXISTS(SELECT * FROM s_objects o 
						INNER JOIN diction d ON  o.code = 'DICTIONARY_TYP_DEDUCTION'  
						AND	o.link = d.object 
			  WHERE d.code = '321')
BEGIN			  
	INSERT INTO dbo.diction (NAME,[OBJECT],CODE)
	VALUES(LEFT('Сумма, уплаченная налогоплательщиком-родителем за обуч. своих детей в возрасте до 24 лет, налогоплательщиком-опекуном/попечителем за обучение своих подопечных в возрасте до 18 лет по очной форме обучения,или после прекращения опеки или попечительства в случаях оплаты обучения граждан в возрасте до 24 лет по очной форме обучения', 254), @OBJ_DEDUCT,'321')
	SET @LINK_DICT = (SELECT LINK FROM dbo.DICTION WHERE  [OBJECT] =  @OBJ_DEDUCT AND CODE = '321')
	INSERT INTO dbo.diction_APP (link_up,[OBJECT],VALUE)
	VALUES(@LINK_DICT, @OBJ_DEDUCT_APP,'321')	
	SET @LINK_DICT = 0
END 

IF NOT EXISTS(SELECT * FROM DICTIONARY_TYP_DEDUCTION WHERE code = '324')
	INSERT INTO dbo.DICTIONARY_TYP_DEDUCTION (SNAME,NAME,CODE,NUMBER,SUMMA)
	VALUES('324',LEFT('Сумма, уплаченная налогоплательщиком за мед. услуги, оказанные мед. организациями, индивидуальными предпринимателями, осуществляющими мед. деятельность, ему, его супругу (супруге), родителям, детям (в том числе усыновленным) в возрасте до 18 лет, подопечным в возрасте до 18 лет (в соответствии с перечнем мед. услуг), а также в размере стоимости лекарственных препаратов для мед. применения (в соответствии с перечнем лекарственных средств), назначенных им лечащим врачом и приобретаемых налогоплательщиком за счет собственных средств', 254),'324',12,0.00)
IF NOT EXISTS(SELECT * FROM s_objects o 
						INNER JOIN diction d ON  o.code = 'DICTIONARY_TYP_DEDUCTION'  
						AND	o.link = d.object 
			  WHERE d.code = '324')
BEGIN			  
	INSERT INTO dbo.diction (NAME,[OBJECT],CODE)
	VALUES(LEFT('Сумма, уплаченная налогоплательщиком за мед. услуги, оказанные мед. организациями, индивидуальными предпринимателями, осуществляющими мед. деятельность, ему, его супругу (супруге), родителям, детям (в том числе усыновленным) в возрасте до 18 лет, подопечным в возрасте до 18 лет (в соответствии с перечнем мед. услуг), а также в размере стоимости лекарственных препаратов для мед. применения (в соответствии с перечнем лекарственных средств), назначенных им лечащим врачом и приобретаемых налогоплательщиком за счет собственных средств', 254), @OBJ_DEDUCT,'324')
	SET @LINK_DICT = (SELECT LINK FROM dbo.DICTION WHERE  [OBJECT] =  @OBJ_DEDUCT AND CODE = '324')
	INSERT INTO dbo.diction_APP (link_up,[OBJECT],VALUE)
	VALUES(@LINK_DICT, @OBJ_DEDUCT_APP,'324')	
	SET @LINK_DICT = 0
END 

IF NOT EXISTS(SELECT * FROM DICTIONARY_TYP_DEDUCTION WHERE code = '325')
	INSERT INTO dbo.DICTIONARY_TYP_DEDUCTION (SNAME,NAME,CODE,NUMBER,SUMMA)
	VALUES('325',LEFT('Суммы страховых взносов, уплаченные налогоплательщиком по договорам добровольного личного страх., а также по договорам добровольного страх. своих супруга (супруги), родителей, детей (в том числе усыновленных) в возрасте до 18 лет, подопечных в возрасте до 18 лет, заключенным им со страх. организациями, имеющими лицензии на ведение соответствующего вида деятельности, предусматривающим оплату такими страх. организациями исключительно мед. услуг', 254),'325',12,0.00)
IF NOT EXISTS(SELECT * FROM s_objects o 
						INNER JOIN diction d ON  o.code = 'DICTIONARY_TYP_DEDUCTION'  
						AND	o.link = d.object 
			  WHERE d.code = '325')
BEGIN			  
	INSERT INTO dbo.diction (NAME,[OBJECT],CODE)
	VALUES(LEFT('Суммы страховых взносов, уплаченные налогоплательщиком по договорам добровольного личного страх., а также по договорам добровольного страх. своих супруга (супруги), родителей, детей (в том числе усыновленных) в возрасте до 18 лет, подопечных в возрасте до 18 лет, заключенным им со страх. организациями, имеющими лицензии на ведение соответствующего вида деятельности, предусматривающим оплату такими страх. организациями исключительно мед. услуг', 254), @OBJ_DEDUCT,'325')
	SET @LINK_DICT = (SELECT LINK FROM dbo.DICTION WHERE  [OBJECT] =  @OBJ_DEDUCT AND CODE = '325')
	INSERT INTO dbo.diction_APP (link_up,[OBJECT],VALUE)
	VALUES(@LINK_DICT, @OBJ_DEDUCT_APP,'325')
	SET @LINK_DICT = 0	
END 

IF NOT EXISTS(SELECT * FROM DICTIONARY_TYP_DEDUCTION WHERE code = '326')
	INSERT INTO dbo.DICTIONARY_TYP_DEDUCTION (SNAME,NAME,CODE,NUMBER,SUMMA)
	VALUES('326',LEFT('Сумма расходов по дорогостоящему лечению в мед. организациях, у индивидуальных предпринимателей, осуществляющих мед. деятельность, - в размере фактически произведенных расходов', 254),'326',12,0.00)
IF NOT EXISTS(SELECT * FROM s_objects o 
						INNER JOIN diction d ON  o.code = 'DICTIONARY_TYP_DEDUCTION'  
						AND	o.link = d.object 
			  WHERE d.code = '326')
BEGIN			  
	INSERT INTO dbo.diction (NAME,[OBJECT],CODE)
	VALUES(LEFT('Сумма расходов по дорогостоящему лечению в мед. организациях, у индивидуальных предпринимателей, осуществляющих мед. деятельность, - в размере фактически произведенных расходов', 254), @OBJ_DEDUCT,'326')
	SET @LINK_DICT = (SELECT LINK FROM dbo.DICTION WHERE  [OBJECT] =  @OBJ_DEDUCT AND CODE = '326')
	INSERT INTO dbo.diction_APP (link_up,[OBJECT],VALUE)
	VALUES(@LINK_DICT, @OBJ_DEDUCT_APP,'326')
	SET @LINK_DICT = 0	
END 

IF NOT EXISTS(SELECT * FROM DICTIONARY_TYP_DEDUCTION WHERE code = '327')
	INSERT INTO dbo.DICTIONARY_TYP_DEDUCTION (SNAME,NAME,CODE,NUMBER,SUMMA)
	VALUES('327',LEFT('Сумма уплаченных налогоплательщиком пенсионных взносов по договору (договорам) негосударственного пенсионного обеспечения, в сумме уплаченных налогоплательщиком в налоговом периоде страх. взносов по договору (договорам) добровольного пенс. страх. в свою пользу и (или) в пользу супруга (в том числе вдовы, вдовца), родителей (в том числе усыновителей), детей-инвалидов (в том числе усыновленных, находящихся под опекой (попечительством)', 254),'327',10,0.00)
IF NOT EXISTS(SELECT * FROM s_objects o 
						INNER JOIN diction d ON  o.code = 'DICTIONARY_TYP_DEDUCTION'  
						AND	o.link = d.object 
			  WHERE d.code = '327')
BEGIN			  
	INSERT INTO dbo.diction (NAME,[OBJECT],CODE)
	VALUES(LEFT('Сумма уплаченных налогоплательщиком пенсионных взносов по договору (договорам) негосударственного пенсионного обеспечения, в сумме уплаченных налогоплательщиком в налоговом периоде страх. взносов по договору (договорам) добровольного пенс. страх. в свою пользу и (или) в пользу супруга (в том числе вдовы, вдовца), родителей (в том числе усыновителей), детей-инвалидов (в том числе усыновленных, находящихся под опекой (попечительством)', 254), @OBJ_DEDUCT,'327')
	SET @LINK_DICT = (SELECT LINK FROM dbo.DICTION WHERE  [OBJECT] =  @OBJ_DEDUCT AND CODE = '327')
	INSERT INTO dbo.diction_APP (link_up,[OBJECT],VALUE)
	VALUES(@LINK_DICT, @OBJ_DEDUCT_APP,'327')	
	SET @LINK_DICT = 0
END 

IF NOT EXISTS(SELECT * FROM DICTIONARY_TYP_DEDUCTION WHERE code = '328')
	INSERT INTO dbo.DICTIONARY_TYP_DEDUCTION (SNAME,NAME,CODE,NUMBER,SUMMA)
	VALUES('328',LEFT('Сумма уплаченных налогоплательщиком дополнительных страховых взносов на накопительную пенсию - в размере фактически произведенных расходов с учетом ограничения', 254),'328',13,0.00)
IF NOT EXISTS(SELECT * FROM s_objects o 
						INNER JOIN diction d ON  o.code = 'DICTIONARY_TYP_DEDUCTION'  
						AND	o.link = d.object 
			  WHERE d.code = '328')
BEGIN			  
	INSERT INTO dbo.diction (NAME,[OBJECT],CODE)
	VALUES(LEFT('Сумма уплаченных налогоплательщиком дополнительных страховых взносов на накопительную пенсию - в размере фактически произведенных расходов с учетом ограничения', 254), @OBJ_DEDUCT,'328')
	SET @LINK_DICT = (SELECT LINK FROM dbo.DICTION WHERE  [OBJECT] =  @OBJ_DEDUCT AND CODE = '328')
	INSERT INTO dbo.diction_APP (link_up,[OBJECT],VALUE)
	VALUES(@LINK_DICT, @OBJ_DEDUCT_APP,'328')
	SET @LINK_DICT = 0	
END 
GO
/****** Объект: Клиенты сервиса обмена******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'DICT_RMS_CONTACTS')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'DICT_RMS_CONTACTS')
	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 = 'DICT_RMS_CONTACTS')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'DICT_RMS_CONTACTS')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DICT_RMS_CONTACTS'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DICT_RMS_CONTACTS')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_RMS_CONTACTS', 'Клиенты сервиса обмена', 24, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_BUH_DICTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),1,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_RMS_CONTACTS', NAME = 'Клиенты сервиса обмена', ORDERS = '24', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_BUH_DICTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DICT_RMS_CONTACTS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS_MARK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_RMS_CONTACTS_MARK', 'Поле-маркер справочника', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_RMS_CONTACTS_MARK', NAME = 'Поле-маркер справочника', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICT_RMS_CONTACTS_MARK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS_CHANAL_LINK')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_RMS_CONTACTS_CHANAL_LINK', 'Ссылка на канал', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_RMS_CONTACTS_CHANAL_LINK', NAME = 'Ссылка на канал', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICT_RMS_CONTACTS_CHANAL_LINK'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS_ADDRESS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_RMS_CONTACTS_ADDRESS', 'Адрес', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_RMS_CONTACTS_ADDRESS', NAME = 'Адрес', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICT_RMS_CONTACTS_ADDRESS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS_NAME')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_RMS_CONTACTS_NAME', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_RMS_CONTACTS_NAME', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICT_RMS_CONTACTS_NAME'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS_COMMENT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_RMS_CONTACTS_COMMENT', 'Комментарий', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_RMS_CONTACTS_COMMENT', NAME = 'Комментарий', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICT_RMS_CONTACTS_COMMENT'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS_ENABLED')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DICT_RMS_CONTACTS_ENABLED', 'Включен', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DICT_RMS_CONTACTS_ENABLED', NAME = 'Включен', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICT_RMS_CONTACTS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DICT_RMS_CONTACTS_ENABLED'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS', 'TITLE', 'Клиенты сервиса обмена'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS', 'INIT_OBJECT_METHOD', 'x_spisok(''DICT_RMS_CONTACTS'')'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''DICT_RMS_CONTACTS'')'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(''DICT_RMS_CONTACTS'')'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS', 'OPEN_CODE', 'LINK'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS', 'SERVER_TABLE_NAME', 'RMS_CONTACTS'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS', 'HELP_TOPIC', 'Клиенты сервиса обмена'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS', 'PREPARE_NEW_RECORD', 'x_new_diction_record(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_MARK', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_MARK', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_MARK', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_CHANAL_LINK', 'TITLE', 'Ссылка на канал'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_CHANAL_LINK', 'CONTROL_TYPE', '8'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_CHANAL_LINK', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_CHANAL_LINK', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_CHANAL_LINK', 'SHORT_CODE_OBJ', 'LINK'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_CHANAL_LINK', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".LINK"'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_CHANAL_LINK', 'REFERENCE_TO_FIELD', 'LINK'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ADDRESS', 'TITLE', 'Адрес'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ADDRESS', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ADDRESS', 'CONTROLSOURCE', 'm.cAlias + ".ADDRESS"'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ADDRESS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ADDRESS', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ADDRESS', 'TYPE_FIELD_DICT', 'varchar(100)'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ADDRESS', 'SHORT_CODE_OBJ', 'ADDRESS'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ADDRESS', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ADDRESS"'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ADDRESS', 'CONTROL_NAME_EDIT', 'ATxt1'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ADDRESS', 'REFERENCE_TO_FIELD', 'ADDRESS'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_NAME', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_NAME', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_NAME', 'CONTROLSOURCE', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_NAME', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_NAME', 'STORAGE', 'DICTION'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_NAME', 'TYPE_FIELD_DICT', 'varchar(254)'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_NAME', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_NAME', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME"'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_NAME', 'CONTROL_NAME_EDIT', 'ATxt2'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_NAME', 'REFERENCE_TO_FIELD', 'NAME'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_COMMENT', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_COMMENT', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_COMMENT', 'CONTROLSOURCE', 'm.cAlias + ".COMMENTS"'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_COMMENT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_COMMENT', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_COMMENT', 'TYPE_FIELD_DICT', 'varchar(254)'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_COMMENT', 'SHORT_CODE_OBJ', 'COMMENTS'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_COMMENT', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COMMENTS"'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_COMMENT', 'CONTROL_NAME_EDIT', 'ATxt3'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_COMMENT', 'REFERENCE_TO_FIELD', 'COMMENTS'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ENABLED', 'TITLE', 'Включен'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ENABLED', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ENABLED', 'CONTROLSOURCE', 'm.cAlias + ".ENABLED"'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ENABLED', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ENABLED', 'TYPE_FIELD_DICT', 'char(3)'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ENABLED', 'SHORT_CODE_OBJ', 'ENABLED'
GO
EXEC X_SET_PROP 'DICT_RMS_CONTACTS_ENABLED', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ENABLED"'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'SAL_OPT_INTEGR_CHANAL', 'db_owner', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'DICT_RMS_CONTACTS', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'DICT_RMS_CONTACTS', 'Смета-КС', 63,0
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Интеграция с ПК Смета-Смарт"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '4811' AND NAME = 'НАСТРОЙКИ')

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 = '4811' AND NAME = 'НАСТРОЙКИ'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SAL_INTEGR_SMETA_SMART_FOLDER'),0)

IF COALESCE(@LINK_SELF,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'SAL_INTEGR_SMETA_SMART_FOLDER', 'Интеграция с ПК Смета-Смарт', @ORD, NULL, 1, @LINK_SELF, 'FOLDER', NULL, @LINK_VAR, 3
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Клиенты сервиса обмена"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SAL_INTEGR_SMETA_SMART_FOLDER' AND NAME = 'Интеграция с ПК Смета-Смарт')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DICT_RMS_CONTACTS')

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 = 'SAL_INTEGR_SMETA_SMART_FOLDER' AND NAME = 'Интеграция с ПК Смета-Смарт'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SAL_CLIENT_EXCH_SERVICE'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'SAL_CLIENT_EXCH_SERVICE', 'Клиенты сервиса обмена', @ORD, NULL, 1, @LINK_SELF, 'DICTIONARY', @OBJECT, @LINK_VAR, 3
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='DOCUMENTS_ADD_RESERV'

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_DOCUMENTS_ADD_RESERV]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_DOCUMENTS_ADD_RESERV]

CREATE TABLE  dbo._UPD_OPT_DOCUMENTS_ADD_RESERV (CODE VARCHAR(30), [SID] varbinary(85), VALUE VARCHAR(1000))

INSERT INTO _UPD_OPT_DOCUMENTS_ADD_RESERV (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 = 'DOCUMENTS_ADD_RESERV')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'DOCUMENTS_ADD_RESERV')
	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 = 'DOCUMENTS_ADD_RESERV')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'DOCUMENTS_ADD_RESERV')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_ADD_RESERV'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_ADD_RESERV')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_ADD_RESERV', 'Расчет резерва сумм отпускных', 32, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENT_SALARY_KADR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_ADD_RESERV', NAME = 'Расчет резерва сумм отпускных', ORDERS = '32', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENT_SALARY_KADR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='XDOCUMENT_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='DOCUMENTS_ADD_RESERV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_MARKER_ADD_RESERV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_MARKER_ADD_RESERV', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_MARKER_ADD_RESERV', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_MARKER_ADD_RESERV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NUMBER_ADD_RESERV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NUMBER_ADD_RESERV', 'Номер документа', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NUMBER_ADD_RESERV', NAME = 'Номер документа', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NUMBER_ADD_RESERV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DATE_ADD_RESERV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DATE_ADD_RESERV', 'Дата документа', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DATE_ADD_RESERV', NAME = 'Дата документа', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DATE_ADD_RESERV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COL_MONTH_PERIOD_ADD_RESERV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COL_MONTH_PERIOD_ADD_RESERV', 'Месяц периода расчета', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COL_MONTH_PERIOD_ADD_RESERV', NAME = 'Месяц периода расчета', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COL_MONTH_PERIOD_ADD_RESERV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COL_YEAR_PERIOD_ADD_RESERV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COL_YEAR_PERIOD_ADD_RESERV', 'Год периода расчета', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COL_YEAR_PERIOD_ADD_RESERV', NAME = 'Год периода расчета', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COL_YEAR_PERIOD_ADD_RESERV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_ISUMMA_ADD_RESERV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_ISUMMA_ADD_RESERV', 'Итоговая сумма', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_ISUMMA_ADD_RESERV', NAME = 'Итоговая сумма', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_ISUMMA_ADD_RESERV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='ADD_RESERV_NAME_DEP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'ADD_RESERV_NAME_DEP', 'Организация', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'ADD_RESERV_NAME_DEP', NAME = 'Организация', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='ADD_RESERV_NAME_DEP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_ADD_RESERV_COMMENTARY')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_ADD_RESERV_COMMENTARY', 'Комментарий', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_ADD_RESERV_COMMENTARY', NAME = 'Комментарий', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_ADD_RESERV_COMMENTARY'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_ADD_RESERV_TABLE', 'Расчет резерва таблица', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_ADD_RESERV_TABLE', NAME = 'Расчет резерва таблица', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_ADD_RESERV_TABLE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_OPTIONS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_ADD_RESERV_OPTIONS', 'Настройки расчета резерва сумм отпускных', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_ADD_RESERV_OPTIONS', NAME = 'Настройки расчета резерва сумм отпускных', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_ADD_RESERV_OPTIONS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_MARKER_ADD_RESERV_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_MARKER_ADD_RESERV_T', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_MARKER_ADD_RESERV_T', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_MARKER_ADD_RESERV_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NUMBER_ADD_RESERV_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NUMBER_ADD_RESERV_T', 'Номер строки', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NUMBER_ADD_RESERV_T', NAME = 'Номер строки', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NUMBER_ADD_RESERV_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_CODE_EMPL_ADD_RESERV_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_CODE_EMPL_ADD_RESERV_T', 'Табельный номер', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_CODE_EMPL_ADD_RESERV_T', NAME = 'Табельный номер', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_CODE_EMPL_ADD_RESERV_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_EMPL_ADD_RESERV_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_EMPL_ADD_RESERV_T', 'ФИО', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_EMPL_ADD_RESERV_T', NAME = 'ФИО', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_EMPL_ADD_RESERV_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_REF_EMPL_ADD_RESERV_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_REF_EMPL_ADD_RESERV_T', 'Ссылка на работника', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_REF_EMPL_ADD_RESERV_T', NAME = 'Ссылка на работника', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_REF_EMPL_ADD_RESERV_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_SUMMA_BASE_ADD_RESERV_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_SUMMA_BASE_ADD_RESERV_T', 'Сумма базовая', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_SUMMA_BASE_ADD_RESERV_T', NAME = 'Сумма базовая', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_SUMMA_BASE_ADD_RESERV_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_AMOUN_DED_ADD_RESERV_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_AMOUN_DED_ADD_RESERV_T', 'Размер вычетов', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_AMOUN_DED_ADD_RESERV_T', NAME = 'Размер вычетов', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_AMOUN_DED_ADD_RESERV_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_SUMMA_DED_ADD_RESERV_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_SUMMA_DED_ADD_RESERV_T', 'Сумма вычетов', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_SUMMA_DED_ADD_RESERV_T', NAME = 'Сумма вычетов', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_SUMMA_DED_ADD_RESERV_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_AMOUNT_TR_ADD_RESERV_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_AMOUNT_TR_ADD_RESERV_T', 'Размер по травматизму', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_AMOUNT_TR_ADD_RESERV_T', NAME = 'Размер по травматизму', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_AMOUNT_TR_ADD_RESERV_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_SUMMA_TR_RESERV_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_SUMMA_TR_RESERV_T', 'Сумма по травматизму', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_SUMMA_TR_RESERV_T', NAME = 'Сумма по травматизму', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_SUMMA_TR_RESERV_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_OST_VAC_D_ADD_RESERV')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_OST_VAC_D_ADD_RESERV', 'Остаток дней отпуска', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_OST_VAC_D_ADD_RESERV', NAME = 'Остаток дней отпуска', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_OST_VAC_D_ADD_RESERV'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_SUM_RESERV_ADD_RES_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_SUM_RESERV_ADD_RES_T', 'Сумма расчета резерва', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_SUM_RESERV_ADD_RES_T', NAME = 'Сумма расчета резерва', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_SUM_RESERV_ADD_RES_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_REF_SUBDIV_ADD_RESERV_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_REF_SUBDIV_ADD_RESERV_T', 'Ссылка на подразделение', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_REF_SUBDIV_ADD_RESERV_T', NAME = 'Ссылка на подразделение', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_REF_SUBDIV_ADD_RESERV_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_REF_POST_ADD_RESERV_T')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_REF_POST_ADD_RESERV_T', 'Ссылка на должность', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_REF_POST_ADD_RESERV_T', NAME = 'Ссылка на должность', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_TABLE'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_REF_POST_ADD_RESERV_T'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_OPT1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOCUMENTS_ADD_RESERV_OPT1', 'Вид начисления для расчета отпускных', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOCUMENTS_ADD_RESERV_OPT1', NAME = 'Вид начисления для расчета отпускных', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_ADD_RESERV_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOCUMENTS_ADD_RESERV_OPT1'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV', 'TITLE', 'Расчет резерва сумм отпускных'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV', 'INIT_OBJECT_METHOD', 'X_SPISOK("DOCUMENTS_ADD_RESERV")'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "DOCUMENTS_ADD_RESERV", "SALARY_DELETE_SDOC", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV', 'SAVE_OBJECT_METHOD', 'sd_n_reserv_save(oForm)'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV', 'EDIT_OBJECT_METHOD', 'SALARY_BROW(''SD_N_RESERV'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV', 'SELECT_RECORDS_METHOD', 'sa_select_document_list_zb1(''DOCUMENTS_ADD_RESERV'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DOCUMENT_LIST(''DOCUMENTS_ADD_RESERV'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV', 'SERVER_TABLE_NAME', 'SDOC'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV', 'OPTIONS_OBJECT_CODE', 'DOCUMENTS_ADD_RESERV_OPTIONS'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV', 'HELP_TOPIC', '23'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV', 'COMMENTARY', 'РАСЧЕТ РЕЗЕРВА СУММ ОТПУСКНЫХ

Режим предназначен для организаций, в которых ведется расчет сумм отпусков с учетом резерва. 

'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_ADD_RESERV', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_ADD_RESERV', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_ADD_RESERV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV', 'TITLE', '№'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV', 'CONTROLSOURCE', 'm.cAlias + ".NUMBER"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV', 'TYPE_FIELD_DICT', 'VARCHAR(10)'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NUMBER"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.numdate1.number'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV', 'COMMENTARY', 'Номер документа по порядку'
GO
EXEC X_SET_PROP 'COLUMN_DATE_ADD_RESERV', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'COLUMN_DATE_ADD_RESERV', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_DATE_ADD_RESERV', 'CONTROLSOURCE', 'm.cAlias + ".DATE"'
GO
EXEC X_SET_PROP 'COLUMN_DATE_ADD_RESERV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DATE_ADD_RESERV', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_DATE_ADD_RESERV', 'TYPE_FIELD_DICT', 'datetime'
GO
EXEC X_SET_PROP 'COLUMN_DATE_ADD_RESERV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE"'
GO
EXEC X_SET_PROP 'COLUMN_DATE_ADD_RESERV', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.numdate1.date'
GO
EXEC X_SET_PROP 'COLUMN_DATE_ADD_RESERV', 'COMMENTARY', 'Дата расчета'
GO
EXEC X_SET_PROP 'COL_MONTH_PERIOD_ADD_RESERV', 'TITLE', 'Месяц'
GO
EXEC X_SET_PROP 'COL_MONTH_PERIOD_ADD_RESERV', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COL_MONTH_PERIOD_ADD_RESERV', 'CONTROLSOURCE', 'm.cAlias + ".MONTH"'
GO
EXEC X_SET_PROP 'COL_MONTH_PERIOD_ADD_RESERV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COL_MONTH_PERIOD_ADD_RESERV', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COL_MONTH_PERIOD_ADD_RESERV', 'TYPE_FIELD_DICT', 'NUMERIC(4,0)'
GO
EXEC X_SET_PROP 'COL_MONTH_PERIOD_ADD_RESERV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".MONTH"'
GO
EXEC X_SET_PROP 'COL_MONTH_PERIOD_ADD_RESERV', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.Amonth1'
GO
EXEC X_SET_PROP 'COL_MONTH_PERIOD_ADD_RESERV', 'COMMENTARY', 'Месяц периода расчета'
GO
EXEC X_SET_PROP 'COL_YEAR_PERIOD_ADD_RESERV', 'TITLE', 'Год'
GO
EXEC X_SET_PROP 'COL_YEAR_PERIOD_ADD_RESERV', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COL_YEAR_PERIOD_ADD_RESERV', 'CONTROLSOURCE', 'm.cAlias + ".YEAR"'
GO
EXEC X_SET_PROP 'COL_YEAR_PERIOD_ADD_RESERV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COL_YEAR_PERIOD_ADD_RESERV', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COL_YEAR_PERIOD_ADD_RESERV', 'TYPE_FIELD_DICT', 'NUMERIC(10,0)'
GO
EXEC X_SET_PROP 'COL_YEAR_PERIOD_ADD_RESERV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".YEAR"'
GO
EXEC X_SET_PROP 'COL_YEAR_PERIOD_ADD_RESERV', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.Ayear1'
GO
EXEC X_SET_PROP 'COL_YEAR_PERIOD_ADD_RESERV', 'COMMENTARY', 'Год периода расчета'
GO
EXEC X_SET_PROP 'COLUMN_ISUMMA_ADD_RESERV', 'TITLE', 'Итоговая сумма'
GO
EXEC X_SET_PROP 'COLUMN_ISUMMA_ADD_RESERV', 'ORDER_NUMBER', '10'
GO
EXEC X_SET_PROP 'COLUMN_ISUMMA_ADD_RESERV', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_ISUMMA_ADD_RESERV', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'COLUMN_ISUMMA_ADD_RESERV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_ISUMMA_ADD_RESERV', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_ISUMMA_ADD_RESERV', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'COLUMN_ISUMMA_ADD_RESERV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA"'
GO
EXEC X_SET_PROP 'COLUMN_ISUMMA_ADD_RESERV', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.Atextbox2'
GO
EXEC X_SET_PROP 'ADD_RESERV_NAME_DEP', 'TITLE', 'Организация'
GO
EXEC X_SET_PROP 'ADD_RESERV_NAME_DEP', 'EDIT_OBJECT_METHOD', 'N_VIBOR_01 (''DICTIONARY_DEPARTMENT'', oForm.ALIAS, ''LINK, NAME'', ''LINK_DEP, NAME_DEP'', '''','''', "(TYPE=4 OR ZB=1) AND dbo.xu_GetAccessByDep (LINK) > 0 ", .T., 1, oForm, oObj, "")'
GO
EXEC X_SET_PROP 'ADD_RESERV_NAME_DEP', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'ADD_RESERV_NAME_DEP', 'CONTROLSOURCE', 'm.cAlias + ".NAME_DEP"'
GO
EXEC X_SET_PROP 'ADD_RESERV_NAME_DEP', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'ADD_RESERV_NAME_DEP', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'ADD_RESERV_NAME_DEP', 'TYPE_FIELD_DICT', 'VARCHAR(50)'
GO
EXEC X_SET_PROP 'ADD_RESERV_NAME_DEP', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_DEP"'
GO
EXEC X_SET_PROP 'ADD_RESERV_NAME_DEP', 'CONTROL_NAME_EDIT', 'APageframe1.Page1.cnt_dep.asel_spr01'
GO
EXEC X_SET_PROP 'ADD_RESERV_NAME_DEP', 'COMMENTARY', 'Наименование организации'
GO
EXEC X_SET_PROP 'DOC_ADD_RESERV_COMMENTARY', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'DOC_ADD_RESERV_COMMENTARY', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'DOC_ADD_RESERV_COMMENTARY', 'CONTROLSOURCE', 'm.cAlias + ".COMMENTARY"'
GO
EXEC X_SET_PROP 'DOC_ADD_RESERV_COMMENTARY', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_ADD_RESERV_COMMENTARY', 'TYPE_FIELD_DICT', 'VARCHAR(50)'
GO
EXEC X_SET_PROP 'DOC_ADD_RESERV_COMMENTARY', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".COMMENTARY"'
GO
EXEC X_SET_PROP 'DOC_ADD_RESERV_COMMENTARY', 'COMMENTARY', 'Комментарий к расчету'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV_TABLE', 'SELECT_RECORDS_METHOD', 'salary_select_table(m.nLinkSalaryTable, m.cAlias,''DOCUMENTS_ADD_RESERV_TABLE'',''*'')'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV_OPTIONS', 'TITLE', 'Настройки расчета резерва сумм отпускных'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV_OPTIONS', 'EDIT_OBJECT_METHOD', 'sa_open_task_options("DOCUMENTS_ADD_RESERV", "Группа базовых начислений для расчета ФОТ")'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV_OPTIONS', 'COMMENTARY', 'Настройки устанавливают параметры по умолчанию и особенности для режима "Расчет резерва сумм отпускных"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_ADD_RESERV_T', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_ADD_RESERV_T', 'CONTROLSOURCE', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_ADD_RESERV_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV_T', 'TITLE', '№'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV_T', 'ORDER_NUMBER', '1'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV_T', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV_T', 'CONTROLSOURCE', 'm.cAlias + ".ORDERS"'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV_T', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV_T', 'TYPE_FIELD_DICT', 'NUMERIC(5,0)'
GO
EXEC X_SET_PROP 'COLUMN_NUMBER_ADD_RESERV_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ORDERS"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_ADD_RESERV_T', 'TITLE', 'Tаб.№'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_ADD_RESERV_T', 'ORDER_NUMBER', '2'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_ADD_RESERV_T', 'EDIT_OBJECT_METHOD', 'N_VIBOR_01 (''KU_EMPL_PLACING'', oForm.apageframe1.page2.bSpisok.bGrid1.RecordSource, ''LINK, TAB, NAME_EMPL, SUBDIV_LINK, SUBDIV_NAME, POST_LINK, POST_NAME'', ''REF_EMPL,  TAB_NUMER, NAME_EMPL, REF_SUBDIV, NAME_SUBDIV, REF_POST, NAME_POST'', '''', '''',''DEP_LINK= '' + STR(EVALUATE(oFORM.ALIAS + ".LINK_DEP")), .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_ADD_RESERV_T', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_ADD_RESERV_T', 'CONTROLSOURCE', 'm.cAlias + ".TAB_NUMER"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_ADD_RESERV_T', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_ADD_RESERV_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_ADD_RESERV_T', 'TYPE_FIELD_DICT', 'VARCHAR(5)'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_ADD_RESERV_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TAB_NUMER"'
GO
EXEC X_SET_PROP 'COLUMN_CODE_EMPL_ADD_RESERV_T', 'CONTROL_NAME_EDIT', 'Asel_spr1'
GO
EXEC X_SET_PROP 'COLUMN_NAME_EMPL_ADD_RESERV_T', 'TITLE', 'ФИО'
GO
EXEC X_SET_PROP 'COLUMN_NAME_EMPL_ADD_RESERV_T', 'ORDER_NUMBER', '3'
GO
EXEC X_SET_PROP 'COLUMN_NAME_EMPL_ADD_RESERV_T', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_NAME_EMPL_ADD_RESERV_T', 'CONTROLSOURCE', 'm.cAlias + ".NAME_EMPL"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_EMPL_ADD_RESERV_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_NAME_EMPL_ADD_RESERV_T', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_EMPL_ADD_RESERV_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".NAME_EMPL"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_EMPL_ADD_RESERV_T', 'CONTROL_NAME_EDIT', 'Atextbox1'
GO
EXEC X_SET_PROP 'COLUMN_REF_EMPL_ADD_RESERV_T', 'CONTROLSOURCE', 'm.cAlias + ".REF_EMPL"'
GO
EXEC X_SET_PROP 'COLUMN_REF_EMPL_ADD_RESERV_T', 'TYPE_FIELD_DICT', 'NUMERIC(24,0)'
GO
EXEC X_SET_PROP 'COLUMN_REF_EMPL_ADD_RESERV_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".REF_EMPL"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_ADD_RESERV_T', 'TITLE', 'Базовая сумма'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_ADD_RESERV_T', 'ORDER_NUMBER', '5'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_ADD_RESERV_T', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_ADD_RESERV_T', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA_BASE"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_ADD_RESERV_T', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_ADD_RESERV_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_ADD_RESERV_T', 'TYPE_FIELD_DICT', 'NUMERIC(15,2)'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_BASE_ADD_RESERV_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA_BASE"'
GO
EXEC X_SET_PROP 'COLUMN_AMOUN_DED_ADD_RESERV_T', 'TITLE', 'Размер СВ'
GO
EXEC X_SET_PROP 'COLUMN_AMOUN_DED_ADD_RESERV_T', 'ORDER_NUMBER', '4'
GO
EXEC X_SET_PROP 'COLUMN_AMOUN_DED_ADD_RESERV_T', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_AMOUN_DED_ADD_RESERV_T', 'CONTROLSOURCE', 'm.cAlias + ".AMOUNT_DED"'
GO
EXEC X_SET_PROP 'COLUMN_AMOUN_DED_ADD_RESERV_T', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_AMOUN_DED_ADD_RESERV_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_AMOUN_DED_ADD_RESERV_T', 'TYPE_FIELD_DICT', 'NUMERIC(20,2)'
GO
EXEC X_SET_PROP 'COLUMN_AMOUN_DED_ADD_RESERV_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".AMOUNT_DED"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DED_ADD_RESERV_T', 'TITLE', 'Сумма СВ'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DED_ADD_RESERV_T', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DED_ADD_RESERV_T', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DED_ADD_RESERV_T', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA_DED"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DED_ADD_RESERV_T', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DED_ADD_RESERV_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DED_ADD_RESERV_T', 'TYPE_FIELD_DICT', 'NUMERIC(20,2)'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_DED_ADD_RESERV_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA_DED"'
GO
EXEC X_SET_PROP 'COLUMN_AMOUNT_TR_ADD_RESERV_T', 'TITLE', 'Размер Тр.'
GO
EXEC X_SET_PROP 'COLUMN_AMOUNT_TR_ADD_RESERV_T', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'COLUMN_AMOUNT_TR_ADD_RESERV_T', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_AMOUNT_TR_ADD_RESERV_T', 'CONTROLSOURCE', 'm.cAlias + ".AMOUNT_TR"'
GO
EXEC X_SET_PROP 'COLUMN_AMOUNT_TR_ADD_RESERV_T', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_AMOUNT_TR_ADD_RESERV_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_AMOUNT_TR_ADD_RESERV_T', 'TYPE_FIELD_DICT', 'NUMERIC(20,2)'
GO
EXEC X_SET_PROP 'COLUMN_AMOUNT_TR_ADD_RESERV_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".AMOUNT_TR"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_TR_RESERV_T', 'TITLE', 'Сумма Тр'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_TR_RESERV_T', 'ORDER_NUMBER', '6'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_TR_RESERV_T', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_TR_RESERV_T', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA_TR"'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_TR_RESERV_T', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_TR_RESERV_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_TR_RESERV_T', 'TYPE_FIELD_DICT', 'NUMERIC(20,2)'
GO
EXEC X_SET_PROP 'COLUMN_SUMMA_TR_RESERV_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA_TR"'
GO
EXEC X_SET_PROP 'COLUMN_OST_VAC_D_ADD_RESERV', 'TITLE', 'Остаток дн. отп.'
GO
EXEC X_SET_PROP 'COLUMN_OST_VAC_D_ADD_RESERV', 'ORDER_NUMBER', '9'
GO
EXEC X_SET_PROP 'COLUMN_OST_VAC_D_ADD_RESERV', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_OST_VAC_D_ADD_RESERV', 'CONTROLSOURCE', 'm.cAlias + ".OST_VAC_D"'
GO
EXEC X_SET_PROP 'COLUMN_OST_VAC_D_ADD_RESERV', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_OST_VAC_D_ADD_RESERV', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_OST_VAC_D_ADD_RESERV', 'TYPE_FIELD_DICT', 'NUMERIC(10,2)'
GO
EXEC X_SET_PROP 'COLUMN_OST_VAC_D_ADD_RESERV', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".OST_VAC_D"'
GO
EXEC X_SET_PROP 'COLUMN_SUM_RESERV_ADD_RES_T', 'TITLE', 'Сумма резерва'
GO
EXEC X_SET_PROP 'COLUMN_SUM_RESERV_ADD_RES_T', 'ORDER_NUMBER', '9'
GO
EXEC X_SET_PROP 'COLUMN_SUM_RESERV_ADD_RES_T', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_SUM_RESERV_ADD_RES_T', 'CONTROLSOURCE', 'm.cAlias + ".SUMMA_RESERV"'
GO
EXEC X_SET_PROP 'COLUMN_SUM_RESERV_ADD_RES_T', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_SUM_RESERV_ADD_RES_T', 'CONTROL_TYPE', '2'
GO
EXEC X_SET_PROP 'COLUMN_SUM_RESERV_ADD_RES_T', 'TYPE_FIELD_DICT', 'NUMERIC(20,2)'
GO
EXEC X_SET_PROP 'COLUMN_SUM_RESERV_ADD_RES_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".SUMMA_RESERV"'
GO
EXEC X_SET_PROP 'COLUMN_REF_SUBDIV_ADD_RESERV_T', 'TITLE', 'Ссылка на подразделение'
GO
EXEC X_SET_PROP 'COLUMN_REF_SUBDIV_ADD_RESERV_T', 'CONTROLSOURCE', 'm.cAlias + ".REF_SUBDIV"'
GO
EXEC X_SET_PROP 'COLUMN_REF_SUBDIV_ADD_RESERV_T', 'TYPE_FIELD_DICT', 'numeric(24,0)'
GO
EXEC X_SET_PROP 'COLUMN_REF_SUBDIV_ADD_RESERV_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".REF_SUBDIV"'
GO
EXEC X_SET_PROP 'COLUMN_REF_POST_ADD_RESERV_T', 'TITLE', 'Ссылка на должность'
GO
EXEC X_SET_PROP 'COLUMN_REF_POST_ADD_RESERV_T', 'CONTROLSOURCE', 'm.cAlias + ".REF_POST"'
GO
EXEC X_SET_PROP 'COLUMN_REF_POST_ADD_RESERV_T', 'TYPE_FIELD_DICT', 'numeric(24,0)'
GO
EXEC X_SET_PROP 'COLUMN_REF_POST_ADD_RESERV_T', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".REF_POST"'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV_OPT1', 'TITLE', 'Вид начисления для расчета отпускных'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV_OPT1', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("DICTIONARY_PAY_SALARY", oForm.cSel_Spr_Alias, "LINK, CODE, NAME", "AN_OPT1,AN_OPT1C,AN_OPT1N", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV_OPT1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV_OPT1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV_OPT1', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV_OPT1', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV_OPT1', 'SHORT_CODE_OBJ', 'AN_OPT1'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV_OPT1', 'CONTROL_NAME_EDIT', 'Asel_spr1'
GO
EXEC X_SET_PROP 'DOCUMENTS_ADD_RESERV_OPT1', 'COMMENTARY', 'Настройки вида начисления используются для расчета среднедневного заработка'
GO
/******--Восстановить, либо установить настройки на базе пользователя ******/
DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'DOCUMENTS_ADD_RESERV_OPT1' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_DOCUMENTS_ADD_RESERV] WHERE CODE = 'DOCUMENTS_ADD_RESERV_OPT1')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'DOCUMENTS_ADD_RESERV_OPT1'), SID, VALUE FROM [dbo].[_UPD_OPT_DOCUMENTS_ADD_RESERV] WHERE CODE = 'DOCUMENTS_ADD_RESERV_OPT1'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '34364' FROM  dbo.S_OBJECTS WHERE CODE = 'DOCUMENTS_ADD_RESERV_OPT1'

GO


IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_DOCUMENTS_ADD_RESERV]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_DOCUMENTS_ADD_RESERV]

GO


/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'DOCUMENTS_ADD_RESERV', 'db_owner', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'DOCUMENTS_ADD_RESERV', 'Зарплата-КС', 63,0
GO

/**************** УСТАНОВКА ДОСТУПА К НАСТРОЙКАМ *************/

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Расчет резерва сумм отпускных"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '4337' AND NAME = 'РАСЧЕТЫ')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DOCUMENTS_ADD_RESERV')

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 = '4337' AND NAME = 'РАСЧЕТЫ'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SD_ADD_RESERV_NAVIGATOR'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'SD_ADD_RESERV_NAVIGATOR', 'Расчет резерва сумм отпускных', @ORD, NULL, 1, @LINK_SELF, 'DOCUMENT', @OBJECT, @LINK_VAR, 3
GO


GO
EXEC X_SET_PROP 'DOCUMENTS_M15', 'SAVE_OBJECT_METHOD', 'X_SAVE(''X_SAVE_DOCUMENTS_M15'', m.cAlias,"NUMBER, SQLNULL(DATE), SQLNULL(DATE_PROV), SUMMA, COMMENT, SQLNULL (DEP_LINK), SQLNULL (ACC_LINK), TYPE_PRINT, TAX, MIDDLEMAN, REQUEST,REQ_POST, ALLOW,ALLOW_POST, BASE, SQLNULL(K_DEP_LINK), MOVE_REST","DOCUMENTS_M15")'
GO

EXEC X_SET_PROP 'DOC_M15_REQUEST', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''KU_EMPL_PLACING'', oForm.ALIAS, ''NAME_EMPL, POST_NAME'', ''REQUEST,REQ_POST'', "", "", "", .T., 1, oForm, oObj)
'
GO

EXEC X_SET_PROP 'DOC_M15_ALLOW', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 (''KU_EMPL_PLACING'', oForm.ALIAS, ''NAME_EMPL, POST_NAME'', ''ALLOW, ALLOW_POST'', "", "", "", .T., 1, oForm, oObj)'
GO

GO

/****** Объект: Затребовал(должность)******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'DOC_M15_REQUEST_POST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'DOC_M15_REQUEST_POST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'DOC_M15_REQUEST_POST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'DOC_M15_REQUEST_POST')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DOC_M15_REQUEST_POST'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DOC_M15_REQUEST_POST')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_REQUEST_POST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_REQUEST_POST', 'Затребовал(должность)', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_REQUEST_POST', NAME = 'Затребовал(должность)', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_REQUEST_POST'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST_POST', 'TITLE', 'Затребовал(Должность)'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST_POST', 'CONTROLSOURCE', 'm.cAlias + ".REQ_POST"'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST_POST', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST_POST', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST_POST', 'TYPE_FIELD_DICT', 'VARCHAR (100)'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST_POST', 'SHORT_CODE_OBJ', 'REQ_POST'
GO
EXEC X_SET_PROP 'DOC_M15_REQUEST_POST', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".REQ_POST"'
GO

GO

/****** Объект: Разрешил(должность)******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'DOC_M15_ALLOW_POST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'DOC_M15_ALLOW_POST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'DOC_M15_ALLOW_POST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'DOC_M15_ALLOW_POST')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'DOC_M15_ALLOW_POST'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'DOC_M15_ALLOW_POST')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_M15_ALLOW_POST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_M15_ALLOW_POST', 'Разрешил(должность)', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_M15_ALLOW_POST', NAME = 'Разрешил(должность)', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_M15'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_M15_ALLOW_POST'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW_POST', 'TITLE', 'Разрешил(должность)'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW_POST', 'CONTROLSOURCE', 'm.cAlias + ".ALLOW_POST"'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW_POST', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW_POST', 'STORAGE', 'VALUE'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW_POST', 'TYPE_FIELD_DICT', 'VARCHAR (100)'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW_POST', 'SHORT_CODE_OBJ', 'ALLOW_POST'
GO
EXEC X_SET_PROP 'DOC_M15_ALLOW_POST', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ALLOW_POST"'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/

GO


EXECUTE BK_FORM_SAVE_DOCUMENT_ZB 'DOCUMENTS_M15', 'DOCUMENTS_M15', 0

GO


EXECUTE BK_FORM_VIEW_DOCUMENT_ZB 'DOCUMENTS_M15', 'DOCUMENTS_M15', 0, 0, 0

GO


GO


EXEC X_SET_PROP 'DOCUMENTS_M15', 'QUERY_REPORT', 'F0504204_M11.XLT#F0504205_M15.XLT'
GO
GO

update s_navigator 
	set name = 'Акт приема-передачи ОС'
	where code = 'DOCUMENTS_OS1'
GO

update s_objects 
	set name = 'Акт приема-передачи ОС'
	where code = 'DOCUMENTS_OS1'	
GO

update s_navigator 
	set name = 'Акт приема-передачи объектов НФА (52н)'
	where code = 'DOCUMENTS_OS1B_70N'
GO

update s_objects 
	set name = 'Акт приема-передачи объектов НФА (52н)'
	where code = 'DOCUMENTS_OS1B_70N'	
GO

EXEC X_SET_PROP 'DOCUMENTS_OS1B_70N', 'TITLE', 'Акт приема-передачи объектов НФА (52н)'
GO

EXEC X_SET_PROP 'DOCUMENTS_OS1', 'QUERY_REPORT', 'F0504101_OS1.XLT#F0504101_OS1.XLT'

GO

GO
EXEC X_SET_PROP 'DOCUMENTS_OS2_70N', 'QUERY_REPMAKER', 'KirRepMakerMultiSheet.xls'
GO

EXEC X_SET_PROP 'DOCUMENTS_OS2_70N', 'QUERY_ADD_MODULE', 'F0504102_OS2.BAS'
GO

EXEC X_SET_PROP 'DOCUMENTS_OS2_70N', 'QUERY_REPORT', 'F0504102_OS2.XLT'
GO

GO
EXEC X_SET_PROP 'DOCUMENTS_OS4_70N', 'QUERY_REPORT', 'F0504104_OS4.XLT#F0504105_OS4A.XLT'
GO

EXEC X_SET_PROP 'DOCUMENTS_OS4_70N', 'QUERY_ADD_MODULE', 'RepF0504104_OS4_70N.bas#RepF0504105_OS4A_70N.bas'
GO

EXEC X_SET_PROP 'DOCUMENTS_OS4_70N', 'QUERY_REPMAKER', 'KirRepMakerMultiSheet.xls#KirRepMakerMultiSheet.xls'
GO


EXEC X_SET_PROP 'DOC_OS4_PRINT', 'ROWSOURCE', '"ф.0504104,ф.0504105"'
GO

update G_PROV_VALUE
set VALUE = 'ф.0504104'
where OBJECT=(select link from S_OBJECTS where code = 'DOC_OS4_PRINT') and VALUE in ('OC-4Б','OC-4')
GO

update G_PROV_VALUE
set VALUE = 'ф.0504105'
where OBJECT=(select link from S_OBJECTS where code = 'DOC_OS4_PRINT') and VALUE =  ('OC-4A')
GO


GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='DOC_OS1_PRINT')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'DOC_OS1_PRINT', 'Печатная форма документа', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_OS1'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'DOC_OS1_PRINT', NAME = 'Печатная форма документа', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='DOCUMENTS_OS1'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='DOC_OS1_PRINT'
GO
EXEC X_SET_PROP 'DOC_OS1_PRINT', 'TITLE', 'Печатная форма документа'
GO
EXEC X_SET_PROP 'DOC_OS1_PRINT', 'CONTROLSOURCE', 'm.cAlias+".TYPE"'
GO
EXEC X_SET_PROP 'DOC_OS1_PRINT', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'DOC_OS1_PRINT', 'FIELD_IN_ALIAS', '0'
GO
EXEC X_SET_PROP 'DOC_OS1_PRINT', 'TYPE_FIELD_DICT', 'tinyint'
GO
EXEC X_SET_PROP 'DOC_OS1_PRINT', 'SHORT_CODE_OBJ', 'TYPE'
GO
EXEC X_SET_PROP 'DOC_OS1_PRINT', 'CONTROLSOURCE_EDIT', 'm.cAlias+".TYPE"'
GO
EXEC X_SET_PROP 'DOC_OS1_PRINT', 'CONTROL_NAME_EDIT', 'Acombobox1'
GO
EXEC X_SET_PROP 'DOC_OS1_PRINT', 'VISIBLE', '0'
GO


GO


EXEC X_SET_PROP 'DOCUMENTS_OS1B_70N', 'QUERY_REPORT', 'F0504101_OS1B.XLT'
GO

EXEC X_SET_PROP 'DOCUMENTS_OS1B_70N', 'QUERY_ADD_MODULE', 'RepOS1B_F0504101.bas'
GO

GO
/****** Объект: Дата окончания******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'EF_DATE_END')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'EF_DATE_END')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[OBJECT_VAR] V INNER JOIN [dbo].[S_OBJECTS] O ON V.[OBJECT] = O.[LINK] WHERE O.CODE = 'EF_DATE_END')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'EF_DATE_END')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'EF_DATE_END'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'EF_DATE_END')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='EF_DATE_END')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'EF_DATE_END', 'Дата окончания', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_FOT'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'EF_DATE_END', NAME = 'Дата окончания', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_FOT'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='EF_DATE_END'
GO
EXEC X_SET_PROP 'EF_DATE_END', 'TITLE', 'Дата окончания'
GO
EXEC X_SET_PROP 'EF_DATE_END', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'EF_DATE_END', 'CONTROLSOURCE', 'm.cAlias+".DATE_END"'
GO
EXEC X_SET_PROP 'EF_DATE_END', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'EF_DATE_END', 'SHORT_CODE_OBJ', 'DATE_END'
GO
EXEC X_SET_PROP 'EF_DATE_END', 'CONTROLSOURCE_EDIT', 'm.cAlias+".DATE_END"'
GO
EXEC X_SET_PROP 'EF_DATE_END', 'CONTROL_NAME_EDIT', 'atxt3'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
/*Добавление напоминания об истечении срока временного перемещения*/
if not exists(select * from remind_query where code = 'EMPL_TEMP_MOVE_TO_ORDER')
BEGIN
	insert into dbo.remind_query(code, name, sqlstr, prepare,task_enable,s_objects_code)
			values('EMPL_TEMP_MOVE_TO_ORDER','Истекает срок временного перемещения сотрудника',' SELECT IM.DATE_END2,RTRIM(EMPL.FIO) + '' Истекает срок временного перемещения.'',IM.ORDER_LINK FROM ITEM_MOVE IM LEFT JOIN ORDERS O ON IM.ORDER_LINK = O.LINK LEFT JOIN KU_EMPL_PLACING EMPL ON IM.EMPL_LINK = EMPL.LINK WHERE IM.ACTIVE = 1 AND O.DEP_LINK = (SELECT DEP_LINK FROM USER_DEP) AND (DATEDIFF(DAY,GETDATE(),IM.DATE_END2) >= 0 or DATEDIFF(DAY,GETDATE(),IM.DATE_END2) < 0)  and im.TYPE = 1 AND o.TYPE  = (SELECT TOP 1 code FROM ORDER_TYPES WHERE OBJ_CODE=''MOVES'') ','',5,'ORDERS_REESTR' ) 
END 
ELSE BEGIN
     	UPDATE remind_query
			set sqlstr = ' SELECT IM.DATE_END2,RTRIM(EMPL.FIO) + '' Истекает срок временного перемещения.'',IM.ORDER_LINK FROM ITEM_MOVE IM LEFT JOIN ORDERS O ON IM.ORDER_LINK = O.LINK LEFT JOIN KU_EMPL_PLACING EMPL ON IM.EMPL_LINK = EMPL.LINK WHERE IM.ACTIVE = 1 AND O.DEP_LINK = (SELECT DEP_LINK FROM USER_DEP) AND (DATEDIFF(DAY,GETDATE(),IM.DATE_END2) >= 0 or DATEDIFF(DAY,GETDATE(),IM.DATE_END2) < 0)  and im.TYPE = 1 AND o.TYPE  = (SELECT TOP 1 code FROM ORDER_TYPES WHERE OBJ_CODE=''MOVES'')'
			WHERE LTRIM(rtrim(code)) = 'EMPL_TEMP_MOVE_TO_ORDER' and LTRIM(rtrim(name)) = 'Истекает срок временного перемещения сотрудника' AND LTRIM(rtrim(s_objects_code)) = 'ORDERS_REESTR'

     END
	
GO


GO
/* R_SPR_CHET_710G_T */
IF NOT EXISTS (select * from dbo.sysobjects where id = object_id('dbo.R_SPR_CHET_710G_T') )
BEGIN 
	CREATE TABLE R_SPR_CHET_710G_T (CODE VARCHAR(100) ,[NAME] VARCHAR(250))
		 
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404120','Внутриведомственные расчеты по доходам от собственности');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404130','Внутриведомственные расчеты по доходам от оказания платных услуг');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404140','Внутриведомственные расчеты по доходам по суммам принудительного изъятия');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404173','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404180','Внутриведомственные расчеты по прочим доходам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404211','Внутриведомственные расчеты по заработной плате');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404212','Внутриведомственные расчеты по прочим выплатам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404213','Внутриведомственные расчеты по начислениям на выплаты по оплате труда');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404221','Внутриведомственные расчеты по услугам связи');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404222','Внутриведомственные расчеты по транспортным услугам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404223','Внутриведомственные расчеты по коммунальным услугам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404224','Внутриведомственные расчеты по арендной плате за пользование имуществом');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404225','Внутриведомственные расчеты по работам, услугам по содержанию имущества');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404226','Внутриведомственные расчеты по прочим работам, услугам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404231','Внутриведомственные расчеты по обслуживанию долговых обязательств учреждений с резидентами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404232','Внутриведомственные расчеты по обслуживанию долговых обязательств учреждений нерезидентами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404241','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404242','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных орг');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404252','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государ');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404253','Внутриведомственные расчеты по перечислениям международным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404262','Внутриведомственные расчеты по пособиям по социальной помощи населению');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404263','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управле');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404273','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230404290','Внутриведомственные расчеты по прочим расходам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230406730','Увеличение кредиторской задолженности по расчетам с прочими кредиторами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('230406830','Уменьшение кредиторской задолженности по расчетам с прочими кредиторами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240110120','Доходы от собственности');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240110130','Доходы от  оказания платных услуг');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240110140','Доходы от сумм принудительного изъятия');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240110151','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240110152','Доходы от поступлений от наднациональных организаций и правительств иностранных государств');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240110153','Доходы от поступления от международных финансовых организаций');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240110160','Доходы от страховых взносов на обязательное социальное страхование');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240110171','Доходы от переоценки активов');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240110172','Доходы от операций с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240110173','Чрезвычайные доходы от операций с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240110180','Прочие доходы');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120211','Расходы по заработной плате');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120212','Расходы по прочим выплатам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120213','Расходы на начисления на выплаты по оплате труда');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120221','Расходы на услуги связи');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120222','Расходы на транспортные услуги');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120223','Расходы на коммунальные услуги');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120224','Расходы на арендную плату за пользование имуществом');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120225','Расходы на работы, услуги по содержанию имущества');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120226','Расходы на прочие работы, услуги');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120231','Расходы на обслуживание внутреннего долга');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120232','Расходы на обслуживание внешнего государственного долга');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120241','Расходы на безвозмездные перечисления государственным и муниципальным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120242','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120251','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120252','Расходы на перечисления наднациональным организациям и правительствам иностранных государств');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120253','Расходы на перечисления международным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120261','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120262','Расходы на пособия по социальной помощи населению');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120263','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120271','Расходы на амортизацию основных средств и нематериальных активов');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120272','Расходование материальных запасов');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120273','Чрезвычайные расходы по операциям с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('240120290','Прочие расходы');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404120','Внутриведомственные расчеты по доходам от собственности');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404130','Внутриведомственные расчеты по доходам от оказания платных услуг');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404140','Внутриведомственные расчеты по доходам по суммам принудительного изъятия');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404173','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404180','Внутриведомственные расчеты по прочим доходам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404211','Внутриведомственные расчеты по заработной плате');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404212','Внутриведомственные расчеты по прочим выплатам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404213','Внутриведомственные расчеты по начислениям на выплаты по оплате труда');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404221','Внутриведомственные расчеты по услугам связи');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404222','Внутриведомственные расчеты по транспортным услугам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404223','Внутриведомственные расчеты по коммунальным услугам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404224','Внутриведомственные расчеты по арендной плате за пользование имуществом');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404225','Внутриведомственные расчеты по работам, услугам по содержанию имущества');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404226','Внутриведомственные расчеты по прочим работам, услугам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404231','Внутриведомственные расчеты по обслуживанию долговых обязательств учреждений с резидентами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404232','Внутриведомственные расчеты по обслуживанию долговых обязательств учреждений нерезидентами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404241','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404242','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных орг');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404252','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государ');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404253','Внутриведомственные расчеты по перечислениям международным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404262','Внутриведомственные расчеты по пособиям по социальной помощи населению');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404263','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управле');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404273','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430404290','Внутриведомственные расчеты по прочим расходам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430406730','Увеличение кредиторской задолженности по расчетам с прочими кредиторами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('430406830','Уменьшение кредиторской задолженности по расчетам с прочими кредиторами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440110120','Доходы от собственности');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440110130','Доходы от  оказания платных услуг');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440110140','Доходы от сумм принудительного изъятия');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440110151','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440110152','Доходы от поступлений от наднациональных организаций и правительств иностранных государств');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440110153','Доходы от поступления от международных финансовых организаций');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440110160','Доходы от страховых взносов на обязательное социальное страхование');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440110171','Доходы от переоценки активов');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440110172','Доходы от операций с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440110173','Чрезвычайные доходы от операций с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440110180','Прочие доходы');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120211','Расходы по заработной плате');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120212','Расходы по прочим выплатам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120213','Расходы на начисления на выплаты по оплате труда');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120221','Расходы на услуги связи');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120222','Расходы на транспортные услуги');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120223','Расходы на коммунальные услуги');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120224','Расходы на арендную плату за пользование имуществом');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120225','Расходы на работы, услуги по содержанию имущества');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120226','Расходы на прочие работы, услуги');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120231','Расходы на обслуживание внутреннего долга');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120232','Расходы на обслуживание внешнего государственного долга');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120241','Расходы на безвозмездные перечисления государственным и муниципальным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120242','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120251','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120252','Расходы на перечисления наднациональным организациям и правительствам иностранных государств');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120253','Расходы на перечисления международным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120261','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120262','Расходы на пособия по социальной помощи населению');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120263','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120271','Расходы на амортизацию основных средств и нематериальных активов');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120272','Расходование материальных запасов');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120273','Чрезвычайные расходы по операциям с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('440120290','Прочие расходы');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404120','Внутриведомственные расчеты по доходам от собственности');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404130','Внутриведомственные расчеты по доходам от оказания платных услуг');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404140','Внутриведомственные расчеты по доходам по суммам принудительного изъятия');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404173','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404180','Внутриведомственные расчеты по прочим доходам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404211','Внутриведомственные расчеты по заработной плате');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404212','Внутриведомственные расчеты по прочим выплатам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404213','Внутриведомственные расчеты по начислениям на выплаты по оплате труда');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404221','Внутриведомственные расчеты по услугам связи');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404222','Внутриведомственные расчеты по транспортным услугам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404223','Внутриведомственные расчеты по коммунальным услугам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404224','Внутриведомственные расчеты по арендной плате за пользование имуществом');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404225','Внутриведомственные расчеты по работам, услугам по содержанию имущества');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404226','Внутриведомственные расчеты по прочим работам, услугам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404231','Внутриведомственные расчеты по обслуживанию долговых обязательств учреждений с резидентами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404232','Внутриведомственные расчеты по обслуживанию долговых обязательств учреждений нерезидентами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404241','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404242','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных орг');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404252','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государ');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404253','Внутриведомственные расчеты по перечислениям международным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404262','Внутриведомственные расчеты по пособиям по социальной помощи населению');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404263','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управле');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404273','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530404290','Внутриведомственные расчеты по прочим расходам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530406730','Увеличение кредиторской задолженности по расчетам с прочими кредиторами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('530406830','Уменьшение кредиторской задолженности по расчетам с прочими кредиторами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540110120','Доходы от собственности');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540110130','Доходы от  оказания платных услуг');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540110140','Доходы от сумм принудительного изъятия');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540110151','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540110152','Доходы от поступлений от наднациональных организаций и правительств иностранных государств');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540110153','Доходы от поступления от международных финансовых организаций');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540110160','Доходы от страховых взносов на обязательное социальное страхование');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540110171','Доходы от переоценки активов');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540110172','Доходы от операций с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540110173','Чрезвычайные доходы от операций с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540110180','Прочие доходы');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120211','Расходы по заработной плате');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120212','Расходы по прочим выплатам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120213','Расходы на начисления на выплаты по оплате труда');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120221','Расходы на услуги связи');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120222','Расходы на транспортные услуги');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120223','Расходы на коммунальные услуги');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120224','Расходы на арендную плату за пользование имуществом');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120225','Расходы на работы, услуги по содержанию имущества');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120226','Расходы на прочие работы, услуги');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120231','Расходы на обслуживание внутреннего долга');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120232','Расходы на обслуживание внешнего государственного долга');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120241','Расходы на безвозмездные перечисления государственным и муниципальным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120242','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120251','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120252','Расходы на перечисления наднациональным организациям и правительствам иностранных государств');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120253','Расходы на перечисления международным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120261','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120262','Расходы на пособия по социальной помощи населению');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120263','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120271','Расходы на амортизацию основных средств и нематериальных активов');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120272','Расходование материальных запасов');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120273','Чрезвычайные расходы по операциям с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('540120290','Прочие расходы');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404120','Внутриведомственные расчеты по доходам от собственности');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404130','Внутриведомственные расчеты по доходам от оказания платных услуг');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404140','Внутриведомственные расчеты по доходам по суммам принудительного изъятия');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404173','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404180','Внутриведомственные расчеты по прочим доходам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404211','Внутриведомственные расчеты по заработной плате');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404212','Внутриведомственные расчеты по прочим выплатам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404213','Внутриведомственные расчеты по начислениям на выплаты по оплате труда');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404221','Внутриведомственные расчеты по услугам связи');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404222','Внутриведомственные расчеты по транспортным услугам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404223','Внутриведомственные расчеты по коммунальным услугам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404224','Внутриведомственные расчеты по арендной плате за пользование имуществом');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404225','Внутриведомственные расчеты по работам, услугам по содержанию имущества');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404226','Внутриведомственные расчеты по прочим работам, услугам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404231','Внутриведомственные расчеты по обслуживанию долговых обязательств учреждений с резидентами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404232','Внутриведомственные расчеты по обслуживанию долговых обязательств учреждений нерезидентами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404241','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404242','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных орг');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404252','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государ');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404253','Внутриведомственные расчеты по перечислениям международным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404262','Внутриведомственные расчеты по пособиям по социальной помощи населению');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404263','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управле');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404273','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630404290','Внутриведомственные расчеты по прочим расходам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630406730','Увеличение кредиторской задолженности по расчетам с прочими кредиторами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('630406830','Уменьшение кредиторской задолженности по расчетам с прочими кредиторами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640110120','Доходы от собственности');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640110130','Доходы от  оказания платных услуг');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640110140','Доходы от сумм принудительного изъятия');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640110151','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640110152','Доходы от поступлений от наднациональных организаций и правительств иностранных государств');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640110153','Доходы от поступления от международных финансовых организаций');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640110160','Доходы от страховых взносов на обязательное социальное страхование');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640110171','Доходы от переоценки активов');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640110172','Доходы от операций с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640110173','Чрезвычайные доходы от операций с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640110180','Прочие доходы');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120211','Расходы по заработной плате');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120212','Расходы по прочим выплатам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120213','Расходы на начисления на выплаты по оплате труда');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120221','Расходы на услуги связи');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120222','Расходы на транспортные услуги');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120223','Расходы на коммунальные услуги');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120224','Расходы на арендную плату за пользование имуществом');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120225','Расходы на работы, услуги по содержанию имущества');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120226','Расходы на прочие работы, услуги');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120231','Расходы на обслуживание внутреннего долга');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120232','Расходы на обслуживание внешнего государственного долга');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120241','Расходы на безвозмездные перечисления государственным и муниципальным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120242','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120251','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120252','Расходы на перечисления наднациональным организациям и правительствам иностранных государств');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120253','Расходы на перечисления международным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120261','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120262','Расходы на пособия по социальной помощи населению');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120263','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120271','Расходы на амортизацию основных средств и нематериальных активов');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120272','Расходование материальных запасов');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120273','Чрезвычайные расходы по операциям с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('640120290','Прочие расходы');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404120','Внутриведомственные расчеты по доходам от собственности');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404130','Внутриведомственные расчеты по доходам от оказания платных услуг');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404140','Внутриведомственные расчеты по доходам по суммам принудительного изъятия');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404173','Внутриведомственные расчеты по чрезвычайным доходам от операций с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404180','Внутриведомственные расчеты по прочим доходам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404211','Внутриведомственные расчеты по заработной плате');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404212','Внутриведомственные расчеты по прочим выплатам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404213','Внутриведомственные расчеты по начислениям на выплаты по оплате труда');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404221','Внутриведомственные расчеты по услугам связи');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404222','Внутриведомственные расчеты по транспортным услугам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404223','Внутриведомственные расчеты по коммунальным услугам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404224','Внутриведомственные расчеты по арендной плате за пользование имуществом');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404225','Внутриведомственные расчеты по работам, услугам по содержанию имущества');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404226','Внутриведомственные расчеты по прочим работам, услугам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404231','Внутриведомственные расчеты по обслуживанию долговых обязательств учреждений с резидентами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404232','Внутриведомственные расчеты по обслуживанию долговых обязательств учреждений нерезидентами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404241','Внутриведомственные расчеты по безвозмездным перечислениям государственным и муниципальным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404242','Внутриведомственные расчеты по безвозмездным перечислениям, за исключением государственных и муниципальных орг');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404252','Внутриведомственные расчеты по перечислениям наднациональным организациям и правительствам иностранных государ');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404253','Внутриведомственные расчеты по перечислениям международным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404262','Внутриведомственные расчеты по пособиям по социальной помощи населению');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404263','Внутриведомственные расчеты по пенсиям, пособиям, выплачиваемым организациями сектора государственного управле');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404273','Внутриведомственные расчеты по чрезвычайным расходам по операциям с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730404290','Внутриведомственные расчеты по прочим расходам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730406730','Увеличение кредиторской задолженности по расчетам с прочими кредиторами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('730406830','Уменьшение кредиторской задолженности по расчетам с прочими кредиторами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740110120','Доходы от собственности');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740110130','Доходы от  оказания платных услуг');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740110140','Доходы от сумм принудительного изъятия');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740110151','Доходы от поступлений от других бюджетов бюджетной системы Российской Федерации');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740110152','Доходы от поступлений от наднациональных организаций и правительств иностранных государств');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740110153','Доходы от поступления от международных финансовых организаций');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740110160','Доходы от страховых взносов на обязательное социальное страхование');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740110171','Доходы от переоценки активов');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740110172','Доходы от операций с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740110173','Чрезвычайные доходы от операций с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740110180','Прочие доходы');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120211','Расходы по заработной плате');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120212','Расходы по прочим выплатам');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120213','Расходы на начисления на выплаты по оплате труда');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120221','Расходы на услуги связи');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120222','Расходы на транспортные услуги');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120223','Расходы на коммунальные услуги');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120224','Расходы на арендную плату за пользование имуществом');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120225','Расходы на работы, услуги по содержанию имущества');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120226','Расходы на прочие работы, услуги');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120231','Расходы на обслуживание внутреннего долга');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120232','Расходы на обслуживание внешнего государственного долга');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120241','Расходы на безвозмездные перечисления государственным и муниципальным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120242','Расходы на безвозмездные перечисления организациям, за исключением государственных и муниципальных организаций');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120251','Расходы на перечисления другим бюджетам бюджетной системы Российской Федерации');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120252','Расходы на перечисления наднациональным организациям и правительствам иностранных государств');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120253','Расходы на перечисления международным организациям');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120261','Расходы на пенсии, пособия и выплаты по пенсионному, социальному и медицинскому страхованию населения');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120262','Расходы на пособия по социальной помощи населению');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120263','Расходы на пенсии, пособия, выплачиваемые организациями сектора государственного управления');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120271','Расходы на амортизацию основных средств и нематериальных активов');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120272','Расходование материальных запасов');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120273','Чрезвычайные расходы по операциям с активами');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('740120290','Прочие расходы');
	INSERT INTO [R_SPR_CHET_710G_T] ([CODE],[NAME])
	VALUES ('888888888','Итого');
	
	
	
	IF EXISTS ( SELECT * FROM  DBO.[REPORT_KBK] WHERE CODE_FORM = 'R_SPR_CHET_710'  AND  CODE = SUBSTRING(CODE, 1, 6 ) + '000') 
		DELETE FROM DBO.[REPORT_KBK] WHERE CODE_FORM = 'R_SPR_CHET_710'  AND  CODE = SUBSTRING(CODE, 1, 6 ) + '000'


	if exists( SELECT * FROM DBO.R_SPR_CHET_710G_T WHERE  Code NOT in (SELECT code FROM dbo.[REPORT_KBK]  where CODE_FORM = 'R_SPR_CHET_710' ) )
		INSERT INTO DBO.[REPORT_KBK] (Code, Code_Form, Childrens , NAME , PROPERTY, add_info, orders, LONG_NAME, begin_date)
		SELECT CODE, CODE_FORM = 'R_SPR_CHET_710' , CHILDRENS = 1 , NAME , 0 , '', 0, '', '19000101'
		FROM dbo.R_SPR_CHET_710G_T
		WHERE CODE NOT IN (SELECT CODE FROM DBO.[REPORT_KBK] WHERE CODE_FORM = 'R_SPR_CHET_710')
	
 
 	DROP TABLE R_SPR_CHET_710G_T	
		
	
END	

GO



GO
IF EXISTS (SELECT * FROM report_kbk WHERE [Code_Form]='send' AND code LIKE '%0503128%' AND ltrim(rtrim(Name)) = '999|99999999999999999|' AND add_info = '999|***|*****************|')
BEGIN 
		UPDATE  report_kbk
		SET add_info = '999|*****************|'
	WHERE [Code_Form]='send' AND code LIKE '%0503128%' AND ltrim(rtrim(Name)) = '999|99999999999999999|' AND add_info = '999|***|*****************|'
end	

GO




GO
-- Отчет "Приказ о предоставлении отпуска (форма № Т6, форма № Т6а)"
-- Сгенерировано скриптом scriptObjectVar 'FORM_T6k'

/*** Сам отчет ***/

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= 'FORM_T6k'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'FORM_T6k'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Приказ о предоставлении денежной компенсации за неиспользованный отпуск (форма № Т6к)',NULL, 
	(Select link from object_var where code = 'KADRY_SQL_CATALOG'),
	'FORM_T6k',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'FORM_T6k') 
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'EXEC KJ_FORM_T6 @nSel_Spr1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#FORM_T6'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(@nCheck1 = 0,"FORM-T6K.XLT",IIF(@nCheck1 = 1,"FORM-T6A.XLT",""))'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #FORM_T6
	@nSel_Spr1 int	/* Ссылка на приказ */,
	@nCheck1 int	/* Тип приказа */
AS
BEGIN

EXEC KJ_FORM_T6 @nSel_Spr1

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	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 = 'FORM_T6k') 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 = 'FORM_T6k'),
	PROPERTY= (Select LINK from s_property where code = 'SQUERY_NO_SHOW'),
	VALUE= '1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'FORM_T6k') 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 = 'FORM_T6k'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'FORM_T6k_GROUP' 
		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 = 'FORM_T6k'),
		'FORM_T6k_GROUP',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'FORM_T6k_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 = 'FORM_T6k_GROUP'),
					'FORM_T6k_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 = 'FORM_T6k_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_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 = 'FORM_T6k_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_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 = 'FORM_T6k_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_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 = 'FORM_T6k_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_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 = 'FORM_T6k_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_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 = 'FORM_T6k_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_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 = 'FORM_T6k_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_MAIN_PARAM'),
							(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 = 'FORM_T6k_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_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 = 'FORM_T6k_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_MAIN_PARAM'),
							(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 = 'FORM_T6k_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_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 = 'FORM_T6k_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_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 = 'FORM_T6k_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_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 = 'FORM_T6k_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_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 = 'FORM_T6k_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'FORM_T6k_PARAM1' 
					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'),
					'Тип приказа',3, 
					(Select link from object_var where code = 'FORM_T6k_GROUP'),
					'FORM_T6k_PARAM1',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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(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 = 'FORM_T6k_PARAM1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'FORM_T6k_PARAM1'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO


GO
EXEC X_SET_PROP 'GR_GOS_NAME', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("GR_GOS",oForm.ALIAS,"LINK,code, NAME", "GR_GOS_LINK,gr_gos_code, GR_GOS_NAME", "", "", "", .T., 1, oForm, oObj)'
GO

GO
IF not exists(select * from dbo.formula_bridge where name = 'РСВ1_15_ПФР_УСТАНОВКА' and PROC_NAME = 'SA_RSV_1_15_PFR_PREPARE')
begin
  	
  IF not exists(select * from dbo.DICTION where name = 'РСВ1_15_ПФР_УСТАНОВКА')
  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_15_ПФР_УСТАНОВКА', @linkObjF, NULL, '17530101','99991231')

		set @LinkOBJ = (select link from dbo.DICTION where name = 'РСВ1_15_ПФР_УСТАНОВКА')
		
		
		-- insert порядка для формулы в таблицу dbo.DICTION_APP 
		IF not exists(select * from dbo.DICTION_APP where link_up = (select link from dbo.DICTION where name = 'РСВ1_15_ПФР_УСТАНОВКА') 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_15_ПФР_УСТАНОВКА') 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_15_PFR_PREPARE')		
 
		end
			
  end	
 
end   

GO
/****** Объект: Праздничные дни******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'KD_HOLIDAYS')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'KD_HOLIDAYS')
	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 = 'KD_HOLIDAYS')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'KD_HOLIDAYS')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'KD_HOLIDAYS'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'KD_HOLIDAYS')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KD_HOLIDAYS', 'Праздничные дни', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICT_SAL_KADR'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),1,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KD_HOLIDAYS', NAME = 'Праздничные дни', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICT_SAL_KADR'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='KD_HOLIDAYS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_MARKER_HD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_MARKER_HD', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_MARKER_HD', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_MARKER_HD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_ORD_HD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_ORD_HD', 'Порядок', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_ORD_HD', NAME = 'Порядок', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_ORD_HD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DATE_HD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DATE_HD', 'Дата', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DATE_HD', NAME = 'Дата', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DATE_HD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_NAME_HD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_NAME_HD', 'Наименование', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_NAME_HD', NAME = 'Наименование', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_NAME_HD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DAY_HD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DAY_HD', 'День', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DAY_HD', NAME = 'День', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DAY_HD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_MONTH_HD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_MONTH_HD', 'Месяц', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_MONTH_HD', NAME = 'Месяц', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_MONTH_HD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_REF_LINK_TYP_DAY_HOL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_REF_LINK_TYP_DAY_HOL', 'Ссылка на тип дня', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_REF_LINK_TYP_DAY_HOL', NAME = 'Ссылка на тип дня', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_REF_LINK_TYP_DAY_HOL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_REF_NAME_TYP_DAY_HOL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_REF_NAME_TYP_DAY_HOL', 'Наименование типа дня', 8, (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_REF_NAME_TYP_DAY_HOL', NAME = 'Наименование типа дня', ORDERS = '8', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_REF_NAME_TYP_DAY_HOL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_TYPE_PRAZD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_TYPE_PRAZD', 'Вид', 9, (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_TYPE_PRAZD', NAME = 'Вид', ORDERS = '9', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_TYPE_PRAZD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_TYPE_PRAZD_STR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_TYPE_PRAZD_STR', 'Вид', 10, (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_TYPE_PRAZD_STR', NAME = 'Вид', ORDERS = '10', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_TYPE_PRAZD_STR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DAY1_HD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DAY1_HD', 'День', 11, (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DAY1_HD', NAME = 'День', ORDERS = '11', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DAY1_HD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_MONTH1_HD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_MONTH1_HD', 'Месяц', 12, (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_MONTH1_HD', NAME = 'Месяц', ORDERS = '12', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_MONTH1_HD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_YEAR_HD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_YEAR_HD', 'Год', 13, (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_YEAR_HD', NAME = 'Год', ORDERS = '13', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_YEAR_HD'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COLUMN_DATE1_HD')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COLUMN_DATE1_HD', 'Дата', 14, (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COLUMN_DATE1_HD', NAME = 'Дата', ORDERS = '14', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_HOLIDAYS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COLUMN_DATE1_HD'
GO
EXEC X_SET_PROP 'KD_HOLIDAYS', 'TITLE', 'Праздничные дни'
GO
EXEC X_SET_PROP 'KD_HOLIDAYS', 'INIT_OBJECT_METHOD', 'X_SPISOK("KD_HOLIDAYS")'
GO
EXEC X_SET_PROP 'KD_HOLIDAYS', 'REMOVE_OBJECT_METHOD', 'I_DELETE_RECORDS(m.oForm.Alias, "KD_HOLIDAYS", "KD_HOLIDAYS_DELETE", 4, .F., .F.)'
GO
EXEC X_SET_PROP 'KD_HOLIDAYS', 'SAVE_OBJECT_METHOD', 'X_SAVE(''KD_HOLIDAYS_SAVE'', m.cAlias," NAME,DAY, MONTH,SQLNULL(DATE),SQLNULL(TD_LINK),TYPE_HOL,SQLNULL(DAY1), SQLNULL(MONTH1),SQLNULL(DATE1)","KD_HOLIDAYS")'
GO
EXEC X_SET_PROP 'KD_HOLIDAYS', 'EDIT_OBJECT_METHOD', 'salary_brow(''KD_HOLIDAYS'')'
GO
EXEC X_SET_PROP 'KD_HOLIDAYS', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''KD_HOLIDAYS'')'
GO
EXEC X_SET_PROP 'KD_HOLIDAYS', 'SELECT_RECORDS_METHOD_EDIT', 'X_SELECT_DICTIONS(''KD_HOLIDAYS'')'
GO
EXEC X_SET_PROP 'KD_HOLIDAYS', 'SERVER_TABLE_NAME', 'KD_HOLIDAYS'
GO
EXEC X_SET_PROP 'KD_HOLIDAYS', 'HELP_TOPIC', '6'
GO
EXEC X_SET_PROP 'KD_HOLIDAYS', 'PREPARE_NEW_RECORD', 'x_new_diction_record(m.OBJ_CODE, m.cAlias)'
GO
EXEC X_SET_PROP 'KD_HOLIDAYS', 'OPERATION_MASK', '24'
GO
EXEC X_SET_PROP 'KD_HOLIDAYS', 'EDIT_OBJECT_METHOD_SQL', 'KU_EDIT_OBJECT_METHOD @cObject = ''KD_HOLIDAYS'''
GO
EXEC X_SET_PROP 'KD_HOLIDAYS', 'SELECT_RECORDS_METHOD_SQL', 'select [checked] =0, name, day, month, date,td_name, link from kd_holidays'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_HD', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_HD', 'CONTROLSOURCE', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_HD', 'CONTROLSOURCE_EDIT', 'm.cAlias+".CHECKED"'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_HD', 'ASPTYPE', 'checkbox'
GO
EXEC X_SET_PROP 'COLUMN_MARKER_HD', 'FIELD_DATA', 'checked'
GO
EXEC X_SET_PROP 'COLUMN_ORD_HD', 'FIELD_IN_ALIAS', '1'
GO
EXEC X_SET_PROP 'COLUMN_ORD_HD', 'TITLE', 'Порядок'
GO
EXEC X_SET_PROP 'COLUMN_ORD_HD', 'CONTROLSOURCE', 'm.cAlias + ".ORD"'
GO
EXEC X_SET_PROP 'COLUMN_ORD_HD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_ORD_HD', 'VISIBLE', '0'
GO
EXEC X_SET_PROP 'COLUMN_ORD_HD', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'COLUMN_ORD_HD', 'SHORT_CODE_OBJ', 'DAY'
GO
EXEC X_SET_PROP 'COLUMN_ORD_HD', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".ORD"'
GO
EXEC X_SET_PROP 'COLUMN_ORD_HD', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'COLUMN_ORD_HD', 'ATTRIBUTES', 'style="Z-INDEX: 107; LEFT: 80px; POSITION: absolute; TOP: 24px"
Width="184px"'
GO
EXEC X_SET_PROP 'COLUMN_ORD_HD', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 24px"'
GO
EXEC X_SET_PROP 'COLUMN_ORD_HD', 'FIELD_ALIAS', 'KD_HOLIDAYS'
GO
EXEC X_SET_PROP 'COLUMN_ORD_HD', 'FIELD_DATA', 'day'
GO
EXEC X_SET_PROP 'COLUMN_DATE_HD', 'TITLE', 'Дата'
GO
EXEC X_SET_PROP 'COLUMN_DATE_HD', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_DATE_HD', 'CONTROLSOURCE', 'm.cAlias + ".DATE"'
GO
EXEC X_SET_PROP 'COLUMN_DATE_HD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DATE_HD', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_DATE_HD', 'STORAGE', 'DATE'
GO
EXEC X_SET_PROP 'COLUMN_DATE_HD', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'COLUMN_DATE_HD', 'SHORT_CODE_OBJ', 'DATE'
GO
EXEC X_SET_PROP 'COLUMN_DATE_HD', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE"'
GO
EXEC X_SET_PROP 'COLUMN_DATE_HD', 'CONTROL_NAME_EDIT', 'ASeldate1'
GO
EXEC X_SET_PROP 'COLUMN_DATE_HD', 'ASPTYPE', 'WebDateChooser'
GO
EXEC X_SET_PROP 'COLUMN_DATE_HD', 'ATTRIBUTES', 'style="Z-INDEX: 103; LEFT: 140px; POSITION: absolute; TOP: 50px"
Width="170px"'
GO
EXEC X_SET_PROP 'COLUMN_DATE_HD', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 103; LEFT: 16px; POSITION: absolute; TOP: 50px"'
GO
EXEC X_SET_PROP 'COLUMN_DATE_HD', 'FIELD_ALIAS', 'KD_HOLIDAYS'
GO
EXEC X_SET_PROP 'COLUMN_DATE_HD', 'FIELD_DATA', 'date'
GO
EXEC X_SET_PROP 'COLUMN_NAME_HD', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'COLUMN_NAME_HD', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'COLUMN_NAME_HD', 'CONTROLSOURCE', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_HD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_NAME_HD', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_NAME_HD', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'COLUMN_NAME_HD', 'SHORT_CODE_OBJ', 'NAME'
GO
EXEC X_SET_PROP 'COLUMN_NAME_HD', 'CONTROLSOURCE_EDIT', 'm.cAlias+".NAME"'
GO
EXEC X_SET_PROP 'COLUMN_NAME_HD', 'FIELD_ALIAS', 'KD_HOLIDAYS'
GO
EXEC X_SET_PROP 'COLUMN_NAME_HD', 'FIELD_DATA', 'name'
GO
EXEC X_SET_PROP 'COLUMN_DAY_HD', 'TITLE', 'День'
GO
EXEC X_SET_PROP 'COLUMN_DAY_HD', 'CONTROLSOURCE', 'm.cAlias + ".DAY"'
GO
EXEC X_SET_PROP 'COLUMN_DAY_HD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DAY_HD', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_DAY_HD', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'COLUMN_DAY_HD', 'SHORT_CODE_OBJ', 'DAY'
GO
EXEC X_SET_PROP 'COLUMN_DAY_HD', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DAY"'
GO
EXEC X_SET_PROP 'COLUMN_DAY_HD', 'CONTROL_NAME_EDIT', 'Aspinner1'
GO
EXEC X_SET_PROP 'COLUMN_DAY_HD', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'COLUMN_DAY_HD', 'ATTRIBUTES', 'style="Z-INDEX: 107; LEFT: 80px; POSITION: absolute; TOP: 24px"
Width="184px"'
GO
EXEC X_SET_PROP 'COLUMN_DAY_HD', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 24px"'
GO
EXEC X_SET_PROP 'COLUMN_DAY_HD', 'FIELD_ALIAS', 'KD_HOLIDAYS'
GO
EXEC X_SET_PROP 'COLUMN_DAY_HD', 'FIELD_DATA', 'day'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_HD', 'TITLE', 'Месяц'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_HD', 'CONTROLSOURCE', 'm.cAlias + ".MONTH"'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_HD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_HD', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_HD', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_HD', 'SHORT_CODE_OBJ', 'MONTH'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_HD', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".MONTH"'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_HD', 'CONTROL_NAME_EDIT', 'Acmbmonth2'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_HD', 'ASPTYPE', 'DropDownList'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_HD', 'ATTRIBUTES', 'style="Z-INDEX: 104; LEFT: 352px; POSITION: absolute; TOP: 24px"
Width="100px"'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_HD', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 102; LEFT: 288px; POSITION: absolute; TOP: 24px"'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_HD', 'DICTIONARY', 'Январь#1@Февраль#2@Март#3@Апрель#4@Май#5@Июнь#6@Июль#7@Август#8@Сентябрь#9@Октябрь#10@Ноябрь#11@Декабрь#12'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_HD', 'FIELD_ALIAS', 'KD_HOLIDAYS'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_HD', 'FIELD_DATA', 'month'
GO
EXEC X_SET_PROP 'COLUMN_MONTH_HD', 'FIELD_KEY', 'month'
GO
EXEC X_SET_PROP 'COLUMN_REF_LINK_TYP_DAY_HOL', 'VISIBLE', '32'
GO
EXEC X_SET_PROP 'COLUMN_REF_LINK_TYP_DAY_HOL', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'COLUMN_REF_LINK_TYP_DAY_HOL', 'SHORT_CODE_OBJ', 'TD_LINK'
GO
EXEC X_SET_PROP 'COLUMN_REF_LINK_TYP_DAY_HOL', 'ASPTYPE', 'HiddenControl'
GO
EXEC X_SET_PROP 'COLUMN_REF_LINK_TYP_DAY_HOL', 'FIELD_ALIAS', 'KD_HOLIDAYS'
GO
EXEC X_SET_PROP 'COLUMN_REF_LINK_TYP_DAY_HOL', 'FIELD_DATA', 'TD_LINK'
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'TITLE', 'Тип дня'
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("KD_TYP_DAYS",oForm.ALIAS,"LINK, NAME", "TD_LINK,TD_NAME", "", "", "", .T., 1, oForm, oObj)'
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'CONTROLSOURCE', 'm.cAlias+''.TD_NAME'''
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'TYPE_FIELD_DICT', 'VARCHAR(60)'
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'SHORT_CODE_OBJ', 'TD_NAME'
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'CONTROLSOURCE_EDIT', 'm.cAlias+''.TD_NAME'''
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'CONTROL_NAME_EDIT', 'ASel_Spr1'
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'ASPTYPE', 'WebTextBox'
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'ATTRIBUTES', 'style="Z-INDEX: 106; LEFT: 80px; POSITION: absolute; TOP: 72px"
Width="372px"'
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 103; LEFT: 16px; POSITION: absolute; TOP: 72px"'
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'DICTIONARY', 'KD_TYP_DAYS'
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'DICTIONARY_COLUMNS_LIST', 'COLUMN_REF_NAME_TYP_DAY_HOL,COLUMN_REF_LINK_TYP_DAY_HOL'
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'DICTIONARY_FIELDS_LIST', 'name,link'
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'FIELD_ALIAS', 'KD_HOLIDAYS'
GO
EXEC X_SET_PROP 'COLUMN_REF_NAME_TYP_DAY_HOL', 'FIELD_DATA', 'td_name'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD', 'TITLE', 'Вид'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD', 'CONTROLSOURCE', 'm.cAlias + ".TYPE_HOL"'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD', 'ROWSOURCE', '''Нерабочий праздничный  в РФ,Предпраздчный,Дополнительный день отдыха'''
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TYPE_HOL"'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD', 'CONTROL_NAME_EDIT', 'Acombobox1'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD', 'ASPTYPE', 'DropDownList'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD', 'ATTRIBUTES', 'style="Z-INDEX: 104; LEFT: 352px; POSITION: absolute; TOP: 24px"
Width="100px"'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 102; LEFT: 288px; POSITION: absolute; TOP: 24px"'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD', 'FIELD_ALIAS', 'KD_HOLIDAYS'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD_STR', 'TITLE', 'Вид'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD_STR', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD_STR', 'CONTROLSOURCE', 'm.cAlias + ".TYPE_HOL_STR"'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD_STR', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD_STR', 'ROWSOURCE', 'Нерабочий праздничный  в РФ,Предпраздчный,Дополнительный день отдыха'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD_STR', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD_STR', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".TYPE_HOL_STR"'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD_STR', 'ASPTYPE', 'DropDownList'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD_STR', 'ATTRIBUTES', 'style="Z-INDEX: 104; LEFT: 352px; POSITION: absolute; TOP: 24px"
Width="100px"'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD_STR', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 102; LEFT: 288px; POSITION: absolute; TOP: 24px"'
GO
EXEC X_SET_PROP 'COLUMN_TYPE_PRAZD_STR', 'FIELD_ALIAS', 'KD_HOLIDAYS'
GO
EXEC X_SET_PROP 'COLUMN_DAY1_HD', 'TITLE', 'День'
GO
EXEC X_SET_PROP 'COLUMN_DAY1_HD', 'CONTROLSOURCE', 'm.cAlias + ".DAY1"'
GO
EXEC X_SET_PROP 'COLUMN_DAY1_HD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DAY1_HD', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'COLUMN_DAY1_HD', 'SHORT_CODE_OBJ', 'DAY'
GO
EXEC X_SET_PROP 'COLUMN_DAY1_HD', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DAY1"'
GO
EXEC X_SET_PROP 'COLUMN_DAY1_HD', 'CONTROL_NAME_EDIT', 'Aspinner2'
GO
EXEC X_SET_PROP 'COLUMN_DAY1_HD', 'COMMENTARY', 'Дата, с которой перенесен день'
GO
EXEC X_SET_PROP 'COLUMN_DAY1_HD', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'COLUMN_DAY1_HD', 'ATTRIBUTES', 'style="Z-INDEX: 107; LEFT: 80px; POSITION: absolute; TOP: 24px"
Width="184px"'
GO
EXEC X_SET_PROP 'COLUMN_DAY1_HD', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 24px"'
GO
EXEC X_SET_PROP 'COLUMN_DAY1_HD', 'FIELD_ALIAS', 'KD_HOLIDAYS'
GO
EXEC X_SET_PROP 'COLUMN_DAY1_HD', 'FIELD_DATA', 'day'
GO
EXEC X_SET_PROP 'COLUMN_MONTH1_HD', 'TITLE', 'Месяц'
GO
EXEC X_SET_PROP 'COLUMN_MONTH1_HD', 'CONTROLSOURCE', 'm.cAlias + ".MONTH1"'
GO
EXEC X_SET_PROP 'COLUMN_MONTH1_HD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_MONTH1_HD', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'COLUMN_MONTH1_HD', 'SHORT_CODE_OBJ', 'MONTH'
GO
EXEC X_SET_PROP 'COLUMN_MONTH1_HD', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".MONTH1"'
GO
EXEC X_SET_PROP 'COLUMN_MONTH1_HD', 'CONTROL_NAME_EDIT', 'Acmbmonth1'
GO
EXEC X_SET_PROP 'COLUMN_MONTH1_HD', 'COMMENTARY', 'Дата, с которой перенесен день'
GO
EXEC X_SET_PROP 'COLUMN_MONTH1_HD', 'ASPTYPE', 'DropDownList'
GO
EXEC X_SET_PROP 'COLUMN_MONTH1_HD', 'ATTRIBUTES', 'style="Z-INDEX: 104; LEFT: 352px; POSITION: absolute; TOP: 24px"
Width="100px"'
GO
EXEC X_SET_PROP 'COLUMN_MONTH1_HD', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 102; LEFT: 288px; POSITION: absolute; TOP: 24px"'
GO
EXEC X_SET_PROP 'COLUMN_MONTH1_HD', 'DICTIONARY', 'Январь#1@Февраль#2@Март#3@Апрель#4@Май#5@Июнь#6@Июль#7@Август#8@Сентябрь#9@Октябрь#10@Ноябрь#11@Декабрь#12'
GO
EXEC X_SET_PROP 'COLUMN_MONTH1_HD', 'FIELD_ALIAS', 'KD_HOLIDAYS'
GO
EXEC X_SET_PROP 'COLUMN_MONTH1_HD', 'FIELD_DATA', 'month'
GO
EXEC X_SET_PROP 'COLUMN_MONTH1_HD', 'FIELD_KEY', 'month'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_HD', 'TITLE', 'Год'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_HD', 'CONTROLSOURCE', 'm.cAlias + ".YEAR"'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_HD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_HD', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_HD', 'SHORT_CODE_OBJ', 'YEAR'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_HD', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".YEAR"'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_HD', 'CONTROL_NAME_EDIT', 'Aspinner3'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_HD', 'ASPTYPE', 'TextBox'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_HD', 'ATTRIBUTES', 'style="Z-INDEX: 107; LEFT: 80px; POSITION: absolute; TOP: 24px"
Width="184px"'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_HD', 'LABEL_ATTRIBUTES', ' style="Z-INDEX: 101; LEFT: 16px; POSITION: absolute; TOP: 24px"'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_HD', 'FIELD_ALIAS', 'KD_HOLIDAYS'
GO
EXEC X_SET_PROP 'COLUMN_YEAR_HD', 'FIELD_DATA', 'YEAR'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_HD', 'TITLE', 'Дата переноса'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_HD', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_HD', 'CONTROLSOURCE', 'm.cAlias + ".DATE1"'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_HD', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_HD', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_HD', 'STORAGE', 'DATE1'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_HD', 'TYPE_FIELD_DICT', 'DATETIME'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_HD', 'SHORT_CODE_OBJ', 'DATE1'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_HD', 'CONTROLSOURCE_EDIT', 'm.cAlias + ".DATE1"'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_HD', 'CONTROL_NAME_EDIT', 'ASeldate2'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_HD', 'COMMENTARY', 'Дата,с которой перенесен день'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_HD', 'ASPTYPE', 'WebDateChooser'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_HD', 'ATTRIBUTES', 'style="Z-INDEX: 103; LEFT: 140px; POSITION: absolute; TOP: 50px"
Width="170px"'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_HD', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 103; LEFT: 16px; POSITION: absolute; TOP: 50px"'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_HD', 'FIELD_ALIAS', 'KD_HOLIDAYS'
GO
EXEC X_SET_PROP 'COLUMN_DATE1_HD', 'FIELD_DATA', 'date1'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'KD_HOLIDAYS', 'Кадры-КС (чтение)', 5,26
GO
EXEC DBO.W_SPERM_WRITE 'KD_HOLIDAYS', 'Начальник отдела кадров', 127,0
GO
EXEC DBO.W_SPERM_WRITE 'KD_HOLIDAYS', 'Главный бухгалтер', 127,0
GO
EXEC DBO.W_SPERM_WRITE 'KD_HOLIDAYS', 'Зарплата-КС', 127,0
GO
EXEC DBO.W_SPERM_WRITE 'KD_HOLIDAYS', 'Кадры-КС', 127,0
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Праздничные дни"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_GRAPHICS_FOLDER' AND NAME = 'Графики')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'KD_HOLIDAYS')

DECLARE @ORD INT, @LINK_SNAVIGATOR INT
SET @ORD = (SELECT COALESCE(MAX(ORDERS),0) + 1 FROM DBO.S_NAVIGATOR WHERE LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_GRAPHICS_FOLDER' AND NAME = 'Графики'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'KADR_DICTIONARY_HOLIDAY'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'KADR_DICTIONARY_HOLIDAY', 'Праздничные дни', @ORD, NULL, 1, @LINK_SELF, 'DICTIONARY', @OBJECT, @LINK_VAR, 3
GO


/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Праздничные дни" ЗП*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '4583' AND NAME = 'Учет рабочего времени')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'KD_HOLIDAYS')

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 = '4583' AND NAME = 'Учет рабочего времени'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '3930'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, '3930', 'Праздничные дни', @ORD, NULL, 1, @LINK_SELF, 'DICTIONARY', @OBJECT, @LINK_VAR, 3
GO

GO
EXEC X_SET_PROP 'KD_VACATION_VID', 'SAVE_OBJECT_METHOD', 'X_SAVE(''KD_VACATION_VID_SAVE'', m.cAlias," CODE, NAME, SQLNULL(TYPE_LINK), SQLNULL(LINK_PAYS), PERIOD1, SQLNULL(BonusTakeTime),SQLNULL(Time_arche),SQLNULL(NO_SAL),SQLNULL(HOLIDAY),SQLNULL(ADM),SQLNULL(NOT_LGOT_EXPIR), SQLNULL(IS_DOP),VAC_V","KD_VACATION_VID")'
GO

/****** Объект: Вид отпуска******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'KD_VACATION_VID_VAC_V')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'KD_VACATION_VID_VAC_V')
	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 = 'KD_VACATION_VID_VAC_V')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'KD_VACATION_VID_VAC_V')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'KD_VACATION_VID_VAC_V'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'KD_VACATION_VID_VAC_V')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KD_VACATION_VID_VAC_V')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KD_VACATION_VID_VAC_V', 'Вид отпуска', 28, (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_VACATION_VID'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KD_VACATION_VID_VAC_V', NAME = 'Вид отпуска', ORDERS = '28', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_VACATION_VID'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KD_VACATION_VID_VAC_V'
GO
EXEC X_SET_PROP 'KD_VACATION_VID_VAC_V', 'TITLE', 'Вид отпуска'
GO
EXEC X_SET_PROP 'KD_VACATION_VID_VAC_V', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'KD_VACATION_VID_VAC_V', 'CONTROLSOURCE', 'm.cAlias+".VAC_V"'
GO
EXEC X_SET_PROP 'KD_VACATION_VID_VAC_V', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'KD_VACATION_VID_VAC_V', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'KD_VACATION_VID_VAC_V', 'ROWSOURCE', '"0.Не определен,1.Административный отпуск,2.Дополнительный оплачиваемый отпуск,3.Основной оплачиваемый отпуск,4.Отпуск по уходу за ребенком,5.Учебный отпуск"'
GO
EXEC X_SET_PROP 'KD_VACATION_VID_VAC_V', 'TYPE_FIELD_DICT', 'tinyint'
GO
EXEC X_SET_PROP 'KD_VACATION_VID_VAC_V', 'SHORT_CODE_OBJ', 'VAC_V'
GO
EXEC X_SET_PROP 'KD_VACATION_VID_VAC_V', 'CONTROLSOURCE_EDIT', 'm.cAlias+".VAC_V"'
GO
EXEC X_SET_PROP 'KD_VACATION_VID_VAC_V', 'CONTROL_NAME_EDIT', 'Acombobox1'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
GO

/****** Объект: Вид отпуска******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'KD_VACATION_VID_VAC_VC')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'KD_VACATION_VID_VAC_VC')
	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 = 'KD_VACATION_VID_VAC_VC')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'KD_VACATION_VID_VAC_VC')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'KD_VACATION_VID_VAC_VC'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'KD_VACATION_VID_VAC_VC')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='KD_VACATION_VID_VAC_VC')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'KD_VACATION_VID_VAC_VC', 'Вид отпуска', 29, (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_VACATION_VID'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'KD_VACATION_VID_VAC_VC', NAME = 'Вид отпуска', ORDERS = '29', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KD_VACATION_VID'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='KD_VACATION_VID_VAC_VC'
GO
EXEC X_SET_PROP 'KD_VACATION_VID_VAC_VC', 'TITLE', 'Вид отпуска'
GO
EXEC X_SET_PROP 'KD_VACATION_VID_VAC_VC', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'KD_VACATION_VID_VAC_VC', 'CONTROLSOURCE', 'm.cAlias+".VAC_VC"'
GO
EXEC X_SET_PROP 'KD_VACATION_VID_VAC_VC', 'TYPE_FIELD_DICT', 'varchar(35)'
GO
EXEC X_SET_PROP 'KD_VACATION_VID_VAC_VC', 'CONTROLSOURCE_EDIT', 'm.cAlias+".VAC_VC"'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
-----------Добавление 10ти значных кодов Целевых статей ----

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0100000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0100000000', 'Государственная программа Российской Федерации "Развитие здравоохранения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0110000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0110000000', 'Подпрограмма "Профилактика заболеваний и формирование здорового образа жизни. Развитие первичной медико-санитарной помощи"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0110100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0110100000', 'Основное мероприятие "Развитие системы медицинской профилактики неинфекционных заболеваний и формирования здорового образа жизни"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0110120150') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0110120150', 'Мероприятия, направленные на формирование здорового образа жизни у населения Российской Федерации, включая сокращение потребления алкоголя и табака')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0110200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0110200000', 'Основное мероприятие "Профилактика инфекционных заболеваний, включая иммунопрофилактику"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0110220340') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0110220340', 'Мероприятия в рамках национального календаря профилактических прививок')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0110300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0110300000', 'Основное мероприятие "Профилактика ВИЧ, вирусных гепатитов В и С"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0110320110') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0110320110', 'Мероприятия по профилактике, выявлению, мониторингу лечения и лечению лиц, инфицированных вирусами иммунодефицита человека и гепатитов B и C')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0110351790') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0110351790', 'Иные межбюджетные трансферты на реализацию мероприятий по профилактике ВИЧ-инфекции и гепатитов B и C')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0110400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0110400000', 'Основное мероприятие "Развитие первичной медико-санитарной помощи, а также системы раннего выявления заболеваний, патологических состояний и факторов риска их развития, включая проведение медицинских осмотров и диспансеризации населения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0110500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0110500000', 'Основное мероприятие "Совершенствование механизмов обеспечения населения лекарственными препаратами, медицинскими изделиями, специализированными продуктами лечебного питания для детей-инвалидов в амбулаторных условиях"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0110520300') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0110520300', 'Закупки лекарственных препаратов, предназначенных для лечения больных злокачественными новообразованиями лимфоидной, кроветворной и родственных им тканей, гемофилией, муковисцидозом, гипофизарным нанизмом, болезнью Гоше, рассеянным склерозом, а также')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0110551330') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0110551330', 'Иные межбюджетные трансферты на осуществление организационных мероприятий по обеспечению лиц лекарственными препаратами, предназначенными для лечения больных злокачественными новообразованиями лимфоидной, кроветворной и родственных им тканей, гемофил')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0110551610') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0110551610', 'Иные межбюджетные трансферты на реализацию отдельных полномочий в области лекарственного обеспечения')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0110600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0110600000', 'Основное мероприятие "Первичная профилактика стоматологических заболеваний среди населения Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0110700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0110700000', 'Основное мероприятие "Диспансерное наблюдение больных с артериальной гипертонией"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0120000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0120000000', 'Подпрограмма "Совершенствование оказания специализированной, включая высокотехнологичную, медицинской помощи"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0120100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0120100000', 'Основное мероприятие "Совершенствование системы оказания медицинской помощи больным туберкулёзом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0120120100') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0120120100', 'Мероприятия, направленные на обследование населения с целью выявления туберкулеза, лечения больных туберкулезом, профилактические мероприятия')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0120151740') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0120151740', 'Иные межбюджетные трансферты на финансовое обеспечение закупок антибактериальных и противотуберкулезных лекарственных препаратов (второго ряда), применяемых при лечении больных туберкулезом с множественной лекарственной устойчивостью возбудителя, и д')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0120200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0120200000', 'Основное мероприятие "Совершенствование оказания медицинской помощи лицам, инфицированным вирусом иммунодефицита человека, гепатитами В и С"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0120250720') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0120250720', 'Иные межбюджетные трансферты на финансовое обеспечение закупок антивирусных препаратов для профилактики и лечения лиц, инфицированных вирусами иммунодефицита человека и гепатитов B и C')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0120300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0120300000', 'Основное мероприятие "Совершенствование системы оказания медицинской помощи наркологическим больным"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0120400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0120400000', 'Основное мероприятие "Совершенствование системы оказания медицинской помощи больным с психическими расстройствами и расстройствами поведения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0120500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0120500000', 'Основное мероприятие "Совершенствование системы оказания медицинской помощи больным сосудистыми заболеваниями"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0120600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0120600000', 'Основное мероприятие "Совершенствование системы оказания медицинской помощи больным онкологическими заболеваниями"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0120700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0120700000', 'Основное мероприятие "Развитие системы донорства органов человека в целях трансплантации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0120800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0120800000', 'Основное мероприятие "Совершенствование оказания медицинской помощи пострадавшим при дорожно-транспортных происшествиях"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0120900000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0120900000', 'Основное мероприятие "Совершенствование системы оказания медицинской помощи больным прочими заболеваниями"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0120953820') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0120953820', 'Субсидии на реализацию отдельных мероприятий государственной программы Российской Федерации "Развитие здравоохранения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0121000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0121000000', 'Основное мероприятие "Совершенствование высокотехнологичной медицинской помощи"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0121039720') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0121039720', 'Меры по оказанию медицинской помощи гражданам Российской Федерации за рубежом')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0121060870') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0121060870', 'Закупки лекарственных препаратов и медицинского оборудования')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0121100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0121100000', 'Основное мероприятие "Развитие службы крови"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0130000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0130000000', 'Подпрограмма "Развитие и внедрение инновационных методов диагностики, профилактики и лечения, а также основ персонализированной медицины"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0130100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0130100000', 'Основное мероприятие "Развитие ядерной медицины"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0130140640') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0130140640', 'Строительство и реконструкция объектов в целях организации производства новых радиофармпрепаратов и медицинских изделий и формирования сети услуг по оказанию высокотехнологичной медицинской помощи')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0130200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0130200000', 'Основное мероприятие "Развитие фундаментальной, трансляционной и персонализированной медицины"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0130300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0130300000', 'Основное мероприятие "Развитие инновационной инфраструктуры"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0130400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0130400000', 'Основное мероприятие "Медицинская помощь, оказываемая в рамках клинической апробации методов профилактики, диагностики, лечения и реабилитации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0130468660') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0130468660', 'Медицинская помощь, оказываемая в рамках клинической апробации методов профилактики, диагностики, лечения и реабилитации медицинскими организациями')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0140000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0140000000', 'Подпрограмма "Охрана здоровья матери и ребенка"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0140100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0140100000', 'Основное мероприятие "Совершенствование службы родовспоможения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0140200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0140200000', 'Основное мероприятие "Создание системы раннего выявления и коррекции нарушений развития ребёнка"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0140300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0140300000', 'Основное мероприятие "Выхаживание детей с экстремально низкой массой тела"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0140400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0140400000', 'Основное мероприятие "Развитие специализированной медицинской помощи детям"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0140500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0140500000', 'Основное мероприятие "Совершенствование методов борьбы с вертикальной передачей ВИЧ от матери к плоду"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0140600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0140600000', 'Основное мероприятие "Профилактика абортов.  Развитие центров медико-социальной поддержки беременных, оказавшихся в трудной жизненной ситуации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0150000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0150000000', 'Подпрограмма "Развитие медицинской реабилитации и санаторно-курортного лечения, в том числе детей"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0150100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0150100000', 'Основное мероприятие "Развитие санаторно-курортного лечения"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0150200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0150200000', 'Основное мероприятие "Развитие медицинской реабилитации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0160000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0160000000', 'Подпрограмма "Оказание паллиативной помощи, в том числе детям"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0160100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0160100000', 'Основное мероприятие "Оказание паллиативной помощи взрослым"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0160200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0160200000', 'Основное мероприятие "Оказание паллиативной помощи детям"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0170000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0170000000', 'Подпрограмма "Кадровое обеспечение системы здравоохранения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0170100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0170100000', 'Основное мероприятие "Повышение квалификации и переподготовка медицинских и фармацевтических работников"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0170200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0170200000', 'Основное мероприятие "Повышение престижа медицинских специальностей"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0170234960') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0170234960', 'Финансовое обеспечение единовременного денежного поощрения лучших врачей и специалистов со средним медицинским и фармацевтическим образованием')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0170300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0170300000', 'Основное мероприятие "Государственная поддержка отдельных категорий медицинских работников"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0170351360') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0170351360', 'Иные межбюджетные трансферты на осуществление единовременных выплат медицинским работникам')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0170400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0170400000', 'Основное мероприятие "Развитие сети обучающих симуляционных центров"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0170420310') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0170420310', 'Финансовое обеспечение мероприятий по созданию обучающих симуляционных центров')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0170500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0170500000', 'Основное мероприятие "Внедрение профессиональных стандартов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0180000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0180000000', 'Подпрограмма "Развитие международных отношений в сфере охраны здоровья"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0180100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0180100000', 'Основное мероприятие "Формирование национальной системы содействия международному развитию в сфере охраны здоровья"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0180200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0180200000', 'Основное мероприятие "Исполнение международных обязательств Российской Федерации в сфере охраны здоровья"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0190000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0190000000', 'Подпрограмма "Экспертиза и контрольно-надзорные функции в сфере охраны здоровья"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0190100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0190100000', 'Основное мероприятие "Контроль качества и безопасности медицинской деятельности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0190200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0190200000', 'Основное мероприятие "Государственный контроль в сфере обращения лекарственных средств"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0190300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0190300000', 'Основное мероприятие "Государственный контроль за обращением медицинских изделий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0190400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0190400000', 'Основное мероприятие "Развитие государственной судебно-медицинской экспертной деятельности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0190500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0190500000', 'Основное мероприятие "Государственный санитарно-эпидемиологический надзор"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0190600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0190600000', 'Основное мероприятие "Организация обеспечения санитарно-эпидемиологического благополучия населения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0190700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0190700000', 'Основное мероприятие "Обеспечение реализации подпрограммы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Б0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Б0000000', 'Подпрограмма "Медико-санитарное обеспечение отдельных категорий граждан"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Б0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Б0100000', 'Основное мероприятие "Оказание медицинской помощи работникам отдельных отраслей экономики с особо опасными условиями труда и населению отдельных территорий с опасными для здоровья человека физическими, химическими и биологическими факторами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Б0151970') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Б0151970', 'Иные межбюджетные трансферты на реализацию отдельных полномочий в области лекарственного обеспечения населения закрытых административно-территориальных образований, обслуживаемых федеральными государственными бюджетными учреждениями здравоохранения,')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Б0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Б0200000', 'Основное мероприятие "Медико-биологическое и медико-санитарное обеспечение спортсменов сборных команд Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Б0300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Б0300000', 'Основное мероприятие "Развитие и внедрение инновационных технологий в сфере защиты отдельных категорий граждан от воздействия особо опасных факторов физической, химической и биологической природы, а также обеспечение безопасности пилотируемых космиче')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Г0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Г0000000', 'Подпрограмма "Управление развитием отрасли"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Г0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Г0100000', 'Основное мероприятие "Информационно-аналитическая поддержка реализации государственной программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Г0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Г0200000', 'Основное мероприятие "Информатизация здравоохранения, включая развитие телемедицины"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Г0300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Г0300000', 'Основное мероприятие "Реализация функций аппаратов исполнителей государственной программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Г0400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Г0400000', 'Основное мероприятие "Совершенствование статистического наблюдения в сфере здравоохранения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Д0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Д0000000', 'Подпрограмма "Организация обязательного медицинского страхования граждан Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Д0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Д0100000', 'Основное мероприятие "Финансовое обеспечение территориальных программ обязательного медицинского страхования в рамках базовой программы обязательного медицинского страхования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Д0150930') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Д0150930', 'Субвенции бюджетам территориальных фондов обязательного медицинского страхования на финансовое обеспечение организации обязательного медицинского страхования на территориях субъектов Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Д0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Д0200000', 'Основное мероприятие "Обеспечение застрахованных лиц полисами обязательного медицинского страхования единого образца"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Д0300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Д0300000', 'Основное мероприятие "Управление средствами нормированного страхового запаса Федерального фонда обязательного медицинского страхования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Д0400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Д0400000', 'Основное мероприятие "Обеспечение компенсации выпадающих доходов системы обязательного медицинского страхования в связи с установлением пониженных тарифов страховых взносов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01Д0451820') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01Д0451820', 'Иной межбюджетный трансферт на компенсацию выпадающих доходов бюджета Федерального фонда обязательного медицинского страхования в связи с установлением пониженных тарифов страховых взносов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01И0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01И0000000', 'Подпрограмма "Развитие скорой медицинской помощи"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01И0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01И0100000', 'Основное мероприятие "Совершенствование оказания скорой, в том числе скорой специализированной, медицинской помощи, медицинской эвакуации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01И0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01И0200000', 'Основное мероприятие "Развитие системы оказания медицинской помощи в неотложной и экстренной формах"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01И0300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01И0300000', 'Основное мероприятие "Информатизация системы оказания медицинской помощи в неотложной и экстренной формах"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='01И0400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('01И0400000', 'Основное мероприятие "Совершенствование деятельности Всероссийской службы медицины катастроф"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0200000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0200000000', 'Государственная программа Российской Федерации "Развитие образования" на 2013 -2020 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210000000', 'Подпрограмма "Реализация образовательных программ профессионального образования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210100000', 'Основное мероприятие "Реализация образовательных программ в вузах"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210162350') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210162350', 'Субсидии негосударственным образовательным организациям, имеющим аккредитацию, на оказание государственных услуг по реализации образовательных программ среднего профессионального образования и образовательных программ высшего образования')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210164790') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210164790', 'Субсидии образовательным организациям в странах Содружества Независимых Государств и общественным организациям')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210200000', 'Основное мероприятие "Реализация образовательных программ среднего профессионального образования и профессионального обучения "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210267120') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210267120', 'Реализация мероприятий, связанных с участием, подготовкой и проведением чемпионатов по профессиональному мастерству, проводимых международной организацией "WorldSkills International"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210300000', 'Основное мероприятие "Социальная поддержка работников организаций профессионального образования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210400000', 'Основное мероприятие "Социальная поддержка обучающихся в организациях профессионального образования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210464810') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210464810', 'Субсидии на возмещение части затрат на уплату процентов по образовательным кредитам, предоставляемым студентам образовательных организаций высшего образования')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210500000', 'Основное мероприятие "Поддержка талантливой молодежи в организациях профессионального образования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210530490') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210530490', 'Премии Правительства Российской Федерации в области образования')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210538960') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210538960', 'Стипендии Президента Российской Федерации на реализацию мероприятий, связанных с обучением за рубежом студентов и аспирантов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210561610') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210561610', 'Грант Президента Российской Федерации лицам, проявившим склонности к техническому и гуманитарному творчеству, изобретательству, поступившим на обучение в образовательные организации высшего образования')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210600000', 'Основное мероприятие "Развитие инфраструктуры системы профессионального образования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210700000', 'Основное мероприятие "Поддержка программ развития вузов и приоритетных образовательных программ"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210761520') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210761520', 'Мероприятия Программы интеграции в экономику российских выпускников ведущих университетов мира "Глобальное образование"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210767110') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210767110', 'Государственная поддержка ведущих образовательных организаций высшего образования')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210800000', 'Основное мероприятие "Ведомственная целевая программа "Повышение квалификации инженерно-технических кадров на           2015 - 2016 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0210899999') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0210899999', 'Реализация направлений расходов подпрограммы государственной программы Российской Федерации, федеральной целевой программы в рамках государственной программы Российской Федерации, а также непрограммных направлений расходов федеральных государственных')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0220000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0220000000', 'Подпрограмма "Содействие развитию дошкольного и общего образования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0220100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0220100000', 'Основное мероприятие "Содействие развитию дошкольного образования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0220150590') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0220150590', 'Субсидии на модернизацию региональных систем дошкольного образования')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0220200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0220200000', 'Основное мероприятие "Содействие развитию общего образования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0220250970') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0220250970', 'Субсидии на создание в общеобразовательных организациях, расположенных в сельской местности, условий для занятий физической культурой и спортом')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0220264790') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0220264790', 'Субсидии образовательным организациям в странах Содружества Независимых Государств и общественным организациям')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0220300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0220300000', 'Основное мероприятие "Развитие кадрового потенциала системы дошкольного, общего и дополнительного образования детей"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0220350880') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0220350880', 'Субсидии на поощрение лучших учителей')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0220400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0220400000', 'Основное мероприятие "Развитие инфраструктуры общего образования и дополнительного образования детей"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0240000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0240000000', 'Подпрограмма "Развитие дополнительного образования детей и реализация мероприятий молодежной политики"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0240100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0240100000', 'Основное мероприятие "Реализация образовательных программ дополнительного образования детей и мероприятия по их развитию"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0240200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0240200000', 'Основное мероприятие "Содействие развитию дополнительного образования и социализации детей"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0240262270') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0240262270', 'Субсидии Общероссийской общественно-государственной организации "Добровольное общество содействия армии, авиации и флоту России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0240264790') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0240264790', 'Субсидии образовательным организациям в странах Содружества Независимых Государств и общественным организациям')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0240300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0240300000', 'Основное мероприятие "Выявление и поддержка одаренных детей и молодежи"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0240330380') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0240330380', 'Премии Президента Российской Федерации для поддержки талантливой молодежи')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0240333980') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0240333980', 'Премии лауреатам конкурса молодежных проектов Всекавказского молодежного форума')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0240338960') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0240338960', 'Стипендии Президента Российской Федерации на реализацию мероприятий, связанных с обучением за рубежом студентов и аспирантов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0240350680') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0240350680', 'Субсидия на проведение Северо-Кавказского молодежного форума "Машук"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0240360540') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0240360540', 'Субсидии Фонду "Талант и успех", г. Сочи, Краснодарский край')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0240400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0240400000', 'Основное мероприятие "Создание условий успешной социализации и эффективной самореализации молодежи"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0240500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0240500000', 'Основное мероприятие "Проведение мероприятий по содействию патриотическому воспитанию граждан Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0240600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0240600000', 'Основное мероприятие "Реализация механизмов развития молодежной политики"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0250000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0250000000', 'Подпрограмма "Совершенствование управления системой образования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0250100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0250100000', 'Основное мероприятие "Реализация механизмов оценки и обеспечения качества образования в соответствии с государственными образовательными стандартами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0250200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0250200000', 'Основное мероприятие "Поощрения педагогических работников за особые заслуги перед государством"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0250300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0250300000', 'Основное мероприятие "Сопровождение реализации отдельных мероприятий государственной программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0260000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0260000000', 'Федеральная целевая программа развития образования на 2011 - 2015 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0260050260') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0260050260', 'Субсидия на финансовое обеспечение мероприятий федеральной целевой программы развития образования на 2011 - 2015 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0270000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0270000000', 'Федеральная целевая программа "Русский язык" на 2011 - 2015 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0280000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0280000000', 'Федеральная целевая программа развития образования на 2016 - 2020 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0290000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0290000000', 'Федеральная целевая программа "Русский язык" на 2016 - 2020 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0300000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0300000000', 'Государственная программа Российской Федерации "Социальная поддержка граждан"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310000000', 'Подпрограмма "Обеспечение мер социальной поддержки отдельных категорий граждан"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310100000', 'Основное мероприятие "Оказание мер государственной поддержки гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310130020') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310130020', 'Меры социальной поддержки граждан, подвергшихся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310130040') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310130040', 'Компенсация в возмещение вреда гражданам, подвергшимся воздействию радиации вследствие радиационных аварий, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию радиации всл')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310130050') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310130050', 'Меры социальной поддержки граждан, подвергшихся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Федеральным законом от 10 января 2002 года № 2-ФЗ "О социальных гарантиях гражданам, подвергшимся радиационному')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310130060') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310130060', 'Меры социальной поддержки граждан, подвергшихся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Федеральным законом от 26 ноября 1998 года № 175-ФЗ "О социальной защите граждан Российской Федерации, подвергши')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310130080') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310130080', 'Компенсация в возмещение вреда гражданам, подвергшимся воздействию радиации вследствие радиационных аварий, в соответствии с Федеральным законом от 26 ноября 1998 года № 175-ФЗ "О социальной защите граждан Российской Федерации, подвергшихся воздейств')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310130670') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310130670', 'Осуществление ежемесячной денежной выплаты гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Законом Российской Федерации от 15 мая 1991 года N 1244-I "О социальной защите граждан, подве')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310130700') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310130700', 'Осуществление ежемесячной денежной выплаты гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Федеральным законом от 10 января 2002 года № 2-ФЗ "О социальных гарантиях гражданам, подвергш')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310130710') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310130710', 'Осуществление ежемесячной денежной выплаты гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Федеральным законом от 26 ноября 1998 года № 175-ФЗ "О социальной защите граждан Российской Ф')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310130800') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310130800', 'Пособия гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию радиации вследс')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310130880') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310130880', 'Пособия гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Федеральным законом от 10 января 2002 года № 2-ФЗ "О социальных гарантиях гражданам, подвергшимся радиационному воздействию всле')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310130890') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310130890', 'Пособия гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Федеральным законом от 26 ноября 1998 года № 175-ФЗ "О социальной защите граждан Российской Федерации, подвергшихся воздействию')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310151370') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310151370', 'Субвенции на осуществление переданных полномочий Российской Федерации по предоставлению отдельных мер социальной поддержки граждан, подвергшихся воздействию радиации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310200000', 'Основное мероприятие "Предоставление мер государственной поддержки Героям Советского Союза, Героям Российской Федерации и полным кавалерам ордена Славы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310230090') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310230090', 'Социальная поддержка Героев Советского Союза, Героев Российской Федерации и полных кавалеров ордена Славы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310230300') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310230300', 'Дополнительное пожизненное ежемесячное материальное обеспечение Героям Советского Союза, Героям Российской Федерации и полным кавалерам ордена Славы - участникам Великой Отечественной войны 1941 - 1945 годов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310230720') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310230720', 'Осуществление ежемесячной денежной выплаты Героям Советского Союза, Героям Российской Федерации и полным кавалерам ордена Славы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310300000', 'Основное мероприятие "Предоставление мер государственной поддержки Героям Социалистического Труда, Героям Труда Российской Федерации и полным кавалерам ордена Трудовой Славы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310330730') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310330730', 'Осуществление ежемесячной денежной выплаты Героям Социалистического Труда, Героям Труда Российской Федерации и полным кавалерам ордена Трудовой Славы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310351980') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310351980', 'Социальная поддержка Героев Социалистического Труда, Героев Труда Российской Федерации и полных кавалеров ордена Трудовой Славы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310400000', 'Основное мероприятие "Оказание мер социальной поддержки ветеранам Великой Отечественной войны и боевых действий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310430350') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310430350', 'Дополнительное ежемесячное материальное обеспечение некоторых категорий граждан Российской Федерации в связи с 60-летием Победы в Великой Отечественной войне 1941 - 1945 годов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310430690') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310430690', 'Осуществление ежемесячной денежной выплаты ветеранам')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310500000', 'Основное мероприятие "Оказание мер государственной поддержки инвалидам"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310530360') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310530360', 'Дополнительное ежемесячное материальное обеспечение инвалидов вследствие военной травмы в соответствии с Указом Президента Российской Федерации от 1 августа 2005 года № 887 "О мерах по улучшению материального положения инвалидов вследствие военной тр')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310530680') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310530680', 'Осуществление ежемесячной денежной выплаты инвалидам')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310600000', 'Основное мероприятие " Предоставление отдельным категориям граждан государственной социальной помощи в виде набора социальных услуг в части санаторно-курортного лечения, проезда к месту лечения и обратно, а также проезда на железнодорожном транспорте')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310635990') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310635990', 'Оказание государственной социальной помощи отдельным категориям граждан по проезду на транспорте пригородного сообщения')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310651930') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310651930', 'Оказание государственной социальной помощи отдельным категориям граждан в части оплаты санаторно-курортного лечения, а также проезда на междугородном транспорте к месту лечения и обратно')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310651940') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310651940', 'Субвенции на оказание государственной социальной помощи отдельным категориям граждан в части оплаты санаторно-курортного лечения, а также проезда на междугородном транспорте к месту лечения и обратно')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310700000', 'Основное мероприятие "Предоставление социальных доплат к пенсии"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310730570') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310730570', 'Выплата федеральной социальной доплаты к пенсии')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310751530') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310751530', 'Иные межбюджетные трансферты на выплату региональной доплаты к пенсии')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310800000', 'Основное мероприятие "Оказание мер социальной поддержки по оплате жилищно-коммунальных услуг отдельным категориям граждан"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310852500') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310852500', 'Субвенции на оплату жилищно-коммунальных услуг отдельным категориям граждан')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310900000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310900000', 'Основное мероприятие "Оказание мер государственной поддержки лицам, ходатайствующим о признании их беженцами или вынужденными переселенцами, а также прибывшим с ними членам их семей  "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310930100') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310930100', 'Пособие лицам, ходатайствующим о признании их беженцами на территории Российской Федерации, и прибывшим с ними членам их семей')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0310930110') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0310930110', 'Пособие лицам, ходатайствующим о признании их вынужденными переселенцами, и прибывшим с ними членам их семей')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311000000', 'Основное мероприятие "Оказание мер государственной поддержки гражданам, пострадавшим в результате разрешения кризиса в Чеченской Республике и покинувшим ее безвозвратно"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311030470') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311030470', 'Компенсация за утраченное жилье и (или) имущество гражданам, пострадавшим в результате разрешения кризиса в Чеченской Республике и покинувшим ее безвозвратно')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311100000', 'Основное мероприятие "Оказание мер социальной поддержки лицам, награжденным нагрудным знаком "Почетный донор России""')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311152200') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311152200', 'Субвенции на осуществление переданного полномочия Российской Федерации по осуществлению ежегодной денежной выплаты лицам, награжденным нагрудным знаком "Почетный донор России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311200000', 'Основное мероприятие "Оказание мер социальной поддержки гражданам при возникновении поствакцинальных осложнений "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311252400') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311252400', 'Субвенции на выплату государственного единовременного пособия и ежемесячной денежной компенсации гражданам при возникновении поствакцинальных осложнений в соответствии с Федеральным законом от 17 сентября 1998 года № 157-ФЗ "Об иммунопрофилактике инф')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311300000', 'Основное мероприятие "Осуществление компенсационных выплат реабилитированным лицам"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311353000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311353000', 'Иные межбюджетные трансферты на единовременные денежные компенсации реабилитированным лицам')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311400000', 'Основное мероприятие "Оказание поддержки в связи с погребением умерших"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311430140') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311430140', 'Возмещение федеральными органами исполнительной власти расходов на погребение')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311430740') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311430740', 'Выплата социального пособия на погребение и оказание услуг по погребению согласно гарантированному перечню этих услуг за умерших, получавших пенсии по государственному пенсионному обеспечению')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311430900') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311430900', 'Возмещение стоимости гарантированного перечня услуг и социальные пособия на погребение за счет средств Фонда социального страхования Российской Федерации')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311500000', 'Основное мероприятие "Оказание мер государственной поддержки отдельным категориям государственных служащих, а также уволенным из их числа, и членам их семей"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311530130') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311530130', 'Пособия лицам, досрочно уволенным из органов федеральной противопожарной службы Государственной противопожарной службы, и членам семей погибших (умерших) сотрудников и работников федеральной противопожарной службы Государственной противопожарной служ')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311530170') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311530170', 'Пособия, выплаты и компенсации членам семей военнослужащих, а также лицам, уволенным с военной службы без права на пенсию')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311530180') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311530180', 'Пособия, выплаты и компенсации лицам, уволенным с военной службы с правом на пенсию, а также членам их семей')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311530230') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311530230', 'Ежемесячная выплата гражданам, уволенным со службы в органах внутренних дел без права на пенсию, имеющим общую продолжительность службы в органах внутренних дел менее 20 лет')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311530310') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311530310', 'Ежемесячные социальные пособия лицам, уволенным из органов по контролю за оборотом наркотических средств и психотропных веществ без права на пенсию')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311539810') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311539810', 'Пособия и компенсации военнослужащим, приравненным к ним лицам, а также уволенным из их числа (за исключением публичных нормативных обязательств)')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311600000', 'Основное мероприятие "Оказание мер государственной поддержки отдельным категориям государственных служащих, гражданам в связи с исполнением обязанностей военной службы по призыву, получившим увечье или иное повреждение здоровья, а также членам их сем')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311630150') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311630150', 'Пособия лицам, являвшимся сотрудниками учреждений и органов уголовно-исполнительной системы, федеральной противопожарной службы Государственной противопожарной службы, органов по контролю за оборотом наркотических средств и психотропных веществ, тамо')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311630160') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311630160', 'Компенсации лицам, являвшимся судебными приставами, утратившим возможность заниматься профессиональной деятельностью, и нетрудоспособным членам семей погибших (умерших) судебных приставов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311630210') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311630210', 'Пособия гражданам, являвшимся должностными лицами таможенных органов, утратившим возможность заниматься профессиональной деятельностью, и членам семьи и иждивенцам должностного лица таможенных органов в случае его гибели в связи с исполнением служебн')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311630240') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311630240', 'Пособия и компенсации членам семей погибших (умерших) военнослужащих (граждан, проходивших военные сборы, инвалидов вследствие военной травмы), а также лицам, которым установлена инвалидность вследствие военной травмы после увольнения с военной служб')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311630250') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311630250', 'Пособия лицам, являвшимся сотрудниками органов внутренних дел, получившим телесные повреждения, исключающие возможность дальнейшего прохождения службы, а также семьям и иждивенцам сотрудников органов внутренних дел, погибших (умерших) в связи с осуще')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311630990') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311630990', 'Пособия и компенсации членам семей, а также родителям погибших (умерших) сотрудников органов внутренних дел')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311639800') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311639800', 'Компенсация в возмещение вреда, причиненного здоровью граждан в связи с исполнением обязанностей военной службы по призыву')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311639820') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311639820', 'Компенсация членам семей погибших военнослужащих')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311639830') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311639830', 'Обеспечение проведения ремонта индивидуальных жилых домов, принадлежащих членам семей военнослужащих, потерявшим кормильца')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311700000', 'Основное мероприятие "Оказание государственной поддержки членам семей лиц, погибших при осуществлении мероприятий по борьбе с терроризмом, а также лицам, получившим увечья при осуществлении указанных мероприятий, повлекшие наступление инвалидности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311730200') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311730200', 'Единовременное пособие членам семей (лицам, находившимся на их иждивении) лиц, погибших при осуществлении мероприятий по борьбе с терроризмом, а также лицам, получившим увечья при осуществлении мероприятий по борьбе с терроризмом, повлекшие наступлен')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311800000', 'Основное мероприятие "Осуществление компенсационных выплат лицам, осуществляющим уход за нетрудоспособными гражданами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311830390') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311830390', 'Компенсационные выплаты лицам, осуществляющим уход за нетрудоспособными гражданами')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311830980') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311830980', 'Оплата четырех дополнительных выходных дней работающим родителям (опекунам, попечителям) для ухода за детьми-инвалидами')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311831030') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311831030', 'Ежемесячные выплаты лицам, осуществляющим уход за детьми-инвалидами и инвалидами с детства I группы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311900000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311900000', 'Основное мероприятие "Выплата дополнительного материального обеспечения гражданам за выдающиеся достижения и заслуги перед Российской Федерацией"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0311930190') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0311930190', 'Выплата дополнительного материального обеспечения, доплат к пенсиям, пособий и компенсаций')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0312000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0312000000', 'Основное мероприятие "Предоставление мер поддержки гражданам, подлежащим обязательному социальному страхованию"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0312030940') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0312030940', 'Пособия по временной нетрудоспособности отдельным категориям граждан в связи с зачетом в страховой стаж нестраховых периодов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0312030950') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0312030950', 'Пособия по временной нетрудоспособности по обязательному социальному страхованию от несчастных случаев на производстве и профессиональных заболеваний')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0312030960') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0312030960', 'Единовременные страховые выплаты')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0312030970') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0312030970', 'Ежемесячные страховые выплаты')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0312039610') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0312039610', 'Доставка и пересылка страховых выплат')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0312100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0312100000', 'Основное мероприятие "Предоставление отдельным категориям граждан государственной социальной помощи на основании социального контракта"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0312200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0312200000', 'Основное мероприятие "Совершенствование законодательства в области предоставления мер социальной поддержки отдельных категорий граждан и системы социального страхования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0312300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0312300000', 'Основное мероприятие "Создание единой информационной базы данных лиц, получивших средства федерального бюджета на улучшение жилищных условий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0320000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0320000000', 'Подпрограмма "Модернизация и развитие социального обслуживания населения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0320100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0320100000', 'Основное мероприятие "Распространение положительного опыта работы субъектов Российской Федерации в сфере социального обслуживания граждан"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0320200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0320200000', 'Основное мероприятие "Формирование независимой системы оценки качества работы организаций, оказывающих социальные услуги в сфере социального обслуживания населения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0320300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0320300000', 'Основное мероприятие "Обеспечение деятельности учреждений социального обслуживания граждан"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0320400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0320400000', 'Основное мероприятие "Поощрение победителей Всероссийского конкурса на звание "Лучший работник учреждений социального обслуживания""')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0320434970') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0320434970', 'Финансовое обеспечение единовременного денежного поощрения лучших социальных работников')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0320500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0320500000', 'Основное мероприятие "Совершенствование системы оплаты труда социальных работников"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0320600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0320600000', 'Основное мероприятие "Привлечение в сферу социального обслуживания населения бизнеса и социально ориентированных некоммерческих организаций, благотворителей и добровольцев"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0320653970') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0320653970', 'Субсидии на возмещение затрат на уплату процентов по кредитам, полученных юридическими лицами на реализацию инвестиционных проектов в сфере социального обслуживания')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0320700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0320700000', 'Основное мероприятие "Оказание финансовой поддержки бюджетам субъектов Российской Федерации на осуществление мероприятий по укреплению материально-технической базы организаций социального обслуживания"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0320800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0320800000', 'Основное мероприятие "Совершенствование системы социального обслуживания граждан"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330000000', 'Подпрограмма "Совершенствование государственной поддержки семей, имеющих детей"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330100000', 'Основное мероприятие "Оказание мер государственной поддержки в связи с беременностью и родами, а также гражданам, имеющим детей"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330130530') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330130530', 'Компенсации женщинам, имеющим детей в возрасте до трех лет, уволенным в связи с ликвидацией организации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330130820') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330130820', 'Пособия по уходу за ребенком до достижения им возраста полутора лет гражданам, подлежащим обязательному социальному страхованию на случай временной нетрудоспособности и в связи с материнством')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330130830') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330130830', 'Пособия при рождении ребенка гражданам, подлежащим обязательному социальному страхованию на случай временной нетрудоспособности и в связи с материнством')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330130840') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330130840', 'Единовременные пособия женщинам, вставшим на учет в медицинских учреждениях в ранние сроки беременности, подлежащим обязательному социальному страхованию на случай временной нетрудоспособности и в связи с материнством')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330130910') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330130910', 'Пособия по временной нетрудоспособности по обязательному социальному страхованию на случай временной нетрудоспособности и в связи с материнством')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330130920') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330130920', 'Пособия по беременности и родам гражданам, подлежащим обязательному социальному страхованию на случай временной нетрудоспособности и в связи с материнством')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330131040') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330131040', 'Пособия по беременности и родам отдельным категориям граждан в связи с зачетом в страховой стаж нестраховых периодов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330152700') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330152700', 'Субвенции на выплату единовременного пособия беременной жене военнослужащего, проходящего военную службу по призыву, а также ежемесячного пособия на ребенка военнослужащего, проходящего военную службу по призыву, в соответствии с Федеральным законом')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330153800') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330153800', 'Субвенции на выплату государственных пособий лицам, не подлежащим обязательному социальному страхованию на случай временной нетрудоспособности и в связи с материнством, и лицам, уволенным в связи с ликвидацией организаций (прекращением деятельности,')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330200000', 'Основное мероприятие "Обеспечение выплаты пособий по уходу за ребенком гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330230030') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330230030', 'Пособие по уходу за ребенком гражданам, подвергшимся воздействию радиации вследствие радиационных аварий, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию радиации вслед')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330230070') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330230070', 'Пособие по уходу за ребенком гражданам, подвергшимся воздействию радиации вследствие радиационных аварий, в соответствии с Федеральным законом от 26 ноября 1998 года № 175-ФЗ "О социальной защите граждан Российской Федерации, подвергшихся воздействию')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330300000', 'Основное мероприятие "Обеспечение выплаты ежемесячных пособий и пособий на проведение летнего оздоровительного отдыха детям погибших (умерших) военнослужащих и сотрудников некоторых федеральных органов исполнительной власти"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330330260') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330330260', 'Ежемесячное пособие детям военнослужащих и сотрудников некоторых федеральных органов исполнительной власти, погибших (умерших, объявленных умершими, признанных безвестно отсутствующими) при исполнении обязанностей военной службы (служебных обязанност')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330330550') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330330550', 'Пособие на проведение летнего оздоровительного отдыха детей отдельных категорий военнослужащих и сотрудников некоторых федеральных органов исполнительной власти, погибших (умерших), пропавших без вести, ставших инвалидами в связи с выполнением задач')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330400000', 'Основное мероприятие "Оказание социальной поддержки многодетным семьям"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330450840') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330450840', 'Субсидии на ежемесячную денежную выплату, назначаемую в случае рождения третьего ребенка или последующих детей до достижения ребенком возраста трех лет')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330451550') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330451550', 'Иные межбюджетные трансферты на единовременное денежное поощрение при награждении орденом "Родительская слава"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330500000', 'Основное мероприятие "Предоставление материнского (семейного) капитала"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330530790') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330530790', 'Предоставление материнского (семейного) капитала')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330600000', 'Основное мероприятие "Оказание поддержки бюджетам субъектов Российской Федерации на проведение мероприятий по отдыху и оздоровлению детей"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330700000', 'Основное мероприятие "Оказание мер социальной поддержки детям-сиротам, детям, оставшимся без попечения родителей, лицам из числа указанной категории детей, а также гражданам, желающим взять детей на воспитание в семью"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330739860') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330739860', 'Социальное обеспечение детей-сирот и детей, оставшихся без попечения родителей, лиц из числа детей-сирот и детей, оставшихся без попечения родителей, обучающихся по имеющим государственную аккредитацию образовательным программам среднего профессионал')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330750820') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330750820', 'Субсидии на предоставление жилых помещений детям-сиротам и детям, оставшимся без попечения родителей, лицам из их числа по договорам найма специализированных жилых помещений')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330752600') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330752600', 'Субвенции на выплату единовременного пособия при всех формах устройства детей, лишенных родительского попечения, в семью')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330800000', 'Основное мероприятие "Оказание поддержки детям, оказавшимся в трудной жизненной ситуации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330862490') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330862490', 'Разработка и реализация комплекса мер по оказанию поддержки детям, оказавшимся в трудной жизненной ситуации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0330900000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0330900000', 'Основное мероприятие "Совершенствование нормативной правовой базы по предоставлению мер государственной поддержки семьям, имеющим детей"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0331000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0331000000', 'Основное мероприятие "Совершенствование  системы социального обслуживания семей с детьми"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0340000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0340000000', 'Подпрограмма "Повышение эффективности государственной поддержки социально ориентированных некоммерческих организаций"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0340100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0340100000', 'Основное мероприятие "Оказание государственной поддержки общественным и иным некоммерческим организациям"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0340150850') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0340150850', 'Субсидии на мероприятия по поддержке социально ориентированных некоммерческих организаций')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0340152090') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0340152090', 'Софинансирование социальных программ субъектов Российской Федерации, связанных с укреплением материально-технической базы учреждений социального обслуживания населения, оказанием адресной социальной помощи неработающим пенсионерам, обучением компьюте')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0340200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0340200000', 'Основное мероприятие "Организация статистических обследований и переписей"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0340231150') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0340231150', 'Компенсация расходов, связанных с переездом из районов Крайнего Севера и приравненных к ним местностей в другую местность на территории Российской Федерации в соответствии с законодательством Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0340251670') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0340251670', 'Компенсация выпадающих доходов бюджету Фонда социального страхования Российской Федерации в связи с установлением пониженных тарифов страховых взносов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0340251810') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0340251810', 'Обеспечение сбалансированности бюджета Фонда социального страхования Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0340251990') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0340251990', 'Оплата стоимости проезда пенсионерам к месту отдыха и обратно один раз в два года')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0340300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0340300000', 'Основное мероприятие "Обеспечение деятельности Комитета ветеранов подразделений особого риска Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0340362510') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0340362510', 'Государственная поддержка деятельности Комитета ветеранов подразделений особого риска Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0360000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0360000000', 'Подпрограмма "Старшее поколение"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0360100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0360100000', 'Основное мероприятие "Софинансирование социальных программ субъектов Российской Федерации, связанных с укреплением материально-технической базы учреждений социального обслуживания населения и оказанием адресной социальной помощи неработающим пенсионе')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0360200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0360200000', 'Основное мероприятие "Оказанием мер социальной поддержки пенсионерам в районах Крайнего Севера и приравненных к ним местностях"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0370000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0370000000', 'Подпрограмма "Обеспечение условий реализации государственной программы Российской Федерации  "Социальная поддержка граждан"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0370100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0370100000', 'Основное мероприятие "Научно-методическое и материальное обеспечение государственной политики в сфере социальной поддержки населения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0370200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0370200000', 'Основное мероприятие "Обеспечение сбалансированности бюджета Фонда социального страхования Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0370300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0370300000', 'Основное мероприятие "Обеспечение выполнения полномочий Фонда социального страхования Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0370400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0370400000', 'Основное мероприятие "Развитие международного сотрудничества в  сфере социальной поддержки населения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0500000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0500000000', 'Государственная программа Российской Федерации "Обеспечение доступным и комфортным жильем и коммунальными услугами граждан Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0510000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0510000000', 'Подпрограмма "Создание условий для обеспечения доступным и комфортным жильем граждан России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0510100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0510100000', 'Основное мероприятие " Переселение граждан из многоквартирных домов, признанных аварийными и подлежащими сносу и не входящих в действующие программы переселения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0510165120') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0510165120', 'Имущественный взнос Российской Федерации в государственную корпорацию - Фонд содействия реформированию жилищно-коммунального хозяйства для увеличения лимитов предоставления финансовой поддержки субъектам Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0510200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0510200000', 'Основное мероприятие "Совершенствование управления специальными жилищными программами с использованием ипотечного кредитования"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0510300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0510300000', 'Основное мероприятие "Обеспечение жильем отдельных категорий граждан"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0510351340') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0510351340', 'Субвенции на осуществление полномочий по обеспечению жильем отдельных категорий граждан, установленных Федеральным законом от 12 января 1995 года № 5-ФЗ "О ветеранах", в соответствии с Указом Президента Российской Федерации от 7 мая 2008 года № 714 "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0510351350') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0510351350', 'Субвенции на осуществление полномочий по обеспечению жильем отдельных категорий граждан, установленных федеральными законами от 12 января 1995 года № 5-ФЗ "О ветеранах" и от 24 ноября 1995 года № 181-ФЗ "О социальной защите инвалидов в Российской Фед')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0510400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0510400000', 'Основное мероприятие "Реализация программы "Жилье для российской семьи""')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0510500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0510500000', 'Основное мероприятие "Создание условий для развития жилищного строительства на вовлекаемых в гражданский оборот земельных участках в соответствии с Федеральным законом "О содействии развитию жилищного строительства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0510600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0510600000', 'Основное мероприятие "Формирование механизмов долгосрочного финансирования ипотечного жилищного кредитования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0510700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0510700000', 'Основное мероприятие "Содействие формированию рынка доступного арендного жилья и развитие некоммерческого жилищного фонда для граждан, имеющих невысокий уровень дохода"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0510800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0510800000', 'Основное мероприятие "Внедрение новых энергоэффективных и ресурсосберегающих технологий при жилищном строительстве, создание условий для строительства и реконструкции предприятий по производству ресурсосберегающих материалов, изделий и конструкций"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0510900000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0510900000', 'Основное мероприятие "Восстановление и (или) проведение капитального ремонта жилищного фонда (переселение граждан из жилищного фонда), поврежденного (признанного непригодным для проживания) вследствие чрезвычайных ситуаций природного и техногенного х')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0511354850') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0511354850', 'Субвенции на обеспечение жильем граждан, уволенных с военной службы (службы), и приравненных к ним лиц')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0511354960') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0511354960', 'Субсидии на мероприятия по переселению граждан, проживающих в оползневой зоне Малгобекского района Республики Ингушетия')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0511367380') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0511367380', 'Субсидии российским кредитным организациям и открытому акционерному обществу "Агентство по ипотечному жилищному кредитованию" на возмещение недополученных доходов по выданным (приобретенным) жилищным (ипотечным) кредитам (займам)')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0511554170') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0511554170', 'Субсидии на мероприятия по переселению граждан из жилищного фонда, признанного непригодным для проживания вследствие техногенной аварии на руднике БКПРУ-1 публичного акционерного общества "Уралкалий", г. Березники, Пермский край')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0520000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0520000000', 'Подпрограмма "Создание условий для обеспечения качественными услугами жилищно-коммунального хозяйства граждан России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0520100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0520100000', 'Основное мероприятие "Содействие проведению капитального ремонта многоквартирных домов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0520165120') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0520165120', 'Имущественный взнос Российской Федерации в государственную корпорацию - Фонд содействия реформированию жилищно-коммунального хозяйства для увеличения лимитов предоставления финансовой поддержки субъектам Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0520200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0520200000', 'Основное мероприятие "Поддержка региональных программ модернизации систем коммунальной инфраструктуры"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0520265120') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0520265120', 'Имущественный взнос Российской Федерации в государственную корпорацию - Фонд содействия реформированию жилищно-коммунального хозяйства для увеличения лимитов предоставления финансовой поддержки субъектам Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0520300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0520300000', 'Основное мероприятие "Реализация проекта Международного банка реконструкции и развития "Реформа жилищно-коммунального хозяйства в России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0520400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0520400000', 'Основное мероприятие "Стимулирование рационального потребления коммунальных услуг населением"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0520500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0520500000', 'Основное мероприятие "Подготовка коммунальной инфраструктуры, обеспечивающей функционирование спортивных объектов, в рамках проведения в 2018 году в Российской Федерации чемпионата мира по футболу"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0520550300') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0520550300', 'Субсидии на реализацию мероприятий по подготовке и проведению чемпионата мира по футболу в 2018 году в Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0520600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0520600000', 'Основное мероприятие "Содействие развитию коммунальной и инженерной инфраструктуры государственной собственности субъектов Российской Федерации (муниципальной собственности)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0530000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0530000000', 'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Обеспечение доступным и комфортным жильем и коммунальными услугами граждан Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0530100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0530100000', 'Основное мероприятие "Обеспечение функций центрального аппарата Минстроя России"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0530200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0530200000', 'Основное мероприятие "Обеспечение устойчивого развития жилищного сектора и инфраструктуры населенных пунктов (Программой ООН "ХАБИТАТ")"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0530300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0530300000', 'Основное мероприятие "Премирование победителей Всероссийского конкурса на звание "Самое благоустроенное городское (сельское) поселение России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0530351620') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0530351620', 'Иные межбюджетные трансферты на премирование победителей Всероссийского конкурса на звание "Самое благоустроенное городское (сельское) поселение России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0530400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0530400000', 'Основное мероприятие "Совершенствование системы государственного ценообразования, сметного нормирования и технического регулирования в строительной сфере"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540000000', 'Федеральная целевая программа "Жилище" на 2011 - 2015 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540100000', 'Основное мероприятие "Подпрограмма "Модернизация объектов коммунальной инфраструктуры" федеральной целевой программы "Жилище" на 2011 - 2015 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540150220') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540150220', 'Субсидии на мероприятия подпрограммы "Модернизация объектов коммунальной инфраструктуры" федеральной целевой программы "Жилище" на 2011 - 2015 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540150250') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540150250', 'Субсидии на мероприятия по переселению граждан, проживающих в городах Норильск и Дудинка, и модернизации коммунальной инфраструктуры города Норильска')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540200000', 'Основное мероприятие "Подпрограмма "Обеспечение жильем молодых семей" федеральной целевой программы "Жилище" на 2011 - 2015 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540250200') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540250200', 'Субсидии на мероприятия подпрограммы "Обеспечение жильем молодых семей" федеральной целевой программы "Жилище" на 2011 - 2015 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540300000', 'Основное мероприятие "Подпрограмма "Выполнение государственных обязательств по обеспечению жильем категорий граждан, установленных федеральным законодательством" федеральной целевой программы "Жилище" на 2011 - 2015 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540335700') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540335700', 'Приобретение жилья гражданами, подлежащими переселению из закрытых административно-территориальных образований и территорий, ранее входивших в границы закрытых административно-территориальных образований')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540335840') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540335840', 'Приобретение жилья военнослужащими, сотрудниками органов внутренних дел, подлежащими увольнению с военной службы (службы), и приравненными к ним лицами')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540335860') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540335860', 'Приобретение жилья гражданами - участниками ликвидации последствий радиационных аварий и катастроф, пострадавшими в результате этих аварий, и приравненными к ним лицами')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540335870') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540335870', 'Приобретение жилья вынужденными переселенцами')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540335880') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540335880', 'Приобретение жилья гражданами, выезжающими из районов Крайнего Севера и приравненных к ним местностей')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540335890') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540335890', 'Мероприятия по обеспечению жильем федеральных государственных гражданских служащих')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540335900') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540335900', 'Мероприятия по обеспечению жильем прокуроров и следователей')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540335910') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540335910', 'Мероприятия по обеспечению жильем спасателей аварийно-спасательных служб и аварийно-спасательных формирований')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540335920') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540335920', 'Мероприятия по обеспечению жильем молодых ученых и строительство общежитий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540335930') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540335930', 'Мероприятия по обеспечению жильем иных категорий граждан Управлением делами Президента Российской Федерации на основании решений Президента Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540350230') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540350230', 'Субсидии на мероприятия по переселению граждан из ветхого и аварийного жилья в зоне Байкало-Амурской магистрали')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540350240') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540350240', 'Субсидии на мероприятия по приведению объектов города Волгодонска в состояние, обеспечивающее безопасное проживание его жителей')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540400000', 'Основное мероприятие "Подпрограмма "Стимулирование программ развития жилищного строительства субъектов Российской Федерации" федеральной целевой программы "Жилище" на 2011 - 2015 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540450210') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540450210', 'Субсидии на мероприятия подпрограммы "Стимулирование программ развития жилищного строительства субъектов Российской Федерации" федеральной целевой программы "Жилище" на 2011 - 2015 годы')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0540467370') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0540467370', 'Взнос в уставный капитал открытого акционерного общества "Агентство по ипотечному жилищному кредитованию" на реализацию программы помощи отдельным категориям заемщиков, оказавшихся в трудной финансовой ситуации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0550000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0550000000', 'Федеральная целевая программа "Чистая вода" на 2011 - 2017 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0550051090') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0550051090', 'Субсидии на реализацию мероприятий федеральной целевой программы "Чистая вода" на 2011 - 2017 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0560000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0560000000', 'Федеральная целевая программа "Жилище" на 2015 - 2020 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0700000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0700000000', 'Государственная программа Российской Федерации "Содействие занятости населения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0710000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0710000000', 'Подпрограмма "Активная политика занятости населения и социальная поддержка безработных граждан"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0710100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0710100000', 'Основное мероприятие "Разработка нормативной правовой и методической базы в сфере занятости населения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0710200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0710200000', 'Основное мероприятие "Реализация мероприятий активной политики занятости населения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0710220220') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0710220220', 'Реализация комплекса мероприятий по организации альтернативной гражданской службы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0710234950') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0710234950', 'Компенсация за счет средств федерального бюджета расходов, связанных с реализацией права граждан, проходящих альтернативную гражданскую службу, на бесплатный проезд к месту прохождения альтернативной гражданской службы, в том числе в связи с переводо')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0710250830') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0710250830', 'Субсидии на реализацию дополнительных мероприятий в сфере занятости населения')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0710300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0710300000', 'Основное мероприятие "Развитие трудовой мобильности населения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0710352380') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0710352380', 'Субсидии на софинансирование региональных программ повышения мобильности трудовых ресурсов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0710400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0710400000', 'Основное мероприятие "Мониторинг состояния и разработка прогнозных оценок рынка труда"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0710500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0710500000', 'Основное мероприятие "Социальные выплаты безработным гражданам и оптимизация критериев назначения и размеров пособия по безработице"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0710552900') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0710552900', 'Субвенции на социальные выплаты безработным гражданам в соответствии с Законом Российской Федерации от 19 апреля 1991 года № 1032-I "О занятости населения в Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0720000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0720000000', 'Подпрограмма "Внешняя трудовая миграция"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0720100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0720100000', 'Основное мероприятие "Совершенствование миграционного законодательства в части привлечения и использования иностранных работников"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0720200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0720200000', 'Основное мероприятие "Использование дифференцированного подхода к привлечению и использованию иностранных работников"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0720300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0720300000', 'Основное мероприятие "Противодействие незаконной трудовой деятельности иностранных работников в Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0720400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0720400000', 'Основное мероприятие "Организация государственной информационной системы миграционного учета"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0720500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0720500000', 'Основное мероприятие "Содействие развитию и реализации программ по адаптации и интеграции иностранных граждан в российское общество"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0720538970') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0720538970', 'Прием и содержание беженцев и лиц, ходатайствующих о признании их беженцами')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0720538980') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0720538980', 'Прием и содержание вынужденных переселенцев')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0730000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0730000000', 'Подпрограмма "Развитие институтов рынка труда"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0730100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0730100000', 'Основное мероприятие "Создание условий для улучшения качества рабочей силы и развития ее профессиональной мобильности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0730134980') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0730134980', 'Финансовое обеспечение единовременного денежного поощрения победителей Всероссийского конкурса профессионального мастерства "Лучший по профессии"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0730168280') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0730168280', 'Субсидия Общероссийскому объединению работодателей "Российский союз промышленников и предпринимателей" на организацию разработки профессиональных стандартов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0730200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0730200000', 'Основное мероприятие "Содействие увеличению размера реальной заработной платы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0730300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0730300000', 'Основное мероприятие "Развитие социального партнерства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0730400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0730400000', 'Основное мероприятие "Стимулирование работодателей к улучшению условий труда на рабочих местах"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0730500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0730500000', 'Основное мероприятие "Надзор и контроль в сфере труда и занятости"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0740000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0740000000', 'Подпрограмма "Оказание содействия добровольному переселению в Российскую Федерацию соотечественников, проживающих за рубежом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0740100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0740100000', 'Основное мероприятие "Совершенствование нормативной правовой базы в сфере оказания содействия добровольному переселению в Российскую Федерацию соотечественников, проживающих за рубежом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0740200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0740200000', 'Основное мероприятие "Содействие реализации региональных программам переселения, включенных в Государственную программу по оказанию содействия добровольному переселению в Российскую Федерацию соотечественников, проживающих за рубежом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0740250860') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0740250860', 'Субсидии на реализацию мероприятий, предусмотренных региональной программой переселения, включенной в Государственную программу по оказанию содействия добровольному переселению в Российскую Федерацию соотечественников, проживающих за рубежом')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0740300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0740300000', 'Основное мероприятие "Деятельность временных групп за рубежом, а также их инспектирование"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0740320080') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0740320080', 'Переселение в Российскую Федерацию соотечественников, проживающих за рубежом')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0740400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0740400000', 'Основное мероприятие "Оказание мер государственной поддержки участникам Государственной программы по оказанию содействия добровольному переселению в Российскую Федерацию соотечественников, проживающих за рубежом и членам их семей"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0740420080') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0740420080', 'Переселение в Российскую Федерацию соотечественников, проживающих за рубежом')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0740500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0740500000', 'Основное мероприятие "Аналитическое и организационно-методическое обеспечение реализации Государственной программы по оказанию содействия добровольному переселению в Российскую Федерацию соотечественников, проживающих за рубежом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0740520080') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0740520080', 'Переселение в Российскую Федерацию соотечественников, проживающих за рубежом')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0740600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0740600000', 'Основное мероприятие "Совершенствование нормативной правовой базы субъектов Российской Федерации по вопросам реализации соответствующей региональной программы переселения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0740620080') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0740620080', 'Переселение в Российскую Федерацию соотечественников, проживающих за рубежом')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0800000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0800000000', 'Государственная программа Российской Федерации "Обеспечение общественного порядка и противодействие преступности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0810000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0810000000', 'Подпрограмма "Предварительное следствие"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0810100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0810100000', 'Основное мероприятие "Организационно-методическое руководство деятельностью подчиненных органов предварительного следствия"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0810200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0810200000', 'Основное мероприятие "Осуществление ведомственного процессуального контроля"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0810300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0810300000', 'Основное мероприятие "Организация расследования преступлений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0820000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0820000000', 'Подпрограмма "Полиция"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0820100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0820100000', 'Основное мероприятие "Антикриминальная деятельность"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0820200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0820200000', 'Основное мероприятие "Охрана общественного порядка и профилактика правонарушений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0820300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0820300000', 'Основное мероприятие "Взаимодействие и сотрудничество правоохранительных и иных государственных органов Российской Федерации с правоохранительными органами иностранных государств - членов Международной организации уголовной полиции - Интерпола, Генер')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0820400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0820400000', 'Основное мероприятие "Экспертно-криминалистическая деятельность"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0820500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0820500000', 'Основное мероприятие "Дознание"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0820600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0820600000', 'Основное мероприятие "Содержание, охрана и конвоирование лиц, подозреваемых и обвиняемых в совершении преступлений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0820700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0820700000', 'Основное мероприятие "Деятельность подразделений специального назначения и авиации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0820800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0820800000', 'Основное мероприятие "Охрана на договорной основе имущества граждан и организаций, а также объектов, подлежащих обязательной охране полицией "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0820900000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0820900000', 'Основное мероприятие "Государственный контроль в сфере оборота оружия и частной детективной (сыскной) и охранной деятельности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0821000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0821000000', 'Основное мероприятие "Деятельность дежурных частей органов внутренних дел Российской Федерации "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0821100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0821100000', 'Основное мероприятие "Обеспечение безопасности на транспорте"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0821200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0821200000', 'Основное мероприятие "Обеспечение безопасности дорожного движения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0821300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0821300000', 'Основное мероприятие "Обеспечение подготовки кадров для органов внутренних дел Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0821400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0821400000', 'Основное мероприятие "Реализация Государственной программы "Обеспечение безопасности потерпевших, свидетелей и иных участников уголовного судопроизводства на 2014 - 2018 годы""')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0821438990') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0821438990', 'Специальные мероприятия по государственной защите потерпевших, свидетелей и иных участников уголовного судопроизводства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0830000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0830000000', 'Подпрограмма "Внутренние войска Министерства внутренних дел  Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0830100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0830100000', 'Основное мероприятие "Совершенствование системы комплектования и организации служебно-боевой деятельности внутренних войск МВД России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0830200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0830200000', 'Основное мероприятие "Обеспечение подготовки кадров для внутренних войск МВД России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0840000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0840000000', 'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Обеспечение общественного порядка и противодействие преступности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0840100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0840100000', 'Основное мероприятие "Создание условий для формирования позитивного облика сотрудника органов внутренних дел и повышения уровня доверия к органам внутренних дел со стороны населения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0840200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0840200000', 'Основное мероприятие "Административное обеспечение"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0840239790') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0840239790', 'Единовременное пособие лицам, получившим ранения при осуществлении мероприятий по борьбе с терроризмом, не повлекшие наступления инвалидности')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0840300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0840300000', 'Основное мероприятие "Тыловое обеспечение"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0840400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0840400000', 'Основное мероприятие "Медицинское обеспечение"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0840500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0840500000', 'Основное мероприятие "Жилищное обеспечение"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0840535800') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0840535800', 'Субсидия для приобретения или строительства жилого помещения (жилых помещений), предоставляемая военнослужащим - гражданам Российской Федерации и иным лицам в соответствии с Федеральным законом от 27 мая 1998 года № 76-ФЗ "О статусе военнослужащих"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0840540310') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0840540310', 'Обеспечение военнослужащих федеральных органов исполнительной власти, в которых законом предусмотрена военная служба, служебными жилыми помещениями и жилыми помещениями в общежитиях')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0840540320') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0840540320', 'Строительство и приобретение жилых помещений для постоянного проживания военнослужащих федеральных органов исполнительной власти, в которых законом предусмотрена военная служба')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0850000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0850000000', 'Федеральная целевая программа "Повышение безопасности дорожного движения в 2013 - 2020 годах"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0900000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0900000000', 'Государственная программа Российской Федерации "Противодействие незаконному обороту наркотиков"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0910000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0910000000', 'Подпрограмма "Комплексные меры противодействия незаконному обороту наркотиков"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0910100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0910100000', 'Основное мероприятие "Реализация функций органов наркоконтроля"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0910200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0910200000', 'Основное мероприятие "Проведение оперативно-розыскных мероприятий, направленных на выявление, предупреждение, пресечение и раскрытие преступлений, связанных с незаконным оборотом наркотических средств и психотропных веществ"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0910300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0910300000', 'Основное мероприятие "Международное сотрудничество в сфере борьбы с незаконным оборотом наркотиков"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0910400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0910400000', 'Основное мероприятие "Обеспечение научной деятельности в интересах органов наркоконтроля"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0910500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0910500000', 'Основное мероприятие "Жилищное обеспечение сотрудников органов наркоконтроля"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0910600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0910600000', 'Основное мероприятие "Обеспечение реализации образовательных программ в интересах органов наркоконтроля"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0910700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0910700000', 'Основное мероприятие "Медицинское обеспечение сотрудников органов наркоконтроля"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0920000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0920000000', 'Подпрограмма "Координация антинаркотической деятельности федеральных органов исполнительной власти и органов исполнительной власти субъектов Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0920100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0920100000', 'Основное мероприятие "Проведение профилактических мероприятий и реализация государственных мер по усилению противодействия потреблению наркотиков"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0920200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0920200000', 'Основное мероприятие "Совершенствование государственной системы мониторинга наркоситуации в Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0930000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0930000000', 'Подпрограмма "Комплексная реабилитация и ресоциализация лиц, потребляющих наркотические средства и психотропные вещества в немедицинских целях"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0930100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0930100000', 'Основное мероприятие "Создание федеральной инфраструктуры комплексной реабилитации и ресоциализации лиц, потребляющих  наркотические средства и психотропные вещества в немедицинских целях"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='0930200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('0930200000', 'Основное мероприятие "Поддержка реализации региональных проектов по развитию инфраструктуры комплексной реабилитации и ресоциализации лиц, потребляющих  наркотические средства и психотропные вещества в немедицинских целях"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1000000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1000000000', 'Государственная программа Российской Федерации "Защита населения и территорий от чрезвычайных ситуаций, обеспечение пожарной безопасности и безопасности людей на водных объектах"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1010000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1010000000', 'Подпрограмма "Предупреждение, спасение, помощь"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1010100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1010100000', 'Основное мероприятие "Управление средствами резервного фонда Правительства Российской Федерации по предупреждению и ликвидации чрезвычайных ситуаций и последствий стихийных бедствий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1010120570') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1010120570', 'Резервный фонд Правительства Российской Федерации по предупреждению и ликвидации чрезвычайных ситуаций и последствий стихийных бедствий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1010200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1010200000', 'Основное мероприятие "Подготовка и реализация неотложных и внеплановых мероприятий по предупреждению и ликвидации чрезвычайных ситуаций"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1010264230') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1010264230', 'Субсидия федеральному государственному унитарному авиационному предприятию Министерства Российской Федерации по делам гражданской обороны, чрезвычайным ситуациям и ликвидации последствий стихийных бедствий')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1010300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1010300000', 'Основное мероприятие "Обеспечение повседневного функционирования подразделений МЧС России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1010339620') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1010339620', 'Обязательное государственное страхование жизни и здоровья лиц рядового и начальствующего состава договорных подразделений федеральной противопожарной службы Государственной противопожарной службы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1010400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1010400000', 'Основное мероприятие "Оснащение подразделений МЧС России современными образцами техники и оборудования в рамках государственного оборонного заказа"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1010500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1010500000', 'Основное мероприятие "Развитие инфраструктуры МЧС России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1010600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1010600000', 'Основное мероприятие "Организация и проведение противофонтанных работ на нефтяных и газовых скважинах"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1010700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1010700000', 'Основное мероприятие "Содействие деятельности некоммерческих организаций, осуществляющих деятельность в области защиты населения и территорий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1010800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1010800000', 'Основное мероприятие "Снижение рисков и смягчение последствий чрезвычайных ситуаций природного и техногенного характера"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1010900000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1010900000', 'Основное мероприятие "Преодоление последствий радиационных аварий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1011000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1011000000', 'Основное мероприятие "Развитие системы обеспечения пожарной безопасности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1011100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1011100000', 'Основное мероприятие "Повышение устойчивости жилых домов, основных объектов и систем жизнеобеспечения в сейсмических районах Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1011200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1011200000', 'Основное мероприятие "Развитие системы обеспечения вызова экстренных оперативных служб по единому номеру "112""')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1020000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1020000000', 'Подпрограмма "Обеспечение и управление"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1020100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1020100000', 'Основное мероприятие "Обеспечение повседневного функционирования подразделений центрального аппарата и территориальных подразделений МЧС России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1020200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1020200000', 'Основное мероприятие "Научное обеспечение деятельности МЧС России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1020300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1020300000', 'Основное мероприятие "Обеспечение жильем кадрового состава МЧС России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1020340310') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1020340310', 'Обеспечение военнослужащих федеральных органов исполнительной власти, в которых законом предусмотрена военная служба, служебными жилыми помещениями и жилыми помещениями в общежитиях')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1020340320') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1020340320', 'Строительство и приобретение жилых помещений для постоянного проживания военнослужащих федеральных органов исполнительной власти, в которых законом предусмотрена военная служба')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1020400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1020400000', 'Основное мероприятие "Финансовое обеспечение реализации программ высшего профессионального образования в области защиты населения и территорий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1020500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1020500000', 'Основное мероприятие "Обеспечение международного сотрудничества в установленной сфере деятельности МЧС России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1020600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1020600000', 'Основное мероприятие "Оценка рисков и минимизация недостижения целей и задач государственной программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1030000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1030000000', 'Подпрограмма "Развитие системы обеспечения промышленной безопасности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1030100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1030100000', 'Основное мероприятие "Создание информационно-технологической инфраструктуры системы обеспечения промышленной безопасности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1030200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1030200000', 'Основное мероприятие "Обеспечение проведения технологического надзора и федерального государственного надзора в области использования атомной энергии"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1030300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1030300000', 'Основное мероприятие "Осуществление международного сотрудничества в установленной сфере деятельности, направленного на совершенствование государственного регулирования технологической безопасности и безопасности при использовании атомной энергии в ми')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1030400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1030400000', 'Основное мероприятие "Обеспечение реализации подпрограммы"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1040000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1040000000', 'Федеральная целевая программа "Снижение рисков и смягчение последствий чрезвычайных ситуаций природного и техногенного характера в Российской Федерации до 2015 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1050000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1050000000', 'Федеральная целевая программа "Преодоление последствий радиационных аварий на период до 2015 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1050051070') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1050051070', 'Субсидии на реализацию мероприятий федеральной целевой программы "Преодоление последствий радиационных аварий на период до 2015 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1060000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1060000000', 'Федеральная целевая программа "Пожарная безопасность в Российской Федерации на период до 2017 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1060051710') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1060051710', 'Субсидии на реализацию мероприятий федеральной целевой программы "Пожарная безопасность в Российской Федерации на период до 2017 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1080000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1080000000', 'Федеральная целевая программа "Повышение устойчивости жилых домов, основных объектов и систем жизнеобеспечения в сейсмических районах Российской Федерации на 2009 - 2018 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1080051050') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1080051050', 'Субсидии на реализацию мероприятий федеральной целевой программы "Повышение устойчивости жилых домов, основных объектов и систем жизнеобеспечения в сейсмических районах Российской Федерации на 2009 - 2018 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1090000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1090000000', 'Федеральная целевая программа "Создание системы обеспечения вызова экстренных оперативных служб по единому номеру "112" в Российской Федерации на 2013 - 2017 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1090050980') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1090050980', 'Субсидии на реализацию мероприятий федеральной целевой программы "Создание системы обеспечения вызова экстренных оперативных служб по единому номеру "112" в Российской Федерации на 2013 - 2017 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='10Б0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('10Б0000000', 'Федеральная целевая программа "Национальная система химической и биологической безопасности Российской Федерации (2015 - 2020 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1100000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1100000000', 'Государственная программа Российской Федерации "Развитие культуры и туризма" на 2013 - 2020 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1110000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1110000000', 'Подпрограмма "Наследие"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1110112345') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1110112345', 'Основное мероприятие "Сохранение, использование, популяризация исторического и культурного наследия"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1110151450') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1110151450', 'Иные межбюджетные трансферты на мероприятия по реализации комплексного проекта "Культурное наследие - остров-град Свияжск и древний Болгар"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1110160850') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1110160850', 'Субсидия Общероссийской общественно-государственной организации "Российское военно-историческое общество"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1110162320') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1110162320', 'Субсидии Благотворительному фонду по восстановлению Воскресенского Ново-Иерусалимского ставропигиального мужского монастыря Русской Православной Церкви на воссоздание исторического облика монастыря')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1110200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1110200000', 'Основное мероприятие "Развитие библиотечного дела"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1110251440') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1110251440', 'Иные межбюджетные трансферты на комплектование книжных фондов библиотек муниципальных образований и государственных библиотек городов Москвы и Санкт-Петербурга')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1110251460') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1110251460', 'Иные межбюджетные трансферты на подключение общедоступных библиотек Российской Федерации к сети "Интернет" и развитие системы библиотечного дела с учетом задачи расширения информационных технологий и оцифровки')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1110300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1110300000', 'Основное мероприятие "Развитие музейного дела"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1110400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1110400000', 'Основное мероприятие "Развитие архивного дела"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120000000', 'Подпрограмма "Искусство"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120100000', 'Основное мероприятие "Сохранение и развитие исполнительских искусств"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120164900') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120164900', 'Поддержка государственных цирковых организаций')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120200000', 'Основное мероприятие "Сохранение и развитие кинематографии"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120264860') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120264860', 'Мероприятия в сфере культуры и кинематографии')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120264870') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120264870', 'Поддержка деятельности по производству анимационных фильмов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120300000', 'Основное мероприятие "Сохранение и развитие традиционной народной культуры, нематериального культурного наследия народов Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120400000', 'Основное мероприятие "Поддержка творческих инициатив населения, а также выдающихся деятелей, организаций в сфере культуры, творческих союзов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120430520') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120430520', 'Премии Правительства Российской Федерации в области культуры')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120430540') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120430540', 'Премии Правительства Российской Федерации "Душа России" за вклад в развитие народного творчества')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120451470') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120451470', 'Иные межбюджетные трансферты на государственную поддержку муниципальных учреждений культуры')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120451480') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120451480', 'Иные межбюджетные трансферты на государственную поддержку лучших работников муниципальных учреждений культуры, находящихся на территориях сельских поселений')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120451500') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120451500', 'Иные межбюджетные трансферты на гранты в области науки, культуры, искусства и средств массовой информации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120451510') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120451510', 'Иные межбюджетные трансферты на премии в области литературы и искусства, образования, печатных средств массовой информации, науки и техники и иные поощрения за особые заслуги перед государством')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120453940') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120453940', 'Иные межбюджетные трансферты на оказание государственной поддержки (грантов) театрам и музыкальным организациям, находящимся в ведении субъектов Российской Федерации и муниципальных образований, для реализации творческих проектов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120462290') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120462290', 'Субсидии некоммерческим организациям на оказание государственной поддержки (грантов) независимым театральным и музыкальным коллективам для реализации творческих проектов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120462330') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120462330', 'Субсидии творческим союзам')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120464860') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120464860', 'Мероприятия в сфере культуры и кинематографии')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120500000', 'Основное мероприятие "Организация и проведение мероприятий, а также работ по строительству, реконструкции, реставрации, посвященных значимым событиям российской культуры"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1120564860') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1120564860', 'Мероприятия в сфере культуры и кинематографии')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1130000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1130000000', 'Подпрограмма "Туризм"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1130100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1130100000', 'Основное мероприятие "Развитие внутреннего туризма"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1130130290') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1130130290', 'Премии Правительства Российской Федерации в области туризма')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1130200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1130200000', 'Основное мероприятие "Развитие международного туризма"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1140000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1140000000', 'Подпрограмма "Обеспечение условий реализации государственной программы Российской Федерации "Развитие культуры и туризма" на 2013 - 2020 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1140100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1140100000', 'Основное мероприятие "Развитие инфраструктуры и системы управления в сфере культуры и туризма"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1140200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1140200000', 'Основное мероприятие "Развитие фундаментальных и прикладных исследований в сфере культуры и туризма"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1150000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1150000000', 'Федеральная целевая программа "Культура России (2012 - 2018 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1150050140') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1150050140', 'Субсидии на реализацию мероприятий федеральной целевой программы "Культура России (2012 - 2018 годы)"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1160000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1160000000', 'Федеральная целевая программа "Развитие внутреннего и въездного туризма в Российской Федерации (2011 - 2018 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1160051100') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1160051100', 'Субсидии на реализацию мероприятий федеральной целевой программы "Развитие внутреннего и въездного туризма в Российской Федерации (2011 - 2018 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1170000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1170000000', 'Подпрограмма "Укрепление единства российской нации и этнокультурное развитие народов России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1170100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1170100000', 'Основное мероприятие "Выработка и реализация государственной национальной политики"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1170200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1170200000', 'Основное мероприятие "Государственная поддержка экономического и социального развития коренных малочисленных народов Севера, Сибири и Дальнего Востока Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1170250910') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1170250910', 'Иные межбюджетные трансферты на поддержку экономического и социального развития коренных малочисленных народов Севера, Сибири и Дальнего Востока')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1180000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1180000000', 'Федеральная целевая программа "Укрепление единства российской нации и этнокультурное развитие народов России (2014 - 2020 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1180052360') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1180052360', 'Субсидии на реализацию мероприятий федеральной целевой программы "Укрепление единства российской нации и этнокультурное развитие народов России (2014 - 2020 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1200000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1200000000', 'Государственная программа Российской Федерации "Охрана окружающей среды" на 2012 - 2020 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1210000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1210000000', 'Подпрограмма "Регулирование качества окружающей среды"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1210100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1210100000', 'Основное мероприятие "Нормативно-правовое, методическое и информационно-аналитическое обеспечение регулирования в области охраны окружающей среды"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1210200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1210200000', 'Основное мероприятие "Выполнение международных обязательств в области охраны окружающей среды"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1210300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1210300000', 'Основное мероприятие "Организация и проведение комплексного государственного экологического надзора,  разрешительной и лицензионной деятельности в части ограничения негативного техногенного воздействия на окружающую среду и экологической экспертизы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1210320470') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1210320470', 'Реализация государственных полномочий по проведению государственной экологической экспертизы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1220000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1220000000', 'Подпрограмма "Биологическое разнообразие России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1220100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1220100000', 'Основное мероприятие "Нормативно-правовое, методическое и информационно-аналитическое обеспечение деятельности  в сфере сохранения и восстановления биологического разнообразия"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1220200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1220200000', 'Основное мероприятие "Выполнение международных обязательств в сфере сохранения и восстановления биологического разнообразия"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1220300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1220300000', 'Основное мероприятие "Обеспечение охраны объектов животного мира"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1220400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1220400000', 'Основное мероприятие "Функционирование и развитие системы особо охраняемых природных территорий федерального значения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1230000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1230000000', 'Подпрограмма "Гидрометеорология и мониторинг окружающей среды"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1230100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1230100000', 'Основное мероприятие "Нормативно-правовое, методическое и информационно-аналитическое обеспечение деятельности  в сфере гидрометеорологии и мониторинга окружающей среды"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1230200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1230200000', 'Основное мероприятие "Развитие единой государственной системы экологического мониторинга"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1230300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1230300000', 'Основное мероприятие "Обеспечение функционирования и развития государственной наблюдательной сети, государственной системы наблюдений, системы получения, сбора и распространения информации в области гидрометеорологии и смежных с ней областях"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1230400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1230400000', 'Основное мероприятие "Исследования и разработка методов и технологий в сфере гидрометеорологии и мониторинга окружающей среды"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1230500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1230500000', 'Основное мероприятие "Обеспечение выполнения государственных функций в сфере гидрометеорологии и мониторинга окружающей среды и смежных с ней областях"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1230600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1230600000', 'Основное мероприятие "Выполнение международных обязательств в сфере гидрометеорологии и мониторинга окружающей среды и иное международное сотрудничество"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1240000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1240000000', 'Подпрограмма "Организация и обеспечение работ и научных исследований в Арктике и Антарктике"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1240100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1240100000', 'Основное мероприятие "Организация и проведение комплексных исследований и работ в Арктике и Антарктике"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1240163620') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1240163620', 'Субсидии некоммерческой организации "Фонд полярных исследований "Полярный фонд" на организацию дрейфующей станции "Северный полюс"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1240200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1240200000', 'Основное мероприятие "Нормативно-правовое обеспечение работ и научных исследований в Арктике и Антарктике "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1260000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1260000000', 'Федеральная целевая программа "Охрана озера Байкал и социально-экономическое развитие Байкальской природной территории на 2012 - 2020 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1270000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1270000000', 'Федеральная целевая программа "Создание и развитие системы мониторинга геофизической обстановки над территорией Российской Федерации на 2008 - 2015 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1280000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1280000000', 'Подпрограмма "Ликвидация накопленного экологического ущерба"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1280100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1280100000', 'Основное мероприятие "Нормативно-правовое обеспечение в сфере ликвидации накопленного экологического ущерба"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1280200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1280200000', 'Основное мероприятие "Подготовка и реализация проектов по ликвидации накопленных загрязнений бывших промышленных производств"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1280300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1280300000', 'Основное мероприятие "Поддержка региональных проектов в области обращения с отходами и ликвидации накопленного экологического ущерба"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1280400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1280400000', 'Основное мероприятие "Ликвидация последствий загрязнения и иного негативного воздействия на окружающую среду в результате экономической деятельности на особо охраняемых природных территориях федерального значения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1280500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1280500000', 'Основное мероприятие "Научно-методическое и аналитическое сопровождение, мониторинг и оценка реализации проектов по ликвидации накопленного экологического ущерба"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1280600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1280600000', 'Основное мероприятие "Ликвидация экологических и иных последствий ведения горных работ на ликвидируемых организациях угольной промышленности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1300000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1300000000', 'Государственная программа Российской Федерации "Развитие физической культуры и спорта"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1310000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1310000000', 'Подпрограмма "Развитие физической культуры и массового спорта"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1310100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1310100000', 'Основное мероприятие "Физическое воспитание и обеспечение организации и проведения физкультурных мероприятий и массовых спортивных мероприятий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1310151650') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1310151650', 'Иные межбюджетные трансферты на премирование регионов - победителей фестиваля "Кавказские игры"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1310200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1310200000', 'Основное мероприятие "Вовлечение населения в занятия физической культурой и массовым спортом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1310220150') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1310220150', 'Мероприятия, направленные на формирование здорового образа жизни у населения Российской Федерации, включая сокращение потребления алкоголя и табака')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1310262270') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1310262270', 'Субсидии Общероссийской общественно-государственной организации "Добровольное общество содействия армии, авиации и флоту России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1310300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1310300000', 'Основное мероприятие "Совершенствование спортивной инфраструктуры и материально-технической базы для занятий физической культурой и массовым спортом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1310350800') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1310350800', 'Субсидии на приобретение оборудования для быстровозводимых физкультурно-оздоровительных комплексов, включая металлоконструкции и металлоизделия')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1310400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1310400000', 'Основное мероприятие "Внедрение и реализация Всероссийского физкультурно-спортивного комплекса "Готов к труду и обороне""')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1310451270') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1310451270', 'Субсидии на реализацию мероприятий по поэтапному внедрению Всероссийского физкультурно-спортивного комплекса "Готов к труду и обороне" (ГТО)')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1310466790') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1310466790', 'Мероприятия по поэтапному внедрению Всероссийского физкультурно-спортивного комплекса "Готов к труду и обороне" (ГТО)')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1310500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1310500000', 'Основное мероприятие "Развитие студенческого спорта"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1310600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1310600000', 'Основное мероприятие "Организация и проведение научно-исследовательских и опытно-конструкторских работ в сфере физической культуры и массового спорта"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1320000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1320000000', 'Подпрограмма "Развитие спорта высших достижений и системы подготовки спортивного резерва"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1320100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1320100000', 'Основное мероприятие "Проведение спортивных мероприятий, обеспечение подготовки спортсменов высокого класса, материально-техническое обеспечение спортивных сборных команд Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1320130440') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1320130440', 'Стипендии Президента Российской Федерации спортсменам, тренерам и иным специалистам спортивных сборных команд Российской Федерации по видам спорта, включенным в программы Олимпийских игр, Паралимпийских игр и Сурдлимпийских игр, чемпионам Олимпийских')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1320162460') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1320162460', 'Реализация мероприятий, включенных в Единый календарный план межрегиональных, всероссийских и международных физкультурных мероприятий и спортивных мероприятий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1320200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1320200000', 'Основное мероприятие "Развитие системы подготовки спортивного резерва"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1320250810') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1320250810', 'Субсидии на адресную финансовую поддержку спортивных организаций, осуществляющих подготовку спортивного резерва для сборных команд Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1320300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1320300000', 'Основное мероприятие "Антидопинговое обеспечение спортивных сборных команд Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1320400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1320400000', 'Основное мероприятие "Подготовка и проведение особо значимых международных спортивных мероприятий  проводимых на территории Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1320451770') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1320451770', 'Иные межбюджетные трансферты на реализацию мероприятий по подготовке и проведению XXIX Всемирной зимней Универсиады 2019 года в г. Красноярске')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1320460600') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1320460600', 'Субсидия автономной некоммерческой организации "Исполнительная дирекция XXIX Всемирной зимней универсиады 2019 года в г. Красноярске"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1320462390') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1320462390', 'Субсидия автономной некоммерческой организации "Исполнительная дирекция XXVII Всемирной летней универсиады 2013 года в г. Казани"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1320500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1320500000', 'Основное мероприятие "Научно-методическое и информационно-аналитическое обеспечение подготовки спортсменов высокого класса, спортивных сборных команд Российской Федерации, и спортивного резерва"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1320600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1320600000', 'Основное мероприятие "Организация и проведение научно-исследовательских и опытно-конструкторских работ в сфере спорта высших достижений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1330000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1330000000', 'Подпрограмма "Подготовка и проведение Чемпионата мира по футболу ФИФА 2018 года и Кубка конфедераций ФИФА 2017 года в Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1330100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1330100000', 'Основное мероприятие "Обеспечение нормативно-правовых основ в целях подготовки и проведения Чемпионата мира по футболу ФИФА 2018 года и Кубка конфедераций 2017 года и реализации гарантий, взятых Правительством Российской Федерации перед ФИФА "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1330200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1330200000', 'Основное мероприятие "Развитие спортивной инфраструктуры для проведения Чемпионата мира по футболу ФИФА 2018 года и Кубка конфедераций ФИФА 2017 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1330251540') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1330251540', 'Иные межбюджетные трансферты на реализацию мероприятий по подготовке и проведению чемпионата мира по футболу в 2018 году в Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1330300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1330300000', 'Основное мероприятие "Организация подготовки и проведения Чемпионата мира по футболу ФИФА 2018 года и Кубка конфедераций ФИФА 2017 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1340000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1340000000', 'Подпрограмма "Управление развитием отрасли физической культуры и спорта"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1340100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1340100000', 'Основное мероприятие "Совершенствование нормативно-правовой базы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1340200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1340200000', 'Основное мероприятие "Реализация государственной политики в сфере физической культуры и спорта')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1340234940') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1340234940', 'Выплаты в области физической культуры, спорта и туризма')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1340300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1340300000', 'Основное мероприятие Проведение в Российской Федерации семинаров, конференций, форумов, конвенций в сфере физической культуры и спорта')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1340353930') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1340353930', 'Субсидии на проведение ежегодной Международной конвенции "СпортАккорд" в г. Сочи')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1340400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1340400000', 'Основное мероприятие "Развитие международного спортивного сотрудничества"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1340500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1340500000', 'Основное мероприятие "Внедрение современных информационно-коммуникационных технологий в сферу физической культуры и спорта"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1350000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1350000000', 'Федеральная целевая программа "Развитие физической культуры и спорта в Российской Федерации на 2006 - 2015 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1350050170') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1350050170', 'Субсидии на реализацию мероприятий подпрограммы "Развитие футбола в Российской Федерации на 2008 - 2015 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1350050950') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1350050950', 'Субсидии на финансовое обеспечение расходов общепрограммного характера по федеральной целевой программе "Развитие физической культуры и спорта в Российской Федерации на 2006 - 2015 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1360000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1360000000', 'Федеральная целевая программа "Развитие физической культуры и спорта в Российской Федерации на 2016 - 2020 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1360054950') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1360054950', 'Субсидии на финансовое обеспечение мероприятий федеральной целевой программы "Развитие физической культуры и спорта в Российской Федерации на 2016 - 2020 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1400000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1400000000', 'Государственная программа Российской Федерации "Развитие науки и технологий" на 2013 - 2020 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1410000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1410000000', 'Подпрограмма "Фундаментальные научные исследования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1410100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1410100000', 'Основное мероприятие "Выполнение фундаментальных научных исследований учреждениями государственных академий наук, финансовое обеспечение государственных академий наук"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1410130280') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1410130280', 'Государственные научные стипендии для выдающихся ученых России и для талантливых молодых ученых России в соответствии с Указом Президента Российской Федерации от 16 сентября 1993 года № 1372 "О мерах по материальной поддержке ученых России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1410200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1410200000', 'Основное мероприятие "Выполнение фундаментальных научных исследований по приоритетным направлениям, определяемым Российской академией наук"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1410300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1410300000', 'Основное мероприятие "Выполнение фундаментальных научных исследований государственными учреждениями, не являющимися учреждениями государственных академий наук"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1410400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1410400000', 'Основное мероприятие "Грантовое финансирование фундаментальных исследований Российским гуманитарным научным фондом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1410500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1410500000', 'Основное мероприятие "Грантовое финансирование фундаментальных исследований Российским фондом фундаментальных исследований"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1410600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1410600000', 'Основное мероприятие "Грантовое финансирование фундаментальных научных исследований Российским научным фондом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1410665900') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1410665900', 'Имущественный взнос Российской Федерации в Российский научный фонд')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1410700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1410700000', 'Основное мероприятие "Гранты Президента Российской Федерации и Правительства Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1420000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1420000000', 'Подпрограмма "Развитие сектора прикладных научных исследований и разработок"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1420100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1420100000', 'Основное мероприятие "Выполнение прикладных научных исследований НИЦ "Курчатовский институт" и другими государственными учреждениями, не подведомственными Минобрнауки России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1420200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1420200000', 'Основное мероприятие "Обеспечение деятельности подведомственных учреждений Минобрнауки России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1430000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1430000000', 'Подпрограмма "Институциональное развитие научно-исследовательского сектора"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1430100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1430100000', 'Основное мероприятие "Поддержка развития научной кооперации образовательных организаций высшего образования, государственных научных организаций с предприятиями высокотехнологичных секторов экономики"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1430164820') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1430164820', 'Субсидии на государственную поддержку развития кооперации российских образовательных организаций высшего образования, государственных научных учреждений и организаций, реализующих комплексные проекты по созданию высокотехнологичного производства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1430200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1430200000', 'Основное мероприятие "Поддержка научных исследований, проводимых под руководством ведущих ученых"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1430261460') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1430261460', 'Субсидии на предоставление грантов Правительства Российской Федерации, выделяемых для государственной поддержки научных исследований, проводимых под руководством ведущих ученых в российских образовательных учреждениях высшего профессионального образо')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1430300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1430300000', 'Основное мероприятие "Совершенствование системы оплаты труда научных работников"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1430400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1430400000', 'Основное мероприятие "Развитие и поддержка социальной, инженерной и инновационной инфраструктуры наукоградов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1430451580') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1430451580', 'Иные межбюджетные трансферты на развитие и поддержку социальной, инженерной и инновационной инфраструктуры наукоградов Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1430500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1430500000', 'Основное мероприятие "Реализация на территории Российской Федерации проектов создания крупных научных установок класса мега-сайенс"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1430600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1430600000', 'Основное мероприятие "Обеспечение выплаты государственных премий Российской Федерации, премий Правительства Российской Федерации, иных премий и выплат в области науки и техники, стипендий Президента Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1430630460') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1430630460', 'Стипендия Президента Российской Федерации для молодых ученых и аспирантов, осуществляющих перспективные научные исследования и разработки по приоритетным направлениям модернизации российской экономики')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1430630480') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1430630480', 'Премии Правительства Российской Федерации в области науки и техники ученым и специалистам')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1430630500') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1430630500', 'Премии Правительства Российской Федерации в области науки и техники для молодых ученых')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1430700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1430700000', 'Основное мероприятие "Управленческое, информационно-аналитическое, организационно-техническое обеспечение и мониторинг реализации мероприятий Государственной программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1430800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1430800000', 'Основное мероприятие "Обеспечение деятельности Федерального агентства научных организаций"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1450000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1450000000', 'Подпрограмма "Международное сотрудничество в сфере науки"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1450100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1450100000', 'Основное мероприятие "Обеспечение реализации соглашений с правительствами иностранных государств и международными организациями в части обеспечения научно-исследовательской деятельности ученых за рубежом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1450200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1450200000', 'Основное мероприятие "Выполнение финансовых обязательств Российской Федерации в рамках соглашения стран Евразийского экономического сообщества"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1450300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1450300000', 'Основное мероприятие "Обеспечение уплаты взносов Российской Федерации в международные научные организации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1450400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1450400000', 'Основное мероприятие "Участие Российской Федерации в крупных научно-исследовательских проектах"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1450464630') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1450464630', 'Субсидии открытому акционерному обществу "РОСНАНО" на возмещение расходов по оплате целевого взноса на строительство установки Европейского рентгеновского лазера на свободных электронах')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1470000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1470000000', 'Федеральная целевая программа "Исследования и разработки по приоритетным направлениям развития научно-технологического комплекса России на 2014 - 2020 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1500000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1500000000', 'Государственная программа Российской Федерации "Экономическое развитие и инновационная экономика"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1510000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1510000000', 'Подпрограмма "Инвестиционный климат"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1510100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1510100000', 'Основное мероприятие "Создание благоприятных условий для привлечения инвестиций в экономику Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1510200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1510200000', 'Основное мероприятие "Совершенствование корпоративного управления"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1510300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1510300000', 'Основное мероприятие "Повышение качества оценки регулирующего воздействия нормативных правовых актов и их проектов"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1510400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1510400000', 'Основное мероприятие "Развитие особых экономических зон"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1510463940') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1510463940', 'Взнос в уставный капитал открытого акционерного общества "Особые экономические зоны"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1510467350') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1510467350', 'Взнос в уставный капитал открытого акционерного общества "Особые экономические зоны", г. Москва, для участия в проекте создания особой экономической зоны промышленно-производственного типа в городе Владивостоке')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1510500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1510500000', 'Основное мероприятие "Создание благоприятной конкурентной среды"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1510600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1510600000', 'Основное мероприятие "Совершенствование контроля за применением антимонопольного законодательства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1510700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1510700000', 'Основное мероприятие "Создание условий для эффективной реализации государственной политики в области контроля иностранных инвестиций в хозяйственные общества, имеющие стратегическое значение"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1510800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1510800000', 'Основное мероприятие "Формирование и развитие  контрактной системы в сфере закупок"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1510900000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1510900000', 'Основное мероприятие "Содействие развитию моногородов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1510962300') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1510962300', 'Субсидии некоммерческой организации "Фонд развития моногородов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1520000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1520000000', 'Подпрограмма "Развитие малого и среднего предпринимательства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1520100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1520100000', 'Основное мероприятие "Федеральная финансовая программа поддержки малого и среднего предпринимательства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1520150640') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1520150640', 'Субсидии на государственную поддержку малого и среднего предпринимательства, включая крестьянские (фермерские) хозяйства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1520200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1520200000', 'Основное мероприятие "Совершенствование нормативно-правового регулирования малого и среднего предпринимательства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1520300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1520300000', 'Основное мероприятие "Формирование национальной системы гарантийных организаций для субъектов малого и среднего предпринимательства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1530000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1530000000', 'Подпрограмма "Государственная регистрация прав, кадастр и картография"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1530100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1530100000', 'Основное мероприятие "Обеспечение государственного кадастрового учета, государственной регистрации прав и картографии"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1530200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1530200000', 'Основное мероприятие "Землеустройство и мониторинг состояния и использования земельных ресурсов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1530300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1530300000', 'Основное мероприятие "Развитие инфраструктуры пространственных данных Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1530400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1530400000', 'Основное мероприятие "Совершенствование нормативно-правового регулирования в сфере реализации подпрограммы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1540000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1540000000', 'Подпрограмма "Совершенствование системы государственного управления"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1540100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1540100000', 'Основное мероприятие "Совершенствование предоставления государственных услуг и исполнения государственных функций"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1540153920') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1540153920', 'Иные межбюджетные трансферты на создание и развитие сети многофункциональных центров предоставления государственных и муниципальных услуг')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1540200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1540200000', 'Основное мероприятие "Улучшение регуляторной среды"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1540300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1540300000', 'Основное мероприятие "Формирование единой национальной системы аккредитации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1550000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1550000000', 'Подпрограмма "Стимулирование инноваций"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1550100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1550100000', 'Основное мероприятие "Стимулирование спроса на инновации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1550200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1550200000', 'Основное мероприятие "Поддержка малого инновационного предпринимательства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1550300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1550300000', 'Основное мероприятие "Поддержка регионов - инновационных лидеров"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1550353890') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1550353890', 'Субсидии на реализацию комплексных инвестиционных проектов по развитию инновационных территориальных кластеров')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1550400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1550400000', 'Основное мероприятие "Создание университетского комплекса в территориально обособленном инновационном центре "Иннополис""')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1550500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1550500000', 'Основное мероприятие "Проведение исследований в целях инновационного развития экономики"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1550600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1550600000', 'Основное мероприятие "Развитие механизмов правовой охраны и защиты интеллектуальной собственности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1550700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1550700000', 'Основное мероприятие "Содействие развитию современной инновационной инфраструктуры в сфере нанотехнологий, механизмов и инструментов для реализации потенциала наноиндустрии"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1550763200') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1550763200', 'Субсидии Фонду инфраструктурных и образовательных программ на развитие наноиндустрии с помощью инфраструктурных и образовательных программ')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1560000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1560000000', 'Подпрограмма "Регулирование инфраструктурных отраслей"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1560100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1560100000', 'Основное мероприятие "Государственное регулирование, включая ценовое (тарифное) регулирование и поведенческие стандарты и правила"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1560200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1560200000', 'Основное мероприятие "Государственный контроль, досудебное урегулирование споров и рассмотрение разногласий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1560300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1560300000', 'Основное мероприятие "Развитие институциональной среды регулирования, включая совершенствование нормативной правовой базы, системы регулирования, единой среды электронного регулирования, международного сотрудничества"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1570000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1570000000', 'Подпрограмма "Управленческие кадры"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1570100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1570100000', 'Основное мероприятие "Подготовка управленческих кадров для организаций народного хозяйства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1570150660') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1570150660', 'Субсидии на подготовку управленческих кадров для организаций народного хозяйства Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1570200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1570200000', 'Основное мероприятие "Организация и проведение обучения по дополнительным профессиональным программам за рубежом, в том числе в рамках взаимных обменов с иностранными государствами на основе конкурсного отбора проектов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1570300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1570300000', 'Основное мероприятие "Повышение качества и информационно-технологического обеспечения образовательных программ и контроль качества подготовки специалистов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1570400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1570400000', 'Основное мероприятие "Подготовка управленческих кадров в сфере здравоохранения, образования и культуры"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1580000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1580000000', 'Подпрограмма "Совершенствование системы государственного стратегического управления"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1580100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1580100000', 'Основное мероприятие "Развитие государственного стратегического планирования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1580200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1580200000', 'Основное мероприятие "Разработка прогнозов социально-экономического развития Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1580300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1580300000', 'Основное мероприятие "Реализация механизмов стратегического управления социально-экономическим развитием субъектов Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1580400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1580400000', 'Основное мероприятие "Разработка предложений по совершенствованию и участие в реализации государственной политики в отдельных секторах экономики"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1580500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1580500000', 'Основное мероприятие "Разработка предложений по совершенствованию и участие в реализации государственной политики в социальной сфере"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1580600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1580600000', 'Основное мероприятие "Формирование расходов инвестиционного характера, формирование и реализация федеральной адресной инвестиционной программы на очередной год и плановый период"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1580700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1580700000', 'Основное мероприятие "Создание условий для эффективной разработки и реализации федеральных целевых программ и целевых программ ведомств"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1580800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1580800000', 'Основное мероприятие "Научно-аналитическое обеспечение развития стратегического планирования и прогнозирования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1590000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1590000000', 'Подпрограмма "Официальная статистика"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1590100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1590100000', 'Основное мероприятие "Обеспечение выполнения комплекса работ по реализации Федерального плана статистических работ"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1590200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1590200000', 'Основное мероприятие "Подготовка, проведение и подведение итогов всероссийских переписей населения (микропереписей)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1590300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1590300000', 'Основное мероприятие "Подготовка, проведение и подведение итогов всероссийских сельскохозяйственных переписей"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1590353910') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1590353910', 'Субвенции на проведение Всероссийской сельскохозяйственной переписи в 2016 году')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1590400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1590400000', 'Основное мероприятие "Разработка базовых таблиц "затраты - выпуск" и подготовка, проведение и подведение итогов сплошного федерального статистического наблюдения за деятельностью субъектов малого и среднего предпринимательства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1590500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1590500000', 'Основное мероприятие "Организация системы федеральных статистических наблюдений по социально-демографическим проблемам и мониторинга  экономических потерь от смертности, заболеваемости и инвалидизации населения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1590600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1590600000', 'Основное мероприятие "Организация и проведение  выборочных обследований отдельных аспектов занятости населения и оплаты труда"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1590700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1590700000', 'Основное мероприятие "Развитие системы государственной статистики"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='15Б0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('15Б0000000', 'Подпрограмма "Создание и развитие инновационного центра "Сколково"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='15Б0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('15Б0100000', 'Основное мероприятие "Создание и развитие инновационной среды"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='15Б0162180') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('15Б0162180', 'Субсидии некоммерческой организации Фонд развития Центра разработки и коммерциализации новых технологий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='15Б0162190') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('15Б0162190', 'Субсидии некоммерческой организации Фонд развития Центра разработки и коммерциализации новых технологий на компенсацию затрат участников проекта создания инновационного центра "Сколково" по уплате таможенных платежей')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='15Б0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('15Б0200000', 'Основное мероприятие "Создание и развитие Сколковского института науки и технологий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='15Б0262180') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('15Б0262180', 'Субсидии некоммерческой организации Фонд развития Центра разработки и коммерциализации новых технологий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='15Б0300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('15Б0300000', 'Основное мероприятие "Создание и управление физической инфраструктурой инновационного центра "Сколково""')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='15Б0362180') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('15Б0362180', 'Субсидии некоммерческой организации Фонд развития Центра разработки и коммерциализации новых технологий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='15Б0362190') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('15Б0362190', 'Субсидии некоммерческой организации Фонд развития Центра разработки и коммерциализации новых технологий на компенсацию затрат участников проекта создания инновационного центра "Сколково" по уплате таможенных платежей')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='15Г0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('15Г0000000', 'Федеральная целевая программа "Развитие единой государственной системы регистрации прав и кадастрового учета недвижимости (2014 - 2019 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='15Г0054150') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('15Г0054150', 'Субсидии на реализацию в Крымском федеральном округе мероприятий федеральной целевой программы "Развитие единой государственной системы регистрации прав и кадастрового учета недвижимости (2014 - 2019 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1600000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1600000000', 'Государственная программа Российской Федерации "Развитие промышленности и повышение ее конкурентоспособности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1610000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1610000000', 'Подпрограмма "Развитие транспортной промышленности и промышленного специализированного машиностроения"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1610100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1610100000', 'Основное мероприятие "Развитие российских организаций автомобилестроения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1610151730') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1610151730', 'Субсидии на закупку автобусов и техники для жилищно-коммунального хозяйства, работающих на газомоторном топливе')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1610164660') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1610164660', 'Субсидии организациям автомобилестроения на перевозку автомобилей, произведенных на территории Дальневосточного федерального округа, в другие регионы страны')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1610164700') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1610164700', 'Субсидии российским организациям автомобилестроения, в том числе их дочерним организациям, на возмещение части затрат на уплату процентов по кредитам, полученным на реализацию инвестиционных и инновационных проектов и (или) выплату купонного дохода п')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1610164980') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1610164980', 'Субсидии на возмещение части затрат организациям и индивидуальным предпринимателям, осуществляющим деятельность по обращению с отходами, образовавшимися в результате утраты колесными транспортными средствами (шасси), в отношении которых уплачен утили')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1610165200') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1610165200', 'Субсидии российским кредитным организациям на возмещение выпадающих доходов по кредитам, выданным российскими кредитными организациями в 2013 - 2014 годах физическим лицам на приобретение автомобилей')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1610166730') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1610166730', 'Субсидии российским производителям колесных транспортных средств на компенсацию части затрат на содержание рабочих мест')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1610166750') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1610166750', 'Субсидии российским производителям колесных транспортных средств на компенсацию части затрат, связанных с выпуском и поддержкой гарантийных обязательств по колесным транспортным средствам, соответствующим нормам Евро-4, Евро-5')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1610166760') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1610166760', 'Субсидии российским производителям колесных транспортных средств на компенсацию части затрат на использование энергоресурсов энергоемкими предприятиями автомобильной промышленности')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1610200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1610200000', 'Основное мероприятие "Развитие транспортного машиностроения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1610254800') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1610254800', 'Субсидии на закупку троллейбусов и трамвайных вагонов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1610263960') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1610263960', 'Субсидии на возмещение потерь в доходах российских лизинговых организаций при предоставлении скидки при условии приобретения инновационных вагонов с повышенной осевой нагрузкой, а также на возмещение части затрат российским организациям на уплату про')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1610264710') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1610264710', 'Субсидии российским организациям транспортного машиностроения на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государственной корпорации "Банк развития и внешнеэкономической деятельности')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1610300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1610300000', 'Основное мероприятие "Стимулирование сельскохозяйственного машиностроения, машиностроения для пищевой и перерабатывающей промышленности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1610400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1610400000', 'Основное мероприятие "Поддержка развития машиностроения специализированных производств (строительно-дорожная и коммунальная техника, пожарная, аэродромная, лесная техника)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1620000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1620000000', 'Подпрограмма "Развитие производства средств производства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1620100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1620100000', 'Основное мероприятие "Создание условий для импортозамещения продукции станкоинструментальных производств"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1620166720') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1620166720', 'Имущественный взнос Российской Федерации в Государственную корпорацию по содействию разработке, производству и экспорту высокотехнологичной промышленной продукции "Ростех" на цели реализации проектов по созданию серийных производств станкоинструмента')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1620168480') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1620168480', 'Субсидии российским организациям на компенсацию части затрат на проведение научно-исследовательских и опытно-конструкторских работ в рамках реализации комплексных проектов по организации серийных производств станкоинструментальной продукции')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1620200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1620200000', 'Основное мероприятие "Инновационное развитие предприятий тяжелого машиностроения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1620300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1620300000', 'Основное мероприятие "Стимулирование развития предприятий силовой электротехники и энергетического машиностроения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1620400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1620400000', 'Основное мероприятие "Разработка отечественного инженерного программного обеспечения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630000000', 'Подпрограмма "Поддержка традиционных и развитие новых материалов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630100000', 'Основное мероприятие "Развитие металлургии и промышленности редких и редкоземельных металлов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630168370') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630168370', 'Субсидии российским организациям на компенсацию части затрат на захоронение радиоактивных отходов (обращение с радиоактивными отходами)')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630168450') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630168450', 'Субсидии российским организациям на компенсацию процентных ставок по инвестиционным кредитам в сфере производства редких и редкоземельных металлов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630200000', 'Основное мероприятие "Развитие предприятий лесопромышленного комплекса"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630264690') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630264690', 'Субсидии организациям лесопромышленного комплекса на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях в 2011 - 2014 годах на создание межсезонных запасов древесины, сырья и топлива')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630264770') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630264770', 'Субсидии организациям лесопромышленного комплекса на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государственной корпорации "Банк развития и внешнеэкономической деятельности (Внешэкономб')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630268210') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630268210', 'Субсидии организациям лесопромышленного комплекса на возмещение части затрат на обслуживание кредитов, полученных в российских кредитных организациях в 2011 - 2015 годах на цели формирования сезонных запасов сырья, материалов и топлива')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630268220') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630268220', 'Субсидии организациям лесопромышленного комплекса на возмещение части затрат на обслуживание кредитов, привлеченных в 2012 - 2015 годах, на цели реализации инвестиционных проектов создания новых высокотехнологичных обрабатывающих производств по компл')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630268690') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630268690', 'Субсидии российским лесоперерабатывающим предприятиям Дальневосточного федерального округа, участвующим в реализации приоритетных инвестиционных проектов в области освоения лесов, на возмещение части затрат, осуществленных в 2013 - 2015 годах на реал')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630300000', 'Основное мероприятие "Стимулирование развития химического комплекса"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630368400') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630368400', 'Субсидии российским предприятиям (организациям) химического комплекса на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государственной корпорации "Банк развития и внешнеэкономической деяте')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630400000', 'Основное мероприятие "Развитие производства композиционных материалов (композитов) и изделий из них"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630468430') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630468430', 'Субсидии на поддержку развития производства композиционных материалов (композитов) и изделий из них в рамках реализации российскими организациями комплексных инновационных проектов по созданию высокотехнологичной продукции')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630500000', 'Основное мероприятие "Стимулирование развития организаций промышленных биотехнологий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630568340') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630568340', 'Субсидии российским организациям лесопромышленного комплекса на компенсацию части затрат на реализацию комплексных инвестиционных проектов по созданию новых производств с применением промышленных биотехнологий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1630568390') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1630568390', 'Субсидии российским организациям химического комплекса на компенсацию части затрат, понесенных в 2014 - 2016 годах, на реализацию комплексных инвестиционных проектов по созданию новых производств с применением промышленных биотехнологий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1640000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1640000000', 'Подпрограмма "Развитие производства легкой промышленности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1640100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1640100000', 'Основное мероприятие "Стимулирование развития легкой промышленности "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1640164640') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1640164640', 'Субсидии организациям легкой и текстильной промышленности на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях в 2011 - 2014 годах, на осуществление сезонных закупок сырья и материалов для произво')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1640164650') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1640164650', 'Субсидии организациям легкой и текстильной промышленности на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях в 2006 - 2012 годах, на осуществление технического перевооружения')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1640167190') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1640167190', 'Субсидии организациям легкой и текстильной промышленности на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях в 2013 - 2015 годах, на реализацию новых инвестиционных проектов по техническому пере')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1640168380') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1640168380', 'Субсидии организациям легкой и текстильной промышленности на компенсацию части затрат на реализацию инвестиционных проектов по модернизации и созданию производств в сфере текстильной и легкой промышленности, в том числе льняного комплекса')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1640168670') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1640168670', 'Субсидии организациям легкой промышленности на возмещение части затрат на обслуживание кредитов, привлеченных в российских кредитных организациях в 2012 - 2016 годах, на цели формирования межсезонных запасов, необходимых для производства товаров легк')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1640200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1640200000', 'Основное мероприятие "Поддержка производства и реализации изделий народных художественных промыслов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1640264620') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1640264620', 'Субсидии организациям народных художественных промыслов на поддержку производства и реализации изделий народных художественных промыслов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1640300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1640300000', 'Основное мероприятие "Стимулирование развития производства индустрии детских товаров"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1640362480') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1640362480', 'Субсидии российским управляющим организациям индустриальных парков индустрии детских товаров на возмещение части затрат на создание и (или) развитие имущественного комплекса, в том числе инфраструктуры индустриальных парков индустрии детских товаров')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1640362500') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1640362500', 'Субсидии российским организациям на компенсацию части затрат на проведение научно-исследовательских и опытно-конструкторских работ в рамках реализации комплексных инвестиционных проектов индустрии детских товаров')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1640364840') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1640364840', 'Субсидии российским организациям на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях в 2013 - 2016 годах, на реализацию приоритетных инвестиционных проектов индустрии детских товаров, а также на')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1640400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1640400000', 'Основное мероприятие "Противодействие теневому производству и несанкционированному импорту продукции текстильной и легкой промышленности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1650000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1650000000', 'Подпрограмма "Содействие в реализации инвестиционных проектов в гражданских отраслях промышленности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1650100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1650100000', 'Основное мероприятие "Создание условий реализации приоритетных инвестиционных проектов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1650164760') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1650164760', 'Субсидии российским организациям сельскохозяйственного и тракторного машиностроения, лесопромышленного комплекса, машиностроения для нефтегазового комплекса и станкоинструментальной промышленности и предприятиям спецметаллургии на возмещение части за')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1650168000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1650168000', 'Субсидии российским организациям на компенсацию части затрат на реализацию пилотных проектов в области инжиниринга и промышленного дизайна')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1650168230') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1650168230', 'Субсидии российским организациям сельскохозяйственного и тракторного машиностроения, лесопромышленного комплекса, машиностроения для нефтегазового комплекса и станкоинструментальной промышленности и предприятиям спецметаллургии на возмещение части за')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1650168350') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1650168350', 'Субсидии российским организациям на компенсацию части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях в 2014 - 2016 годах на реализацию новых комплексных инвестиционных проектов по приоритетным направлениям граж')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1650200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1650200000', 'Основное мероприятие "Обеспечение деятельности Фонда развития промышленности в целях поддержки реализации инвестиционных проектов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1650300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1650300000', 'Основное мероприятие "Поддержка текущей деятельности организаций промышленности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1650368680') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1650368680', 'Субсидии организациям промышленности для возмещения части затрат, понесенных в 2015 году на уплату процентов по кредитам, полученным в российских кредитных организациях и государственной корпорации "Банк развития и внешнеэкономической деятельности (В')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1660000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1660000000', 'Подпрограмма "Содействие проведению научных исследований и опытных разработок в гражданской промышленности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1660100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1660100000', 'Основное мероприятие "Поддержка научно-исследовательских и опытно-конструкторских работ в гражданских отраслях промышленности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1660164110') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1660164110', 'Субсидии российским операторам услуг на возмещение части затрат на приобретение специализированного инжинирингового программного обеспечения с целью повышения доступности специализированного инжинирингового программного обеспечения для конечных польз')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1660168460') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1660168460', 'Субсидии российским организациям на компенсацию части затрат на проведение научно-исследовательских и опытно-конструкторских работ по приоритетным направлениям гражданской промышленности в рамках реализации такими организациями комплексных инвестицио')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1660200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1660200000', 'Основное мероприятие "Исследования и сопровождение приоритетных и инновационных проектов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1660267180') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1660267180', 'Реализация пилотного проекта по разработке и постановке на производство отечественных автомобилей на базе единой модульной платформы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1660300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1660300000', 'Основное мероприятие "Развитие научно-технологической инфраструктуры"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1660400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1660400000', 'Основное мероприятие "Сопровождение реализации новой научно-технической политики"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1670000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1670000000', 'Подпрограмма "Поддержка экспорта высокотехнологичной промышленной продукции"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1670100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1670100000', 'Основное мероприятие "Аналитическая поддержка экспортеров промышленной продукции"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1670200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1670200000', 'Основное мероприятие "Стимулирование экспортеров высокотехнологичной промышленной продукции "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1670265110') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1670265110', 'Имущественный взнос в государственную корпорацию "Банк развития и внешнеэкономической деятельности (Внешэкономбанк)" на возмещение части затрат, связанных с поддержкой производства высокотехнологичной продукции')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1670268700') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1670268700', 'Субсидии Государственному специализированному Российскому экспортно-импортному банку (акционерное общество) в целях компенсации недополученных доходов по кредитам, выдаваемым в рамках поддержки производства высокотехнологичной продукции')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1680000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1680000000', 'Подпрограмма "Развитие региональной промышленной инфраструктуры"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1680100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1680100000', 'Основное мероприятие "Стимулирование создания и развития индустриальных (промышленных) парков и технопарков"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1680164490') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1680164490', 'Субсидии российским организациям на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государственной корпорации "Банк развития и внешнеэкономической деятельности (Внешэкономбанк)" в 2013 - 20')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1680200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1680200000', 'Основное мероприятие "Поддержка реализации региональных программ развития промышленности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1680300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1680300000', 'Основное мероприятие "Сопровождение региональных программ развития промышленности "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='16Д0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('16Д0000000', 'Подпрограмма "Развитие системы технического регулирования, стандартизации и обеспечение единства измерений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='16Д0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('16Д0100000', 'Основное мероприятие "Развитие системы технического регулирования и стандартизации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='16Д0160660') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('16Д0160660', 'Субсидии автономной некоммерческой организации "Российская система качества"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='16Д0164600') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('16Д0164600', 'Субсидии организациям на создание и ведение Федерального информационного фонда технических регламентов и стандартов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='16Д0167400') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('16Д0167400', 'Субсидии на разработку международных, региональных и национальных документов в области стандартизации, обеспечивающих применение и исполнение требований технических регламентов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='16Д0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('16Д0200000', 'Основное мероприятие "Обеспечение единства измерений и развитие эталонной базы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='16Д0264610') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('16Д0264610', 'Субсидии организациям на осуществление расходов в области обеспечения единства измерений')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='16Д0300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('16Д0300000', 'Основное мероприятие "Выполнение научно-исследовательских и опытно-конструкторских работ в области технического регулирования, стандартизации, обеспечения единства измерений, информации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='16Д0400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('16Д0400000', 'Основное мероприятие "Ведомственная целевая программа "Проведение фундаментальных исследований в области метрологии, разработки государственных (в том числе, первичных) единиц величин"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='16Д0500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('16Д0500000', 'Основное мероприятие "Разработка и утверждение отраслевых справочников наилучших доступных технологий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='16Д0600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('16Д0600000', 'Основное мероприятие "Обеспечение деятельности Росстандарта"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1700000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1700000000', 'Государственная программа Российской Федерации "Развитие авиационной промышленности на 2013 - 2025 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1710000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1710000000', 'Подпрограмма "Самолетостроение"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1710100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1710100000', 'Основное мероприятие "Государственная поддержка российских организаций самолетостроения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1710164680') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1710164680', 'Субсидии организациям авиационной промышленности, осуществляющим деятельность в области самолетостроения, на компенсацию затрат на уплату купонного дохода по облигационным займам, привлеченным с предоставлением в 2010 году государственных гарантий Ро')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1710164740') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1710164740', 'Субсидии российским лизинговым компаниям на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государственной корпорации "Банк развития и внешнеэкономической деятельности (Внешэкономбанк)" в 2')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1710166630') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1710166630', 'Взнос в уставный капитал открытого акционерного общества "Объединенная авиастроительная корпорация", г. Москва, в целях последующего взноса в уставный капитал специализированной компании - дочернего общества в целях реализации механизма гарантии оста')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1710167420') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1710167420', 'Субсидии изготовителям воздушных судов на возмещение части затрат на формирование первоначального склада запасных частей покупателей воздушных судов, обеспечение средствами наземного обслуживания, переподготовку авиационного персонала для воздушных с')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1710167680') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1710167680', 'Субсидии российским компаниям на компенсацию части затрат на реализацию проектов по созданию сети авиационных сервисных центров, оказывающих поддержку по системе 24/365 на глобальном уровне')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1710167750') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1710167750', 'Субсидии компаниям - производителям воздушных судов для местных и региональных воздушных линий на компенсацию части затрат на сертификацию таких воздушных судов, а также на компенсацию части затрат на реализацию проектов по подготовке и сертификации')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1710200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1710200000', 'Основное мероприятие "Выполнение научно-исследовательских и опытно-конструкторских работ в области самолетостроения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1720000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1720000000', 'Подпрограмма "Вертолетостроение"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1720100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1720100000', 'Основное мероприятие "Государственная поддержка российских организаций вертолетостроения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1720200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1720200000', 'Основное мероприятие "Выполнение научно-исследовательских и опытно-конструкторских работ в области вертолетостроения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1730000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1730000000', 'Подпрограмма "Авиационное двигателестроение"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1730100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1730100000', 'Основное мероприятие "Государственная поддержка российских организаций отрасли авиационного двигателестроения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1730163950') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1730163950', 'Взнос в уставный капитал открытого акционерного общества "Объединенная промышленная корпорация "Оборонпром", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1730163990') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1730163990', 'Взнос в уставный капитал открытого акционерного общества "Объединенная промышленная корпорация "Оборонпром", г. Москва, в целях уплаты купонного дохода по облигационным займам, привлекаемым открытым акционерным обществом "Объединенная промышленная ко')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1730167600') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1730167600', 'Имущественный взнос Российской Федерации в Государственную корпорацию по содействию разработке, производству и экспорту высокотехнологичной промышленной продукции "Ростех" с целью последующего взноса в уставный капитал акционерного общества "Объедине')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1730167660') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1730167660', 'Субсидии российским организациям авиационной промышленности, осуществляющим деятельность в области авиационного двигателестроения, на компенсацию процентов по долгосрочным кредитам, полученным в российских кредитных организациях и в государственной к')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1730167700') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1730167700', 'Субсидии российским компаниям отрасли авиационного двигателестроения на компенсацию затрат на уплату купонного дохода по облигационным займам, привлекаемым с предоставлением государственных гарантий Российской Федерации на финансирование работ, связа')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1730200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1730200000', 'Основное мероприятие "Выполнение научно-исследовательских и опытно-конструкторских работ в области авиационного двигателестроения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1740000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1740000000', 'Подпрограмма "Авиационные агрегаты и приборы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1740100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1740100000', 'Основное мероприятие "Государственная поддержка российских организаций в сфере создания и производства современного авиационного бортового электронного оборудования и агрегатов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1740167710') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1740167710', 'Субсидии российским компаниям в сфере разработки, производства и послепродажного обслуживания систем и агрегатов самолетов и вертолетов гражданского и военного назначения на компенсацию затрат на уплату купонного дохода по облигационным займам, привл')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1740167720') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1740167720', 'Субсидии российским предприятиям отрасли авиационного агрегатостроения на компенсацию части затрат на реализацию проектов по выходу на мировой рынок в качестве поставщиков компонентов и агрегатов 2 - 4 уровней')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1740167730') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1740167730', 'Субсидии российским компаниям в сфере создания и производства авиационного бортового электронного оборудования на компенсацию затрат на уплату купонного дохода по облигационным займам, привлекаемым с предоставлением государственных гарантий Российско')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1740167740') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1740167740', 'Субсидии российским компаниям отрасли авиационного приборостроения на компенсацию части затрат на реализацию проектов выхода предприятий отрасли на мировой рынок в качестве поставщиков компонентов 2 - 4 уровней')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1740200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1740200000', 'Основное мероприятие "Выполнение научно-исследовательских и опытно-конструкторских работ в области авиационных агрегатов и приборов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1770000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1770000000', 'Подпрограмма "Авиационная наука и технологии"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1770100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1770100000', 'Основное мероприятие "Государственная поддержка российских научных организаций, осуществляющих исследования в области развития авиации и авиационной деятельности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1770200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1770200000', 'Основное мероприятие "Выполнение научно-исследовательских работ в целях развития науки и технологий в авиастроении и технологической и инженерной инфраструктуры, в том числе на базе инновационных территориальных кластеров "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1780000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1780000000', 'Подпрограмма "Комплексное развитие отрасли"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1780100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1780100000', 'Основное мероприятие "Научно-аналитическое обеспечение реализации государственной программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1780200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1780200000', 'Основное мероприятие "Государственная поддержка авиационной промышленности"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1780264750') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1780264750', 'Субсидии российским производителям самолетов, вертолетов и авиационных двигателей на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государственной корпорации "Банк развития и внешнеэкономи')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1800000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1800000000', 'Государственная программа Российской Федерации "Развитие судостроения и техники для освоения шельфовых месторождений на 2013 - 2030 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1810000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1810000000', 'Подпрограмма "Развитие судостроительной науки"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1810100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1810100000', 'Основное мероприятие "Формирование  научно-технического задела в обеспечение опережающего развития морской и речной техники, а также техники для освоения шельфовых месторождений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1810168440') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1810168440', 'Субсидии российским организациям на компенсацию части затрат на проведение научно-исследовательских и опытно-конструкторских работ в целях формирования опережающего научно-технического задела')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1810200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1810200000', 'Основное мероприятие "Развитие научно-исследовательских организаций для решения основополагающих проблем развития отечественного судостроения и разработки критических технологий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1810300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1810300000', 'Основное мероприятие "Комплекс мероприятий по техническому перевооружению уникальных исследовательских, испытательных комплексов и стендов, развитию полигонной базы судостроительной отрасли"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1810368520') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1810368520', 'Субсидии российским организациям на компенсацию части затрат по кредитам, полученным в 2016 году на проведение технологического перевооружения, а также создание и реконструкцию полигонной базы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1810400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1810400000', 'Основное мероприятие "Развитие в государственном научном центре и центрах компетенции систем отраслевого и междисциплинарного образования в области судостроительной науки"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1810468510') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1810468510', 'Субсидии российским организациям судостроительной отрасли на компенсацию части затрат, понесенных в 2016 году на реализацию мероприятий отраслевого и междисциплинарного образования')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1810500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1810500000', 'Основное мероприятие "Комплекс мероприятий по трансферу технологий в смежные отрасли промышленности и сегменты народного хозяйства, а также на мировой рынок"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1820000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1820000000', 'Подпрограмма "Развитие технологического потенциала гражданского судостроения и техники для освоения шельфовых месторождений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1820100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1820100000', 'Основное мероприятие "Разработка новых технологий и инновационных, конкурентоспособных на рынке проектов гражданской морской и речной техники и техники для освоения шельфовых месторождений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1820200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1820200000', 'Основное мероприятие "Создание пилотных экспериментальных (демонстрационных) образцов высокотехнологичных судов, предназначенных для массовой постройки"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1820300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1820300000', 'Основное мероприятие "Закупка передовых зарубежных технологий и лицензий на строительство объектов и организацию в России производства современного технологического оборудования и другой продукции"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1830000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1830000000', 'Подпрограмма "Развитие производственных мощностей гражданского судостроения и материально-технической базы отрасли"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1830100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1830100000', 'Основное мероприятие "Реализация приоритетных проектов развития производственных мощностей гражданского судостроения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1830164130') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1830164130', 'Взнос Российской Федерации в уставный капитал открытого акционерного общества "Объединенная судостроительная корпорация", г. Санкт-Петербург, на цели возмещения процентов по кредитам, привлеченным открытым акционерным обществом "Дальневосточный центр')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1830200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1830200000', 'Основное мероприятие "Развитие и оптимизация производственных мощностей гражданского судостроения, в том числе поддержка реализации кластерной политики в субъектах"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1840000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1840000000', 'Подпрограмма "Государственная поддержка"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1840100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1840100000', 'Основное мероприятие "Предоставление государственной поддержки российским судостроительным предприятиям"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1840200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1840200000', 'Основное мероприятие "Предоставление государственной поддержки российским транспортным компаниям, пароходствам, организациям рыбохозяйственного комплекса в целях приобретения гражданских судов и (или) утилизации отдельных групп судов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1840264720') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1840264720', 'Субсидии российским транспортным компаниям и пароходствам на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государственной корпорации "Банк развития и внешнеэкономической деятельности (Вне')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1840264730') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1840264730', 'Субсидии российским транспортным компаниям и пароходствам, а также организациям рыбохозяйственного комплекса на возмещение части затрат на уплату лизинговых платежей по договорам лизинга, заключенным в 2008 - 2014 годах с российскими лизинговыми комп')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1840265650') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1840265650', 'Субсидии российским организациям на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государственной корпорации "Банк развития и внешнеэкономической деятельности (Внешэкономбанк)" в 2016 - 20')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1840300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1840300000', 'Основное мероприятие "Государственная поддержка российским лизинговым компаниям на закупку гражданских судов с последующей их передачей российским транспортным компаниям и пароходствам по договорам лизинга"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1840368360') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1840368360', 'Субсидии российским лизинговым компаниям на компенсацию части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях в 2014 - 2016 годах, на закупку гражданских судов с последующей их передачей российским транспортным')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1850000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1850000000', 'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Развитие судостроения и техники для освоения шельфовых месторождений на 2013 - 2030 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1850100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1850100000', 'Основное мероприятие "Системно-аналитическое и экспертное сопровождение реализации государственной программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1850168530') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1850168530', 'Субсидии российским организациям судостроительной отрасли на компенсацию части затрат, понесенных в 2016 году на экспертное и аналитическое сопровождение инвестиционных проектов создания новых и модернизации действующих производств в целях создания о')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1850200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1850200000', 'Основное мероприятие "Координация и сопровождение научно-исследовательских и опытно-конструкторских работ, включая осуществление мероприятий по правовой охране и правовой защите результатов научно-технической деятельности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1870000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1870000000', 'Федеральная целевая программа "Развитие гражданской морской техники" на 2009 - 2016 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1870062790') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1870062790', 'Взнос в уставный капитал открытого акционерного общества "Концерн "Моринформсистема-Агат", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1870062810') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1870062810', 'Взнос в уставный капитал федерального научно-производственного центра Открытое акционерное общество "Научно-производственное объединение "Марс", г. Ульяновск')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1870063710') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1870063710', 'Взнос в уставный капитал открытого акционерного общества "Зеленодольское проектно-конструкторское бюро", г. Зеленодольск, Республика Татарстан')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1870063770') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1870063770', 'Взнос в уставный капитал открытого акционерного общества "Северное проектно-конструкторское бюро", г. Санкт-Петербург')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1900000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1900000000', 'Государственная программа Российской Федерации "Развитие электронной и радиоэлектронной промышленности на 2013 - 2025 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920000000', 'Федеральная целевая программа "Развитие электронной компонентной базы и радиоэлектроники" на 2008 - 2015 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062640') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062640', 'Взнос в уставный капитал открытого акционерного общества "Уфимское агрегатное производственное объединение", г. Уфа, Республика Башкортостан')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062680') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062680', 'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Исток" имени А.И. Шокина", г. Фрязино, Московская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062710') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062710', 'Взнос в уставный капитал открытого акционерного общества "Концерн "Созвездие", г. Воронеж')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062720') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062720', 'Взнос в уставный капитал открытого акционерного общества "Научно-производственный центр "Полюс", г. Томск')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062730') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062730', 'Взнос в уставный капитал открытого акционерного общества "Тамбовский завод "Революционный труд", г. Тамбов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062740') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062740', 'Взнос в уставный капитал открытого акционерного общества "Концерн радиостроения "Вега", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062750') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062750', 'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Лианозовский электромеханический завод", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062760') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062760', 'Взнос в уставный капитал открытого акционерного общества "Марийский машиностроительный завод", г. Йошкар-Ола, Республика Марий Эл')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062770') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062770', 'Взнос в уставный капитал открытого акционерного общества "Ижевский электромеханический завод "Купол", г. Ижевск, Удмуртская Республика')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062780') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062780', 'Взнос в уставный капитал открытого акционерного общества "Концерн "Гранит-Электрон", г. Санкт-Петербург')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062790') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062790', 'Взнос в уставный капитал открытого акционерного общества "Концерн "Моринформсистема-Агат", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062810') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062810', 'Взнос в уставный капитал федерального научно-производственного центра Открытое акционерное общество "Научно-производственное объединение "Марс", г. Ульяновск')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062830') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062830', 'Взнос в уставный капитал открытого акционерного общества "Инженерно-маркетинговый центр Концерна "Вега", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062840') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062840', 'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Правдинский радиозавод", г. Балахна, Нижегородская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062870') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062870', 'Взнос в уставный капитал открытого акционерного общества "Информационные спутниковые системы" имени академика М.Ф. Решетнёва", г. Железногорск, Красноярский край')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062880') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062880', 'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт полупроводниковых приборов", г. Томск')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062900') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062900', 'Взнос в уставный капитал открытого акционерного общества "Концерн ПВО "Алмаз-Антей", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062910') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062910', 'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт физических измерений", г. Пенза')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062920') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062920', 'Взнос в уставный капитал открытого акционерного общества "Российская корпорация ракетно-космического приборостроения и информационных систем", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062930') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062930', 'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт точных приборов", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062950') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062950', 'Взнос в уставный капитал открытого акционерного общества завод "Красное знамя", г. Рязань')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920062960') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920062960', 'Взнос в уставный капитал открытого акционерного общества "Уральское производственное предприятие "Вектор", г. Екатеринбург')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063020') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063020', 'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Государственный институт прикладной оптики", г. Казань, Республика Татарстан')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063040') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063040', 'Взнос в уставный капитал открытого акционерного общества "Карачевский завод "Электродеталь", г. Карачев, Брянская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063050') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063050', 'Взнос в уставный капитал открытого акционерного общества "Курский завод "Маяк", г. Курск')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063060') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063060', 'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Радиоэлектроника" имени В.И. Шимко", г. Казань, Республика Татарстан')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063070') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063070', 'Взнос в уставный капитал открытого акционерного общества "Казанское приборостроительное конструкторское бюро", г. Казань, Республика Татарстан')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063080') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063080', 'Взнос в уставный капитал открытого акционерного общества "Брянский электромеханический завод", г. Брянск')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063090') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063090', 'Взнос в уставный капитал открытого акционерного общества "Калугаприбор", г. Калуга')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063100') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063100', 'Взнос в уставный капитал открытого акционерного общества "Калужский завод телеграфной аппаратуры", г. Калуга')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063110') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063110', 'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт авиационного оборудования", г. Жуковский, Московская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063120') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063120', 'Взнос в уставный капитал открытого акционерного общества "Концерн "Автоматика", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063130') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063130', 'Взнос в уставный капитал открытого акционерного общества "Ордена Трудового Красного Знамени научно-исследовательский институт автоматической аппаратуры им. академика В.С. Семенихина", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063140') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063140', 'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт телевидения", г. Санкт-Петербург')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063150') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063150', 'Взнос в уставный капитал открытого акционерного общества "Всероссийский научно-исследовательский институт "Градиент", г. Ростов-на-Дону')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063160') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063160', 'Взнос в уставный капитал открытого акционерного общества "Таганрогский научно-исследовательский институт связи", г. Таганрог, Ростовская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063180') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063180', 'Взнос в уставный капитал открытого акционерного общества "Федеральный научно-производственный центр "Нижегородский научно-исследовательский приборостроительный институт "Кварц" имени А.П. Горшкова", г. Нижний Новгород')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063190') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063190', 'Взнос в уставный капитал открытого акционерного общества "Пензенское производственное объединение "Электроприбор", г. Пенза')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063300') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063300', 'Взнос в уставный капитал открытого акционерного общества "Летно-исследовательский институт имени М.М. Громова", г. Жуковский, Московская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063310') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063310', 'Взнос в уставный капитал открытого акционерного общества "Пензенское производственное объединение электронной вычислительной техники", г. Пенза')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063320') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063320', 'Взнос в уставный капитал открытого акционерного общества "Омский научно-исследовательский институт приборостроения", г. Омск')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063330') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063330', 'Взнос в уставный капитал открытого акционерного общества "Научно-производственный центр "Вигстар", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063350') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063350', 'Взнос в уставный капитал открытого акционерного общества "Концерн "Центральный научно-исследовательский институт "Электроприбор", г. Санкт-Петербург')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063360') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063360', 'Взнос в уставный капитал открытого акционерного общества "Российская электроника", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063370') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063370', 'Взнос в уставный капитал открытого акционерного общества "Нижегородское научно-производственное объединение имени М.В. Фрунзе", г. Нижний Новгород')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063410') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063410', 'Взнос в уставный капитал открытого акционерного общества "Ставропольский радиозавод "Сигнал", г. Ставрополь')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063440') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063440', 'Взнос в уставный капитал открытого акционерного общества "Корпорация "Фазотрон - Научно-исследовательский институт радиостроения", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063530') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063530', 'Взнос в уставный капитал открытого акционерного общества "Объединенная ракетно-космическая корпорация", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920063600') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920063600', 'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение автоматики имени академика Н.А. Семихатова", г. Екатеринбург')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920064200') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920064200', 'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Радиосвязь", г. Красноярск')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920064380') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920064380', 'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт "Полюс" им. М.Ф. Стельмаха", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920064460') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920064460', 'Взнос в уставный капитал открытого акционерного общества "НПО "Орион", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1920066330') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1920066330', 'Взнос в уставный капитал открытого акционерного общества "Государственный завод "Пульсар", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1930000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1930000000', 'Подпрограмма "Развитие производства телекоммуникационного оборудования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1930100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1930100000', 'Основное мероприятие "Государственная поддержка создания научно-технического задела"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1930200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1930200000', 'Основное мероприятие "Государственная поддержка создания производственной базы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1940000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1940000000', 'Подпрограмма "Развитие производства вычислительной техники"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1940100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1940100000', 'Основное мероприятие "Государственная поддержка создания научно-технического задела"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1940200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1940200000', 'Основное мероприятие "Государственная поддержка создания производственной базы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1950000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1950000000', 'Подпрограмма "Развитие производства специального технологического оборудования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1950100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1950100000', 'Основное мероприятие "Государственная поддержка создания научно-технического задела"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1950200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1950200000', 'Основное мероприятие "Государственная поддержка создания производственной базы"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1960000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1960000000', 'Подпрограмма "Развитие производства систем интеллектуального управления"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1960100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1960100000', 'Основное мероприятие "Государственная поддержка создания научно-технического задела"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='1960200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('1960200000', 'Основное мероприятие "Государственная поддержка создания производственной базы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2000000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2000000000', 'Государственная программа Российской Федерации "Развитие фармацевтической и медицинской промышленности" на 2013 - 2020 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2010000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2010000000', 'Подпрограмма "Развитие производства лекарственных средств"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2010100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2010100000', 'Основное мероприятие "Организация производства и выпуска инновационных лекарственных препаратов на основе биотехнологий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2010200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2010200000', 'Основное мероприятие "Разработка и выпуск инновационных, импортозамещающих лекарственных препаратов для лечения социально-значимых заболеваний"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2010300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2010300000', 'Основное мероприятие "Организация опытно-промышленного производства субстанций и лекарственных средств, необходимых для выпуска дорогостоящих импортозамещающих препаратов "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2010400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2010400000', 'Основное мероприятие "Реализация иных проектов в области фармацевтической промышленности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2010500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2010500000', 'Основное мероприятие "Совершенствование государственного регулирования в сфере обращения лекарственных средств"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2020000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2020000000', 'Подпрограмма "Развитие производства медицинских изделий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2020100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2020100000', 'Основное мероприятие "Организация производства новых радиофармпрепаратов и медицинских изделий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2020200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2020200000', 'Основное мероприятие "Производство медицинской техники для каскадной фильтрации плазмы и других методов экстракорпоральной гемокоррекции"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2020300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2020300000', 'Основное мероприятие "Реализация иных проектов в области медицинской промышленности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2020400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2020400000', 'Основное мероприятие "Совершенствование государственного регулирования в сфере обращения медицинских изделий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2040000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2040000000', 'Федеральная целевая программа "Развитие фармацевтической и медицинской промышленности Российской Федерации на период до 2020 года и дальнейшую перспективу"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2040063560') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2040063560', 'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Уральский оптико-механический завод" имени Э.С. Яламова", г. Екатеринбург')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2040063570') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2040063570', 'Взнос в уставный капитал открытого акционерного общества "Всероссийский научный центр по безопасности биологически активных веществ", г. Старая Купавна, Московская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2040063580') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2040063580', 'Взнос в уставный капитал открытого акционерного общества "Московское производственное объединение "Металлист", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2100000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2100000000', 'Государственная программа Российской Федерации "Космическая деятельность России на 2013 - 2020 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2110000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2110000000', 'Подпрограмма "Приоритетные инновационные проекты ракетно-космической промышленности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2110100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2110100000', 'Основное мероприятие "Создание систем слежения и мониторинга подвижных объектов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2110200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2110200000', 'Основное мероприятие "Создание интеллектуальных систем мониторинга и контроля состояния технически сложных объектов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2110300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2110300000', 'Основное мероприятие "Создание транспортно-энергетического модуля на основе ядерной энергодвигательной установки мегаваттного класса"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2120000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2120000000', 'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Космическая деятельность России на 2013 - 2020 годы"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2120100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2120100000', 'Основное мероприятие "Выполнение функций аппарата ответственного исполнителя"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2120130270') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2120130270', 'Премии Правительства Российской Федерации имени Ю.А. Гагарина в области космической деятельности')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2120200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2120200000', 'Основное мероприятие "Выполнение функций по обеспечению отбора и подготовки космонавтов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2120300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2120300000', 'Основное мероприятие "Поддержание потенциала космодрома "Байконур""')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2120350110') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2120350110', 'Дотации на содержание объектов инфраструктуры города Байконура, связанных с арендой космодрома Байконур')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2120351570') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2120351570', 'Иные межбюджетные трансферты на развитие и поддержку инфраструктуры города Байконура')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2120400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2120400000', 'Основное мероприятие "Выполнение международных обязательств"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2120500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2120500000', 'Основное мероприятие "Обеспечение страхования рисков и ответственности при запусках и летных испытаниях космических аппаратов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2120564240') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2120564240', 'Страхование рисков и ответственности при запусках и летных испытаниях космических аппаратов гражданского назначения')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2120600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2120600000', 'Основное мероприятие "Обеспечение деятельности по использованию космического пространства в мирных целях"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2120700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2120700000', 'Основное мероприятие "Обеспечение реализации первоочередных мероприятий, связанных с созданием космодрома "Восточный""')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2130000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2130000000', 'Федеральная космическая программа России на 2006 - 2015 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2130062570') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2130062570', 'Взнос в уставный капитал открытого акционерного общества "Конструкторское бюро химавтоматики", г. Воронеж')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2130062590') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2130062590', 'Взнос в уставный капитал открытого акционерного общества "Особое конструкторское бюро Московского энергетического института", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2130062660') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2130062660', 'Взнос в уставный капитал открытого акционерного общества "Научно-производственная корпорация "Космические системы мониторинга, информационно-управляющие и электромеханические комплексы" имени А.Г. Иосифьяна", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2130062870') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2130062870', 'Взнос в уставный капитал открытого акционерного общества "Информационные спутниковые системы" имени академика М.Ф. Решетнёва", г. Железногорск, Красноярский край')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2130062940') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2130062940', 'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение измерительной техники", г. Королев, Московская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2130063520') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2130063520', 'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт командных приборов", г. Санкт-Петербург')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2140000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2140000000', 'Федеральная целевая программа "Поддержание, развитие и использование системы ГЛОНАСС на 2012 - 2020 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2140062630') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2140062630', 'Взнос в уставный капитал открытого акционерного общества "Сибирские приборы и системы", г. Омск')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2140062720') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2140062720', 'Взнос в уставный капитал открытого акционерного общества "Научно-производственный центр "Полюс", г. Томск')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2140062870') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2140062870', 'Взнос в уставный капитал открытого акционерного общества "Информационные спутниковые системы" имени академика М.Ф. Решетнёва", г. Железногорск, Красноярский край')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2140062900') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2140062900', 'Взнос в уставный капитал открытого акционерного общества "Концерн ПВО "Алмаз-Антей", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2140062920') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2140062920', 'Взнос в уставный капитал открытого акционерного общества "Российская корпорация ракетно-космического приборостроения и информационных систем", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2140063170') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2140063170', 'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Салют", г. Нижний Новгород')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2140063470') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2140063470', 'Взнос в уставный капитал открытого акционерного общества "Завод "Навигатор", г. Санкт-Петербург')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2140063510') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2140063510', 'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Геофизика-Космос", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2140063530') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2140063530', 'Взнос в уставный капитал открытого акционерного общества "Объединенная ракетно-космическая корпорация", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2140064380') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2140064380', 'Взнос в уставный капитал открытого акционерного общества "Научно-исследовательский институт "Полюс" им. М.Ф. Стельмаха", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2140067670') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2140067670', 'Взнос в уставный капитал открытого акционерного общества "Испытательный технический центр - НПО ПМ", г. Железногорск, Красноярский край')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2140067790') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2140067790', 'Взнос в уставный капитал открытого акционерного общества "Научно-производственное предприятие "Квант", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2140067800') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2140067800', 'Взнос в уставный капитал открытого акционерного общества "106 экспериментальный оптико-механический завод", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2150000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2150000000', 'Федеральная целевая программа "Развитие российских космодромов на 2006 - 2015 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2150020810') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2150020810', 'Реализация мероприятий подпрограммы "Создание обеспечивающей инфраструктуры космодрома "Восточный" федеральной целевой программы "Развитие российских космодромов на 2006 - 2015 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2160000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2160000000', 'Федеральная целевая программа "Развитие космодромов на период 2016 - 2025 годов в обеспечение космической деятельности Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2170000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2170000000', 'Федеральная космическая программа России на 2016 - 2025 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2200000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2200000000', 'Государственная программа Российской Федерации "Развитие атомного энергопромышленного комплекса"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2210000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2210000000', 'Подпрограмма "Расширение мощностей электрогенерации атомных электростанций"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2210100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2210100000', 'Основное мероприятие "Завершение строительства энергоблоков высокой степени готовности и строительство новых энергоблоков"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2210165080') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2210165080', 'Имущественный взнос в Государственную корпорацию по атомной энергии "Росатом" на развитие атомного энергопромышленного комплекса')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2210200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2210200000', 'Основное мероприятие "Строительство атомных станций малой мощности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2210300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2210300000', 'Основное мероприятие "Модернизация действующих атомных электростанций"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2210400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2210400000', 'Основное мероприятие "Обеспечение безопасной и устойчивой работы действующих энергоблоков атомных электростанций"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2220000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2220000000', 'Подпрограмма "Обеспечение безопасного обращения с радиоактивными отходами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2220100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2220100000', 'Основное мероприятие "Обеспечение производственной программы по глубинным пунктам захоронения жидких радиоактивных отходов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2220200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2220200000', 'Основное мероприятие "Обеспечение функционирования штатных аварийно-спасательных формирований в атомной отрасли"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2220300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2220300000', 'Основное мероприятие "Обращение с радиоактивными отходами, включая радиоактивные отходы, образующиеся в бюджетных организациях"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2220365070') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2220365070', 'Субсидии на возмещение затрат на обращение с радиоактивными отходами')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2230000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2230000000', 'Подпрограмма "Обеспечение инновационного развития гражданского сектора атомной отрасли и расширение сферы использования ядерных технологий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2230100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2230100000', 'Основное мероприятие "Участие в проекте создания Международного термоядерного экспериментального реактора ИТЭР"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2230127820') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2230127820', 'Обеспечение реализации проекта Международного термоядерного экспериментального реактора (ИТЭР)')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2230200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2230200000', 'Основное мероприятие "Участие в проекте создания Центра по исследованию ионов и антипротонов в Европе"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2230227830') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2230227830', 'Международный проект по сооружению Центра по исследованию ионов и антипротонов в Европе (ФАИР)')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2230300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2230300000', 'Основное мероприятие "Научно-исследовательские и опытно-конструкторские работы в области развития атомной отрасли"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2230400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2230400000', 'Основное мероприятие "Создание инновационного технопарка в интересах развития гражданского сектора атомной отрасли "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2230500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2230500000', 'Основное мероприятие "Проект "Создание типового оптимизированного и информатизированного энергоблока технологии ВВЭР (ВВЭР-ТОИ)" "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2230600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2230600000', 'Основное мероприятие "Выполнение обязательств по внесению взносов в международные организации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2230700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2230700000', 'Основное мероприятие "Выполнение международных обязательств по поставке низкообогащенного урана, переработанного из высокообогащенного урана"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2240000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2240000000', 'Подпрограмма "Обеспечение исполнения Государственной корпорацией по атомной энергии "Росатом" государственных заданий и функций в области государственного управления использованием атомной энергии"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2240100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2240100000', 'Основное мероприятие "Выполнение Государственной корпорацией по атомной энергии "Росатом" возложенных на нее государственных полномочий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2240165140') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2240165140', 'Субсидии Государственной корпорации по атомной энергии "Росатом" на выполнение возложенных на нее государственных полномочий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2240200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2240200000', 'Основное мероприятие "Информационно-аналитическое обеспечение, управление и мониторинг реализации государственной программы "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2240300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2240300000', 'Основное мероприятие "Обеспечение отрасли квалифицированными выпускниками образовательных учреждений высшего образования, обучающихся по специальностям и направлениям подготовки, связанным с атомной отраслью"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2250000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2250000000', 'Подпрограмма "Обеспечение производственных, технологических и социально-экономических процессов устойчивого развития ядерного оружейного комплекса Российской Федерации и стратегического присутствия России в Арктической зоне"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2250100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2250100000', 'Основное мероприятие "Обеспечение Вооруженных сил Российской Федерации продукцией и услугами атомной отрасли "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2250200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2250200000', 'Основное мероприятие "Совершенствование экспериментально-испытательной и производственно-технологической баз в атомной отрасли "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2250300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2250300000', 'Основное мероприятие "Государственная поддержка федеральных ядерных центров и специалистов, занятых в выполнении государственного оборонного заказа"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2250360590') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2250360590', 'Субсидии организациям ядерно-оружейного комплекса')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2250400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2250400000', 'Основное мероприятие "Формирование, восстановление и хранение материальных ценностей государственного запаса специального сырья и делящихся материалов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2250500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2250500000', 'Основное мероприятие "Специальные мероприятия в области национальной обороны"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2250567460') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2250567460', 'Взнос в уставный капитал акционерного общества "Государственный научный центр Российской Федерации - Физико-энергетический институт имени А.И. Лейпунского", г. Обнинск, Калужская область, в целях технического перевооружения производственной базы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2250568020') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2250568020', 'Взнос в уставный капитал открытого акционерного общества "Машиностроительный завод", г. Электросталь, Московская область, в целях технического перевооружения производственной базы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2250568030') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2250568030', 'Взнос в уставный капитал открытого акционерного общества "Ордена Ленина Научно-исследовательский и конструкторский институт энерготехники имени Н.А. Доллежаля", г. Москва, в целях технического перевооружения производственной базы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2250568050') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2250568050', 'Взнос в уставный капитал открытого акционерного общества "Институт реакторных материалов", г. Заречный, Свердловская область, в целях технического перевооружения производственной базы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2250600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2250600000', 'Основное мероприятие "Мероприятия по промышленной  утилизации вооружения и военной техники ядерного комплекса, не входящие в Федеральную целевую программу "Промышленная утилизация вооружения и военной техники ядерного комплекса на 2011 - 2015 годы и')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2250700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2250700000', 'Основное мероприятие "Содержание объектов федерального государственного унитарного предприятия атомного флота, связанных с использованием атомной энергии"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2250764590') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2250764590', 'Субсидии федеральному государственному унитарному предприятию "Атомфлот" на возмещение расходов по содержанию объектов, связанных с использованием атомной энергии')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2250800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2250800000', 'Основное мероприятие "Строительство атомных ледоколов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2250841090') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2250841090', 'Строительство атомных ледоколов гражданского назначения')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2260000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2260000000', 'Федеральная целевая программа "Обеспечение ядерной и радиационной безопасности на 2008 год и на период до 2015 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2260063670') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2260063670', 'Взнос в уставный капитал открытого акционерного общества "Производственное объединение "Северное машиностроительное предприятие", г. Северодвинск, Архангельская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2260063690') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2260063690', 'Взнос в уставный капитал открытого акционерного общества "Центр судоремонта "Звездочка", г. Северодвинск, Архангельская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2260063800') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2260063800', 'Взнос в уставный капитал открытого акционерного общества "Сибирский химический комбинат", г. Северск, Томская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2260063810') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2260063810', 'Взнос в уставный капитал открытого акционерного общества "Государственный научный центр - Научно-исследовательский институт атомных реакторов", г. Димитровград-10, Ульяновская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2260063820') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2260063820', 'Взнос в уставный капитал открытого акционерного общества "Атомспецтранс", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2260063870') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2260063870', 'Взнос в уставный капитал открытого акционерного общества "Дальневосточный завод "Звезда", г. Большой Камень, Приморский край')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2260063900') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2260063900', 'Взнос в уставный капитал открытого акционерного общества "Чепецкий механический завод", г. Глазов, Удмуртская Республика')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2260067280') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2260067280', 'Взнос в уставный капитал открытого акционерного общества "Радиевый институт имени В.Г. Хлопина", г. Санкт-Петербург')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2270000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2270000000', 'Федеральная целевая программа "Ядерные энерготехнологии нового поколения на период 2010 - 2015 годов и на перспективу до 2020 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2270063800') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2270063800', 'Взнос в уставный капитал открытого акционерного общества "Сибирский химический комбинат", г. Северск, Томская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2270063810') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2270063810', 'Взнос в уставный капитал открытого акционерного общества "Государственный научный центр - Научно-исследовательский институт атомных реакторов", г. Димитровград-10, Ульяновская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2270066690') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2270066690', 'Взнос в уставный капитал открытого акционерного общества "Ордена Ленина Научно-исследовательский и конструкторский институт энерготехники имени Н.А. Доллежаля", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2270066700') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2270066700', 'Взнос в уставный капитал открытого акционерного общества "Высокотехнологический научно-исследовательский институт неорганических материалов имени академика А.А. Бочвара", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2270066710') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2270066710', 'Взнос в уставный капитал открытого акционерного общества "Красная Звезда", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2270067270') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2270067270', 'Взнос в уставный капитал открытого акционерного общества "НИИЭФА им. Д.В. Ефремова", г. Санкт-Петербург')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2270067440') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2270067440', 'Взнос в уставный капитал акционерного общества "Государственный научный центр Российской Федерации - Физико-энергетический институт имени А.И. Лейпунского", г. Обнинск, Калужская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2270067450') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2270067450', 'Взнос в уставный капитал акционерного общества "Государственный научный центр Российской Федерации Троицкий институт инновационных и термоядерных исследований", г. Москва, г. Троицк')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2280000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2280000000', 'Федеральная целевая программа "Развитие ядерного оружейного комплекса Российской Федерации на 2007 - 2015 годы и на период до 2020 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2280063810') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2280063810', 'Взнос в уставный капитал открытого акционерного общества "Государственный научный центр - Научно-исследовательский институт атомных реакторов", г. Димитровград-10, Ульяновская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2280063840') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2280063840', 'Взнос в уставный капитал открытого акционерного общества "Машиностроительный завод", г. Электросталь, Московская область')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2280065510') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2280065510', 'Взнос в уставный капитал открытого акционерного общества "Опытное Конструкторское Бюро Машиностроения имени И.И. Африкантова", г. Нижний Новгород')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2280066690') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2280066690', 'Взнос в уставный капитал открытого акционерного общества "Ордена Ленина Научно-исследовательский и конструкторский институт энерготехники имени Н.А. Доллежаля", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2280066700') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2280066700', 'Взнос в уставный капитал открытого акционерного общества "Высокотехнологический научно-исследовательский институт неорганических материалов имени академика А.А. Бочвара", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2280066710') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2280066710', 'Взнос в уставный капитал открытого акционерного общества "Красная Звезда", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2280067440') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2280067440', 'Взнос в уставный капитал акционерного общества "Государственный научный центр Российской Федерации - Физико-энергетический институт имени А.И. Лейпунского", г. Обнинск, Калужская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2290000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2290000000', 'Федеральная целевая программа "Промышленная утилизация вооружения и военной техники ядерного комплекса на 2011 - 2015 годы и на период до 2020 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2290100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2290100000', 'Основное мероприятие "Подпрограмма "Промышленная утилизация ядерных боеприпасов на 2011 - 2015 годы и на период до 2020 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2290199999') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2290199999', 'Реализация направлений расходов подпрограммы государственной программы Российской Федерации, федеральной целевой программы в рамках государственной программы Российской Федерации, а также непрограммных направлений расходов федеральных государственных')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2290200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2290200000', 'Основное мероприятие "Подпрограмма "Промышленная утилизация атомных подводных лодок, надводных кораблей с ядерной энергетической установкой, судов атомного технологического обслуживания и реабилитация радиационно-опасных объектов на 2011 - 2015 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2290299999') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2290299999', 'Реализация направлений расходов подпрограммы государственной программы Российской Федерации, федеральной целевой программы в рамках государственной программы Российской Федерации, а также непрограммных направлений расходов федеральных государственных')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='22Б0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('22Б0000000', 'Федеральная целевая программа "Обеспечение ядерной и радиационной безопасности на 2016 - 2020 годы и на период до 2030 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='22Б0063690') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('22Б0063690', 'Взнос в уставный капитал открытого акционерного общества "Центр судоремонта "Звездочка", г. Северодвинск, Архангельская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='22Б0063800') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('22Б0063800', 'Взнос в уставный капитал открытого акционерного общества "Сибирский химический комбинат", г. Северск, Томская область')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='22Б0067230') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('22Б0067230', 'Взнос в уставный капитал публичного акционерного общества "Приаргунское производственное горно-химическое объединение", г. Краснокаменск, Забайкальский край')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2300000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2300000000', 'Государственная программа Российской Федерации "Информационное общество (2011 - 2020 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2310000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2310000000', 'Подпрограмма "Информационно-телекоммуникационная инфраструктура информационного общества и услуги, оказываемые на ее основе"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2310100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2310100000', 'Основное мероприятие "Обеспечение доступности услуг электросвязи на территории Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2310120440') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2310120440', 'Финансовое обеспечение оказания универсальных услуг связи')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2310164530') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2310164530', 'Субсидии на возмещение операторам связи убытков, причиняемых оказанием универсальных услуг связи, а также на возмещение затрат оператору базы данных перенесенных абонентских номеров')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2310200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2310200000', 'Основное мероприятие "Развитие федеральной почтовой связи"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2310300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2310300000', 'Основное мероприятие "Расширение использования радиочастотного спектра в гражданских целях"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2310320260') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2310320260', 'Конверсия радиочастотного спектра')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2310400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2310400000', 'Основное мероприятие "Управление развитием информационно-коммуникационной инфраструктуры информационного общества"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2310500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2310500000', 'Основное мероприятие "Развитие связи и информационных технологий в целях осуществления подготовки и проведения в Российской Федерации спортивных мероприятий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320000000', 'Подпрограмма "Информационная среда"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320100000', 'Основное мероприятие "Строительство, восстановление, реконструкция, переоборудование объектов телерадиовещания"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320164960') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320164960', 'Субсидии федеральному государственному унитарному предприятию "Телевизионный технический центр "Останкино" на проведение капитального ремонта инженерного оборудования и техническое перевооружение производственно-технологического оборудования')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320200000', 'Основное мероприятие "Поддержка печатных средств массовой информации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320230510') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320230510', 'Премии Правительства Российской Федерации в области печатных средств массовой информации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320264910') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320264910', 'Государственная поддержка в сфере средств массовой информации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320300000', 'Основное мероприятие "Поддержка создания и распространения телерадиопрограмм и электронных средств массовых информаций"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320362420') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320362420', 'Субсидии автономной некоммерческой организации "Общественное телевидение России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320362520') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320362520', 'Субсидии автономной некоммерческой организации "Спортивное вещание"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320364950') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320364950', 'Субсидии федеральному государственному унитарному предприятию "Всероссийская государственная телевизионная и радиовещательная компания" на финансовое обеспечение деятельности, а также на покрытие расходов, связанных с производством программного проду')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320364970') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320364970', 'Субсидии открытому акционерному обществу "Первый канал", открытому акционерному обществу "Телекомпания НТВ", открытому акционерному обществу "Телерадиокомпания "Петербург", закрытому акционерному обществу "Карусель" и открытому акционерному обществу')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320367170') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320367170', 'Субсидии федеральному государственному унитарному предприятию "Всероссийская государственная телевизионная и радиовещательная компания" на финансовое обеспечение мероприятий по переходу в 2013 - 2015 годах на производство программ в цифровом формате')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320400000', 'Основное мероприятие "Поддержка социально значимых проектов в медиасреде"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320464940') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320464940', 'Субсидии организациям, осуществляющим производство, распространение и тиражирование социально значимых программ в области электронных средств массовой информации, на создание и поддержание в сети "Интернет" сайтов, имеющих социальное или образователь')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320465000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320465000', 'Субсидии издательствам и издающим организациям на реализацию социально значимых проектов, государственную поддержку непериодических изданий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320500000', 'Основное мероприятие "Участие России в международном информационном обмене"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320562410') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320562410', 'Субсидии автономной некоммерческой организации "ТВ-Новости" на создание средств массовой информации: телеканалов, радиоканалов, сетевых изданий и их распространение в мировом информационном пространстве, покрытие расходов, связанных с производством и')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320564170') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320564170', 'Субсидии федеральному государственному унитарному предприятию "Международное информационное агентство "Россия сегодня"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320564930') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320564930', 'Субсидии федеральному государственному унитарному предприятию "Информационное телеграфное агентство России (ИТАР - ТАСС)" на финансовое обеспечение расходов по организации мероприятий по освещению государственной политики и общественной жизни в Росси')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320600000', 'Основное мероприятие "Стимулирование профессиональной деятельности в области средств массовой информации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320660750') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320660750', 'Премии Правительства Российской Федерации в области средств массовой информации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320700000', 'Основное мероприятие "Ведение федеральных информационных фондов, баз и банков данных"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320764540') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320764540', 'Субсидии организациям, осуществляющим ведение федеральных информационных фондов, баз и банков данных')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2320800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2320800000', 'Основное мероприятие "Управление развитием информационной среды"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2330000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2330000000', 'Подпрограмма "Безопасность в информационном обществе"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2330100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2330100000', 'Основное мероприятие "Контроль и надзор в сфере связи, информационных технологий и массовых коммуникаций"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2330200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2330200000', 'Основное мероприятие "Организация деятельности радиочастотной службы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2330264560') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2330264560', 'Субсидия федеральным государственным унитарным предприятиям - радиочастотным центрам федеральных округов на финансовое обеспечение затрат, связанных с выполнением возложенных на них функций')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2330265660') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2330265660', 'Субсидия федеральному государственному унитарному предприятию "Главный радиочастотный центр" на возмещение затрат, связанных с выполнением работ по образованию позывных сигналов для опознавания радиоэлектронных средств гражданского назначения и прове')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2330300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2330300000', 'Основное мероприятие "Развитие сети станций радиоконтроля"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2330400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2330400000', 'Основное мероприятие "Предупреждение информационно-технологических угроз национальным интересам России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2330470020') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2330470020', 'Обеспечение безопасности в информационном обществе')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2330500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2330500000', 'Основное мероприятие "Информационно-техническое сопровождение, модернизация, развитие программно-технических средств подсистемы мониторинга средств массовой информации в специальных целях"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2330570020') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2330570020', 'Обеспечение безопасности в информационном обществе')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2330600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2330600000', 'Основное мероприятие "Противодействие терроризму, экстремизму, насилию"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2330670020') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2330670020', 'Обеспечение безопасности в информационном обществе')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340000000', 'Подпрограмма "Информационное государство"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340100000', 'Основное мероприятие "Управление развитием информационного общества"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340200000', 'Основное мероприятие "Развитие и эксплуатация электронного правительства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340270010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340270010', 'Реализация мероприятий в сфере информационно-коммуникационных технологий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340300000', 'Основное мероприятие "Создание и внедрение современных информационных технологий в сфере государственного управления"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340370010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340370010', 'Реализация мероприятий в сфере информационно-коммуникационных технологий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340400000', 'Основное мероприятие "Создание и развитие официальных сайтов высших должностных лиц и органов управления Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340470010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340470010', 'Реализация мероприятий в сфере информационно-коммуникационных технологий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340500000', 'Основное мероприятие "Координация мероприятий по использованию информационно-коммуникационных технологий в деятельности государственных органов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340570010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340570010', 'Реализация мероприятий в сфере информационно-коммуникационных технологий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340600000', 'Основное мероприятие "Поддержка региональных проектов в сфере информационных технологий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340650280') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340650280', 'Субсидии на поддержку региональных проектов в сфере информационных технологий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340670010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340670010', 'Реализация мероприятий в сфере информационно-коммуникационных технологий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340700000', 'Основное мероприятие "Информатизация в сфере экономической политики, оказания государственных услуг и осуществления государственных функций"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340770010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340770010', 'Реализация мероприятий в сфере информационно-коммуникационных технологий')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340800000', 'Основное мероприятие "Информационно-технологическое и информационно-аналитическое обеспечение деятельности отдельных органов государственной власти"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340870010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340870010', 'Реализация мероприятий в сфере информационно-коммуникационных технологий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340900000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340900000', 'Основное мероприятие "Развитие сервисов на основе информационных технологий в области медицины, здравоохранения, социального обеспечения, образования, науки и культуры"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2340970010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2340970010', 'Реализация мероприятий в сфере информационно-коммуникационных технологий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2341000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2341000000', 'Основное мероприятие "Развитие и эксплуатация государственной системы изготовления, оформления и контроля паспортно-визовых документов нового поколения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2350000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2350000000', 'Федеральная целевая программа "Развитие телерадиовещания в Российской Федерации на 2009 - 2015 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2400000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2400000000', 'Государственная программа Российской Федерации "Развитие транспортной системы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410000000', 'Подпрограмма "Магистральный железнодорожный транспорт"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410100000', 'Основное мероприятие "Компенсация потерь в доходах транспортных предприятий, возникающих в результате государственного регулирования тарифов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410154750') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410154750', 'Иные межбюджетные трансферты, бюджету Калининградской области на компенсацию части затрат российских юридических лиц на перевозку железнодорожным транспортом общего пользования готовых товаров, произведенных на территории Калининградской области, на')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410160690') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410160690', 'Субсидии организациям железнодорожного транспорта на компенсацию потерь в доходах, возникающих в результате государственного регулирования тарифов на услуги по перевозке пассажиров в пригородном железнодорожном сообщении')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410160790') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410160790', 'Субсидии организациям железнодорожного транспорта на компенсацию потерь в доходах, возникающих в результате государственного регулирования тарифов на перевозку пассажиров в поездах дальнего следования в плацкартных и общих вагонах')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410160800') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410160800', 'Субсидии организациям железнодорожного транспорта на компенсацию потерь в доходах, возникающих в результате установления льгот по тарифам на перевозку обучающихся и воспитанников общеобразовательных учреждений старше 10 лет железнодорожным транспорто')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410160810') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410160810', 'Субсидии открытому акционерному обществу "Российские железные дороги" на компенсацию потерь в доходах, возникающих в результате государственного регулирования тарифов на услуги по использованию инфраструктуры железнодорожного транспорта общего пользо')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410164470') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410164470', 'Субсидии организациям железнодорожного транспорта на компенсацию потерь в доходах от выравнивания тарифов при перевозке пассажиров в сообщении из (в) Калининградской области в (из) другие регионы Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410200000', 'Основное мероприятие "Модернизация транспортной инфраструктуры железнодорожного транспорта"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410240100') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410240100', 'Создание транспортной инфраструктуры для освоения минерально-сырьевых ресурсов юго-востока Забайкальского края')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410240110') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410240110', 'Организация скоростного движения пассажирских поездов на участке Санкт-Петербург - Бусловская Октябрьской железной дороги')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410240120') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410240120', 'Создание промышленного комплекса г. Новомосковск Тульской области')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410251540') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410251540', 'Иные межбюджетные трансферты на реализацию мероприятий по подготовке и проведению чемпионата мира по футболу в 2018 году в Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410264000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410264000', 'Взнос в уставный капитал открытого акционерного общества "Российские железные дороги"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410300000', 'Основное мероприятие "Обеспечение реализации подпрограммы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410351230') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410351230', 'Иные межбюджетные трансферты бюджету Республики Крым на финансовое обеспечение деятельности государственного предприятия "Крымская железная дорога"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2410360760') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2410360760', 'Субсидии открытому акционерному обществу "Российские железные дороги" на компенсацию расходов по содержанию автомобильной дороги Адлер - горноклиматический курорт "Альпика-Сервис"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2420000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2420000000', 'Подпрограмма "Дорожное хозяйство"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2420100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2420100000', 'Основное мероприятие "Капитальный ремонт, ремонт и содержание автомобильных дорог общего пользования федерального значения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2420120580') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2420120580', 'Содержание автомобильных дорог общего пользования федерального значения')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2420200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2420200000', 'Основное мероприятие "Обновление парка автоколонн войскового типа"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2420264500') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2420264500', 'Субсидии организациям транспорта, осуществляющим приобретение автотехники для пополнения подвижного состава автоколонн войскового типа')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2420300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2420300000', 'Основное мероприятие "Обеспечение реализации подпрограммы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2420400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2420400000', 'Основное мероприятие "Содействие развитию автомобильных дорог регионального, межмуниципального и местного значения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2420453900') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2420453900', 'Иные межбюджетные трансферты на финансовое обеспечение дорожной деятельности')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2420454200') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2420454200', 'Иные межбюджетные трансферты на реализацию мероприятий региональных программ в сфере дорожного хозяйства по решениям Правительства Российской Федерации в рамках подпрограммы "Дорожное хозяйство" государственной программы Российской Федерации "Развити')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2420500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2420500000', 'Основное мероприятие "Развитие скоростных автомобильных дорог на условиях государственно-частного партнерства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2420565130') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2420565130', 'Имущественный взнос Российской Федерации в Государственную компанию "Российские автомобильные дороги"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2420565150') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2420565150', 'Субсидии Государственной компании "Российские автомобильные дороги" на осуществление деятельности по доверительному управлению автомобильными дорогами Государственной компании')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430000000', 'Подпрограмма "Гражданская авиация и аэронавигационное обслуживание"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430100000', 'Основное мероприятие "Содействие повышению доступности воздушных перевозок населения, в том числе в части развития региональных и внутрирегиональных перевозок"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430160780') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430160780', 'Субсидии организациям воздушного транспорта в целях обеспечения доступности внутренних региональных перевозок пассажиров воздушным транспортом в Приволжском федеральном округе')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430164160') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430164160', 'Субсидии организациям воздушного транспорта на осуществление региональных воздушных перевозок пассажиров на территории Российской Федерации и формирование региональной маршрутной сети')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430164340') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430164340', 'Субсидии на возмещение российским авиакомпаниям части затрат на уплату лизинговых платежей за воздушные суда отечественного производства, получаемые российскими авиакомпаниями от российских лизинговых компаний по договорам лизинга в 2002 - 2010 годах')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430164350') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430164350', 'Субсидии на возмещение российским авиакомпаниям части затрат на уплату лизинговых платежей за воздушные суда, получаемые российскими авиакомпаниями от лизинговых компаний по договорам лизинга для осуществления внутренних региональных и местных воздуш')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430164360') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430164360', 'Субсидии на обеспечение доступности воздушных перевозок пассажиров с Дальнего Востока в европейскую часть страны и в обратном направлении')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430164400') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430164400', 'Субсидии на обеспечение доступности воздушных перевозок пассажиров из г. Калининграда в европейскую часть страны и в обратном направлении')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430164410') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430164410', 'Субсидии закрытому акционерному обществу "Терминал Владивосток" на возмещение части затрат на уплату процентов по кредитам, полученным в государственной корпорации "Банк развития и внешнеэкономической деятельности (Внешэкономбанк)" в 2010 году на стр')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430164550') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430164550', 'Субсидии организациям воздушного транспорта в целях обеспечения доступности воздушных перевозок пассажиров в г. Симферополь и в обратном направлении')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430167080') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430167080', 'Субсидии авиационным перевозчикам для возмещения недополученных ими доходов в связи с обеспечением перевозки пассажиров, заключивших договор воздушной перевозки с авиационным перевозчиком, в отношении которого принято решение о приостановлении действ')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430200000', 'Основное мероприятие "Государственная поддержка авиапредприятий, расположенных в районах Крайнего Севера и приравненных к ним местностях"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430264320') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430264320', 'Субсидии аэропортам, расположенным в районах Крайнего Севера и приравненных к ним местностях')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430264390') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430264390', 'Субсидии федеральным казенным предприятиям, расположенным в районах Крайнего Севера и приравненных к ним местностях')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430300000', 'Основное мероприятие "Обеспечение охвата территории Российской Федерации деятельностью специализированных поисково- и аварийно-спасательных служб на воздушном транспорте"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430364310') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430364310', 'Субсидии авиационным предприятиям и организациям экспериментальной авиации на возмещение затрат при осуществлении ими поисково-спасательных операций (работ) и участии в их обеспечении')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430400000', 'Основное мероприятие "Возмещение расходов за аэронавигационное обслуживание и услуги по аэропортовому и наземному обеспечению полетов воздушных судов пользователей воздушного пространства, освобожденных в соответствии с законодательством Российской Ф')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430464300') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430464300', 'Субсидии на возмещение расходов за аэронавигационное обслуживание полетов воздушных судов пользователей воздушного пространства, освобожденных в соответствии с законодательством Российской Федерации от платы за аэронавигационное обслуживание')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430464370') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430464370', 'Субсидии на возмещение организациям недополученных доходов от предоставления услуг по аэропортовому и наземному обеспечению полетов воздушных судов пользователей воздушного пространства, освобожденных в соответствии с законодательством Российской Фед')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430500000', 'Основное мероприятие "Обеспечение реализации подпрограммы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2430564330') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2430564330', 'Субсидии на функционирование координационного центра Россия - НАТО')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2440000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2440000000', 'Подпрограмма "Морской и речной транспорт"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2440100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2440100000', 'Основное мероприятие "Поисковое и аварийно-спасательное обеспечение судоходства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2440164420') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2440164420', 'Субсидии на выполнение мероприятий по несению аварийно-спасательной готовности на море')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2440200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2440200000', 'Основное мероприятие "Навигационно-гидрографическое обеспечение судоходства на трассах Северного морского пути"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2440264450') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2440264450', 'Субсидии на навигационно-гидрографическое обеспечение судоходства на трассах Северного морского пути')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2440300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2440300000', 'Основное мероприятие "Обеспечение эксплуатации внутренних водных путей и гидротехнических сооружений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2440364430') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2440364430', 'Субсидии на обеспечение безопасности судоходства на канале имени Москвы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2440364440') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2440364440', 'Субсидии на обеспечение мероприятий по обводнению')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2440400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2440400000', 'Основное мероприятие "Обеспечение реализации подпрограммы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2450000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2450000000', 'Подпрограмма "Надзор в сфере транспорта"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2450100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2450100000', 'Основное мероприятие "Обеспечение функционирования и развития системы государственного контроля и надзора в сфере транспорта"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2450200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2450200000', 'Основное мероприятие "Развитие и обеспечение функционирования единой информационно-аналитической системы (ЕИАС)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2480000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2480000000', 'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Развитие транспортной системы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2480100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2480100000', 'Основное мероприятие "Управление реализацией Программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2480160610') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2480160610', 'Субсидии автономной некоммерческой организации "Единая транспортная дирекция" на организацию перевозок пассажиров в прямом смешанном сообщении на территорию Крымского федерального округа и в обратном направлении')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2480162210') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2480162210', 'Субсидии автономной некоммерческой организации "Дирекция Московского транспортного узла"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2480162230') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2480162230', 'Субсидии автономной некоммерческой организации "Дирекция по развитию транспортной системы Санкт-Петербурга и Ленинградской области"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2480162240') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2480162240', 'Субсидии автономной некоммерческой организации "Единая транспортная дирекция"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2480162310') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2480162310', 'Субсидии автономной некоммерческой организации "Транспортная дирекция чемпионата мира по футболу в 2018 году в Российской Федерации", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2480165670') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2480165670', 'Возмещение организациям транспорта потерь в доходах в связи с обеспечением бесплатного проезда участников и инвалидов Великой Отечественной войны, а также сопровождающих их лиц, в период празднования 70-й годовщины Победы в Великой Отечественной войн')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2480200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2480200000', 'Основное мероприятие "Содействие развитию транспортной инфраструктуры города Москвы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2480254050') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2480254050', 'Иные межбюджетные трансферты на развитие транспортной инфраструктуры города Москвы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2480300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2480300000', 'Основное мероприятие "Комплексная программа обеспечения безопасности населения на транспорте"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0000000', 'Федеральная целевая программа "Развитие транспортной системы России (2010 - 2020 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0100000', 'Основное мероприятие "Подпрограмма "Развитие экспорта транспортных услуг"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0199999') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0199999', 'Реализация направлений расходов подпрограммы государственной программы Российской Федерации, федеральной целевой программы в рамках государственной программы Российской Федерации, а также непрограммных направлений расходов федеральных государственных')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0200000', 'Основное мероприятие "Подпрограмма "Железнодорожный транспорт"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0264180') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0264180', 'Взнос в уставный капитал открытого акционерного общества "Российские железные дороги" в рамках реализации мероприятий подпрограммы "Железнодорожный транспорт" федеральной целевой программы "Развитие транспортной системы России (2010 - 2020 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0299999') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0299999', 'Реализация направлений расходов подпрограммы государственной программы Российской Федерации, федеральной целевой программы в рамках государственной программы Российской Федерации, а также непрограммных направлений расходов федеральных государственных')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0300000', 'Основное мероприятие "Подпрограмма "Автомобильные дороги"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0351150') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0351150', 'Субсидии на реализацию мероприятий подпрограммы "Автомобильные дороги" федеральной целевой программы "Развитие транспортной системы России (2010 - 2020 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0351950') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0351950', 'Субсидии на реализацию мероприятий по подготовке и проведению чемпионата мира по футболу в 2018 году в Российской Федерации по подпрограмме "Автомобильные дороги" федеральной целевой программы "Развитие транспортной системы России (2010 - 2020 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0399999') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0399999', 'Реализация направлений расходов подпрограммы государственной программы Российской Федерации, федеральной целевой программы в рамках государственной программы Российской Федерации, а также непрограммных направлений расходов федеральных государственных')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0400000', 'Основное мероприятие "Подпрограмма "Морской транспорт"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0499999') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0499999', 'Реализация направлений расходов подпрограммы государственной программы Российской Федерации, федеральной целевой программы в рамках государственной программы Российской Федерации, а также непрограммных направлений расходов федеральных государственных')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0500000', 'Основное мероприятие "Подпрограмма "Внутренний водный транспорт"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0599999') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0599999', 'Реализация направлений расходов подпрограммы государственной программы Российской Федерации, федеральной целевой программы в рамках государственной программы Российской Федерации, а также непрограммных направлений расходов федеральных государственных')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0600000', 'Основное мероприятие "Подпрограмма "Гражданская авиация"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0651160') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0651160', 'Субсидии на реализацию мероприятий подпрограммы "Гражданская авиация" федеральной целевой программы "Развитие транспортной системы России (2010 - 2020 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0699999') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0699999', 'Реализация направлений расходов подпрограммы государственной программы Российской Федерации, федеральной целевой программы в рамках государственной программы Российской Федерации, а также непрограммных направлений расходов федеральных государственных')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0700000', 'Основное мероприятие "Подпрограмма "Государственный контроль и надзор в сфере транспорта""')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б0799999') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б0799999', 'Реализация направлений расходов подпрограммы государственной программы Российской Федерации, федеральной целевой программы в рамках государственной программы Российской Федерации, а также непрограммных направлений расходов федеральных государственных')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Б9920640') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Б9920640', 'Реализация мероприятий общепрограммного характера по федеральной целевой программе "Развитие транспортной системы России (2010 - 2020 годы)"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Г0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Г0000000', 'Федеральная целевая программа "Модернизация Единой системы организации воздушного движения Российской Федерации (2009 - 2020 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Д0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Д0000000', 'Подпрограмма "Развитие гражданского использования системы ГЛОНАСС на транспорте"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Д0062550') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Д0062550', 'Взнос в уставный капитал акционерного общества "ГЛОНАСС"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Д0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Д0100000', 'Основное мероприятие "Создание и обеспечение постоянной эксплуатации системы экстренного реагирования при авариях "ЭРА-ГЛОНАСС"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Д0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Д0200000', 'Основное мероприятие "Создание региональных информационно-навигационных систем в субъектах Российской Федерации, функционирующих с использованием технологий ГЛОНАСС"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Е0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Е0000000', 'Подпрограмма "Перевод автомобильного, железнодорожного, авиационного, морского и речного транспорта на использование газомоторного топлива"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Е0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Е0100000', 'Основное мероприятие "Разработка и реализация мер по поэтапному переходу на использование газомоторного топлива в транспортном комплексе"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='24Е0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('24Е0200000', 'Основное мероприятие "Научно-техническое обеспечение реализации Подпрограммы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2500000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2500000000', 'Государственная программа Российской Федерации "Государственная программа развития сельского хозяйства и регулирования рынков сельскохозяйственной продукции, сырья и продовольствия на 2013 - 2020 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510000000', 'Подпрограмма "Развитие подотрасли растениеводства, переработки и реализации продукции растениеводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510100000', 'Основное мероприятие "Развитие садоводства, поддержка закладки и ухода за многолетними насаждениями и виноградниками"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510150320') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510150320', 'Субсидии на возмещение части затрат на закладку и уход за виноградниками')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510150330') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510150330', 'Субсидии на возмещение части затрат на раскорчевку выбывших из эксплуатации старых садов и рекультивацию раскорчеванных площадей')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510150340') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510150340', 'Субсидии на возмещение части затрат на закладку и уход за многолетними плодовыми и ягодными насаждениями')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510200000', 'Основное мероприятие "Поддержка экономически значимых программ субъектов Российской Федерации в области растениеводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510250350') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510250350', 'Субсидии на поддержку экономически значимых региональных программ в области растениеводства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510300000', 'Основное мероприятие "Поддержка сельскохозяйственных товаропроизводителей в районах Крайнего Севера и приравненных к ним местностях"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510350360') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510350360', 'Субсидии на возмещение части затрат на приобретение семян с учетом доставки в районы Крайнего Севера и приравненные к ним местности')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510354370') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510354370', 'Субсидии на возмещение части прямых понесенных затрат на создание и модернизацию объектов плодохранилищ')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510400000', 'Основное мероприятие "Государственная поддержка кредитования подотрасли растениеводства, переработки ее продукции, развития инфраструктуры и логистического обеспечения рынков продукции растениеводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510450380') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510450380', 'Субсидии на возмещение части процентной ставки по краткосрочным кредитам (займам) на развитие растениеводства, переработки и реализации продукции растениеводства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510450390') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510450390', 'Субсидии на возмещение части процентной ставки по инвестиционным кредитам (займам) на развитие растениеводства, переработки и развития инфраструктуры и логистического обеспечения рынков продукции растениеводства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510500000', 'Основное мероприятие "Управление рисками в подотраслях растениеводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510550400') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510550400', 'Субсидии на возмещение части затрат сельскохозяйственных товаропроизводителей на уплату страховой премии, начисленной по договору сельскохозяйственного страхования в области растениеводства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510600000', 'Основное мероприятие "Регулирование рынков продукции растениеводства"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510664260') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510664260', 'Проведение закупочных и товарных интервенций на рынках сельскохозяйственной продукции, а также залоговых операций')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510700000', 'Основное мероприятие "Оказание несвязанной поддержки сельскохозяйственным товаропроизводителям в области растениеводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2510750410') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2510750410', 'Субсидии на оказание несвязанной поддержки сельскохозяйственным товаропроизводителям в области растениеводства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2520000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2520000000', 'Подпрограмма "Развитие подотрасли животноводства, переработки и реализации продукции животноводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2520100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2520100000', 'Основное мероприятие "Развитие овцеводства и козоводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2520150440') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2520150440', 'Субсидии на возмещение части затрат по наращиванию маточного поголовья овец и коз')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2520200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2520200000', 'Основное мероприятие "Развитие северного оленеводства и табунного коневодства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2520250450') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2520250450', 'Субсидии на возмещение части затрат по наращиванию поголовья северных оленей, маралов и мясных табунных лошадей')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2520300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2520300000', 'Основное мероприятие "Предупреждение распространения и ликвидация африканской чумы свиней на территории Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2520400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2520400000', 'Основное мероприятие "Обеспечение проведения противоэпизоотических мероприятий в субъектах Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2520500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2520500000', 'Основное мероприятие "Поддержка экономически значимых региональных программ развития сельского хозяйства субъектов Российской Федерации в области животноводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2520550460') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2520550460', 'Субсидии на поддержку экономически значимых региональных программ в области животноводства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2520600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2520600000', 'Основное мероприятие "Государственная поддержка кредитования подотрасли животноводства, переработки ее продукции, развития инфраструктуры и логистического обеспечения рынков продукции животноводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2520650470') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2520650470', 'Субсидии на возмещение части процентной ставки по краткосрочным кредитам (займам) на развитие животноводства, переработки и реализации продукции животноводства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2520650480') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2520650480', 'Субсидии на возмещение части процентной ставки по инвестиционным кредитам (займам) на развитие животноводства, переработки и развития инфраструктуры и логистического обеспечения рынков продукции животноводства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2520700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2520700000', 'Основное мероприятие "Управление рисками в подотраслях животноводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2520750490') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2520750490', 'Субсидии на возмещение части затрат сельскохозяйственных товаропроизводителей на уплату страховой премии, начисленной по договору сельскохозяйственного страхования в области животноводства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2520800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2520800000', 'Основное мероприятие "Регулирование рынков продукции животноводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2520900000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2520900000', 'Основное мероприятие "Государственная поддержка сельскохозяйственных товаропроизводителей, осуществляющих производство свинины, мяса птицы и яиц, в связи с удорожанием приобретенных кормов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2521000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2521000000', 'Основное мероприятие "Развитие производства тонкорунной и полутонкорунной шерсти"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2530000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2530000000', 'Подпрограмма "Развитие мясного скотоводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2530100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2530100000', 'Основное мероприятие "Государственная поддержка товарного маточного поголовья крупного рогатого скота мясных пород и их помесей"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2530200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2530200000', 'Основное мероприятие "Поддержка экономически значимых программ субъектов Российской Федерации в области мясного скотоводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2530250510') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2530250510', 'Субсидии на поддержку экономически значимых региональных программ по развитию мясного скотоводства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2530300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2530300000', 'Основное мероприятие "Государственная поддержка строительства и реконструкции объектов для мясного скотоводства"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2530350520') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2530350520', 'Субсидии на возмещение части процентной ставки по инвестиционным кредитам на строительство и реконструкцию объектов мясного скотоводства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2530454530') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2530454530', 'Субсидии на содержание товарного маточного поголовья крупного рогатого скота мясных пород и их помесей')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2540000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2540000000', 'Подпрограмма "Поддержка малых форм хозяйствования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2540100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2540100000', 'Основное мероприятие "Государственная поддержка кредитования малых форм хозяйствования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2540150550') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2540150550', 'Субсидии на возмещение части процентной ставки по долгосрочным, среднесрочным и краткосрочным кредитам, взятым малыми формами хозяйствования')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2540200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2540200000', 'Основное мероприятие "Оформление земельных участков в собственность крестьянскими (фермерскими) хозяйствами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2540250560') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2540250560', 'Субсидии на возмещение части затрат крестьянских (фермерских) хозяйств, включая индивидуальных предпринимателей, при оформлении в собственность используемых ими земельных участков из земель сельскохозяйственного назначения')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2540300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2540300000', 'Основное мероприятие "Поддержка начинающих фермеров"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2540350530') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2540350530', 'Субсидии на поддержку начинающих фермеров')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2540400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2540400000', 'Основное мероприятие "Развитие семейных животноводческих ферм на базе крестьянских (фермерских) хозяйств"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2540450540') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2540450540', 'Субсидии на развитие семейных животноводческих ферм')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2540500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2540500000', 'Основное мероприятие "Ведомственная целевая программа "О развитии сельскохозяйственной кооперации на 2014 - 2017 годы и на период до 2020 года""')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2550000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2550000000', 'Подпрограмма "Техническая и технологическая модернизация, инновационное развитие"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2550100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2550100000', 'Основное мероприятие "Обновление парка сельскохозяйственной техники"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2550164250') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2550164250', 'Субсидии производителям сельскохозяйственной техники')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2550200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2550200000', 'Основное мероприятие "Реализация перспективных инновационных проектов в агропромышленном комплексе"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2550250580') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2550250580', 'Субсидии на реализацию перспективных инновационных проектов в агропромышленном комплексе')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2550300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2550300000', 'Основное мероприятие "Развитие биотехнологии"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2550350570') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2550350570', 'Субсидии на возмещение части затрат на уплату процентов по кредитам, полученным на строительство, реконструкцию и модернизацию биоэнергетических установок, объектов по производству биотехнологической продукции')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2550400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2550400000', 'Основное мероприятие "Развитие рынка лизинга сельскохозяйственной техники и оборудования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2550460680') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2550460680', 'Субсидии лизинговым компаниям для поставки сельскохозяйственной техники и оборудования')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2560000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2560000000', 'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Государственная программа развития сельского хозяйства и регулирования рынков сельскохозяйственной продукции, сырья и продовольствия на 2013 - 2020 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2560100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2560100000', 'Основное мероприятие "Совершенствование управления реализацией Программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2560200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2560200000', 'Основное мероприятие "Совершенствование системы налогообложения в сельском хозяйстве"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2560300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2560300000', 'Основное мероприятие "Совершенствование механизма финансового оздоровления сельскохозяйственных товаропроизводителей в рамках Федерального закона "О финансовом оздоровлении сельскохозяйственных товаропроизводителей"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2560320230') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2560320230', 'Оказание государственной поддержки сельскохозяйственных товаропроизводителей по решениям Правительства Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2560400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2560400000', 'Основное мероприятие "Оказание государственных услуг и выполнение работ в рамках реализации государственной программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2560500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2560500000', 'Основное мероприятие "Формирование государственных информационных ресурсов в сферах обеспечения продовольственной безопасности и управления агропромышленным комплексом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2560600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2560600000', 'Основное мероприятие "Обеспечение государственного мониторинга земель сельскохозяйственного назначения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2560700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2560700000', 'Основное мероприятие "Обеспечение функций в области ветеринарного и фитосанитарного надзора"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2560800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2560800000', 'Основное мероприятие "Осуществление компенсации понесенных затрат сельскохозяйственных товаропроизводителей вследствие причиненного ущерба в результате чрезвычайных ситуаций природного характера"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2560854730') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2560854730', 'Иные межбюджетные трансферты на осуществление компенсации сельскохозяйственным товаропроизводителям ущерба, причиненного в результате чрезвычайных ситуаций природного характера в отдельных регионах Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2570000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2570000000', 'Федеральная целевая программа "Устойчивое развитие сельских территорий на 2014 - 2017 годы и на период до 2020 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2580000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2580000000', 'Федеральная целевая программа "Развитие мелиорации земель сельскохозяйственного назначения  России на 2014 - 2020 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2590000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2590000000', 'Подпрограмма "Развитие овощеводства открытого и защищенного грунта и семенного картофелеводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2590100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2590100000', 'Основное мероприятие "Развитие производства семенного картофеля и овощей открытого грунта"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2590200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2590200000', 'Основное мероприятие "Развитие производства овощей защищенного грунта"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Б0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Б0000000', 'Подпрограмма "Развитие молочного скотоводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Б0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Б0100000', 'Основное мероприятие "Развитие молочного скотоводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Б0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Б0200000', 'Основное мероприятие "Государственная поддержка кредитования подотрасли молочного скотоводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Б0300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Б0300000', 'Основное мероприятие "Идентификация маточного поголовья крупного рогатого скота молочного направления"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Б0354540') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Б0354540', 'Субсидии на идентификацию племенного маточного поголовья крупного рогатого скота молочного направления')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Г0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Г0000000', 'Подпрограмма  "Поддержка племенного дела, селекции и семеноводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Г0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Г0100000', 'Основное мероприятие "Развитие элитного семеноводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Г0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Г0200000', 'Основное мероприятие "Поддержка племенного животноводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Г0300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Г0300000', 'Основное мероприятие "Развитие племенной базы молочного скотоводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Г0400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Г0400000', 'Основное мероприятие "Развитие племенной базы мясного скотоводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Г0500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Г0500000', 'Основное мероприятие "Государственная поддержка строительства объектов селекционно-генетических и селекционно-семеноводческих центров"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Г0600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Г0600000', 'Основное мероприятие "Государственная поддержка кредитования развития селекционно-генетических и селекционно-семеноводческих центров в подотраслях животноводства и растениеводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Д0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Д0000000', 'Подпрограмма  "Развитие оптово-распределительных центров и инфраструктуры системы социального питания"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Д0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Д0100000', 'Основное мероприятие "Государственная поддержка кредитования развития оптово-распределительных центров, производства и товаропроводящей инфраструктуры системы социального питания"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Д0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Д0200000', 'Основное мероприятие "Государственная поддержка строительства объектов оптово-распределительных центров, производства и товаропроводящей инфраструктуры системы социального питания"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Ж0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Ж0000000', 'Подпрограмма "Развитие финансово-кредитной системы агропромышленного комплекса"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Ж0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Ж0100000', 'Основное мероприятие "Докапитализация открытого акционерного общества "Россельхозбанк"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='25Ж0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('25Ж0200000', 'Основное мероприятие "Развитие рынка лизинга сельскохозяйственной техники и оборудования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2600000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2600000000', 'Государственная программа Российской Федерации "Развитие рыбохозяйственного комплекса"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2610000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2610000000', 'Подпрограмма "Организация рыболовства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2610100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2610100000', 'Основное мероприятие "Повышение эффективности в области организации рыболовства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2610200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2610200000', 'Основное мероприятие "Развитие промышленного и прибрежного рыболовства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2610300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2610300000', 'Основное мероприятие "Развитие рыболовства в районах действия международных договоров Российской Федерации в области рыболовства и сохранения водных биологических ресурсов и открытой части Мирового океана"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2610400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2610400000', 'Основное мероприятие "Совершенствование работы государственного рыбохозяйственного реестра и повышение эффективности его использования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2620000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2620000000', 'Подпрограмма "Развитие аквакультуры"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2620100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2620100000', 'Основное мероприятие "Осуществление работ по искусственному воспроизводству водных биологических ресурсов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2620200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2620200000', 'Основное мероприятие "Осуществление работ по сохранению водных биологических ресурсов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2620300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2620300000', 'Основное мероприятие "Информационное обеспечение деятельности предприятий аквакультуры"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2620400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2620400000', 'Основное мероприятие "Государственная поддержка субъектов аквакультуры"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2620453960') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2620453960', 'Субсидии сельскохозяйственным товаропроизводителям на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях, на развитие аквакультуры (рыбоводство)')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2620500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2620500000', 'Основное мероприятие "Стимулирование научно-исследовательской и опытно-конструкторской деятельности в области аквакультуры"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2620600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2620600000', 'Основное мероприятие "Строительство и реконструкция рыбоводных заводов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2630000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2630000000', 'Подпрограмма "Наука и инновации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2630100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2630100000', 'Основное мероприятие "Проведение рыбохозяйственных исследований"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2630200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2630200000', 'Основное мероприятие "Проведение научно-исследовательских работ в области формирования инфраструктуры и развития рыбохозяйственного комплекса"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2640000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2640000000', 'Подпрограмма "Охрана и контроль"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2640100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2640100000', 'Основное мероприятие "Совершенствование деятельности по предупреждению, сдерживанию и ликвидации незаконного, несообщаемого и нерегулируемого промысла водных биологических ресурсов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2640200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2640200000', 'Основное мероприятие "Повышение безопасности плавания судов рыбопромыслового флота и выполнение комплекса аварийно-спасательных работ на рыбопромысловых судах в районах промысла при осуществлении рыболовства"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2640300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2640300000', 'Основное мероприятие "Совершенствование разграничения полномочий в области контроля, надзора и охраны водных биологических ресурсов на внутренних водных объектах рыбохозяйственного значения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2640400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2640400000', 'Основное мероприятие "Обеспечение государственного контроля (надзора) в области рыболовства и сохранения водных биологических ресурсов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2640500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2640500000', 'Основное мероприятие "Информационное обеспечение деятельности рыбохозяйственного комплекса"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2650000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2650000000', 'Подпрограмма "Модернизация и стимулирование"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2650100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2650100000', 'Основное мероприятие "Стимулирование модернизации существующего и строительства нового рыбопромыслового флота"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2650164270') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2650164270', 'Субсидии на возмещение рыбохозяйственным организациям и индивидуальным предпринимателям части затрат на уплату процентов по инвестиционным кредитам, полученным в российских кредитных организациях, на строительство и модернизацию рыбопромысловых судов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2650200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2650200000', 'Основное мероприятие "Стимулирование модернизации и строительства объектов рыбоперерабатывающей инфраструктуры, объектов хранения рыбной продукции"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2650264280') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2650264280', 'Субсидии на возмещение рыбохозяйственным организациям и индивидуальным предпринимателям части затрат на уплату процентов по инвестиционным кредитам, полученным в российских кредитных организациях, на строительство и модернизацию объектов рыбоперераба')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2650300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2650300000', 'Основное мероприятие "Развитие выставочной деятельности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2660000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2660000000', 'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Развитие рыбохозяйственного комплекса"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2660100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2660100000', 'Основное мероприятие "Руководство и управление в сфере установленных функций"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2660200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2660200000', 'Основное мероприятие "Мониторинг выполнения государственных услуг и работ в рамках реализации государственной программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2670000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2670000000', 'Подпрограмма "Повышение эффективности использования и развитие ресурсного потенциала рыбохозяйственного комплекса"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2670100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2670100000', 'Основное мероприятие "Строительство и реконструкция рыбоводных заводов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2670200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2670200000', 'Основное мероприятие "Развитие научно-производственной базы аквакультуры"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2670300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2670300000', 'Основное мероприятие "Обеспечение эффективной и безопасной добычи водных биологических ресурсов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2670400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2670400000', 'Основное мероприятие "Повышение качества государственного мониторинга контроля добычи водных биологических ресурсов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2670500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2670500000', 'Основное мероприятие "Реконструкция объектов федеральной собственности портовых сооружений рыбных терминалов морских портов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2670600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2670600000', 'Основное мероприятие "Комплексная капитальная реконструкция научно-исследовательских судов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2680000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2680000000', 'Подпрограмма "Развитие осетрового хозяйства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2680100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2680100000', 'Основное мероприятие "Межведомственное взаимодействие и контроль, направленные на борьбу с незаконной добычей (выловом) осетровых видов рыб"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2680200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2680200000', 'Основное мероприятие "Международная деятельность в области регулирования рыболовства, сохранения и воспроизводства осетровых видов рыб в бассейне Каспийского моря"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2680300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2680300000', 'Основное мероприятие "Государственная поддержка товарного осетроводства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2680354160') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2680354160', 'Субсидии на возмещение сельскохозяйственным товаропроизводителям части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях, на развитие товарного осетроводства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2680400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2680400000', 'Основное мероприятие "Развитие технологий товарного осетроводства"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2680500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2680500000', 'Основное мероприятие "Мониторинг состояния запасов осетровых видов рыб"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2680600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2680600000', 'Основное мероприятие "Осуществление работ по искусственному воспроизводству осетровых видов рыб"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2680700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2680700000', 'Основное мероприятие "Мелиорация водных объектов рыбохозяйственного значения (для осетровых видов рыб)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2700000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2700000000', 'Государственная программа Российской Федерации "Развитие внешнеэкономической деятельности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2710000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2710000000', 'Подпрограмма "Реализация приоритетных направлений внешнеэкономической деятельности в процессе международного экономического сотрудничества"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2710100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2710100000', 'Основное мероприятие "Расширение двустороннего торгово-экономического сотрудничества с зарубежными странами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2710127970') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2710127970', 'Субсидии российским организациям на обеспечение деятельности на архипелаге Шпицберген')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2710200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2710200000', 'Основное мероприятие "Развитие многостороннего экономического сотрудничества и интеграционных процессов на пространстве Содружества Независимых Государств"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2710300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2710300000', 'Основное мероприятие "Обеспечение участия и защиты интересов Российской Федерации в деятельности Всемирной торговой организации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2710400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2710400000', 'Основное мероприятие "Развитие интеграции Российской Федерации в международную экономическую систему, обеспечение участия в международных экономических организациях, форумах и соглашениях"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2710500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2710500000', 'Основное мероприятие "Развитие взаимодействия с региональными экономическими организациями"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2720000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2720000000', 'Подпрограмма "Формирование Евразийского экономического союза"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2720100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2720100000', 'Основное мероприятие "Создание, развитие и имплементация системы соглашений по формированию и обеспечению функционирования Евразийского экономического союза"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2720200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2720200000', 'Основное мероприятие "Обеспечения деятельности наднациональных и межгосударственных органов Евразийского экономического союза с передачей им необходимых полномочий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2730000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2730000000', 'Подпрограмма "Создание национальной системы поддержки развития внешнеэкономической деятельности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2730100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2730100000', 'Основное мероприятие "Финансовая поддержка экспорта"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2730165920') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2730165920', 'Имущественный взнос в государственную корпорацию "Банк развития и внешнеэкономической деятельности (Внешэкономбанк)" на цели приобретения акций открытого акционерного общества "Российское агентство по страхованию экспортных кредитов и инвестиций", г.')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2730200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2730200000', 'Основное мероприятие "Промоутерская поддержка экспорта и инвестиционного сотрудничества"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2730300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2730300000', 'Основное мероприятие "Обеспечение планирования, координации и мониторинга внешнеэкономической деятельности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2730400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2730400000', 'Основное мероприятие "Устранение барьеров для экспорта и инвестиций на внешних рынках"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2730500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2730500000', 'Основное мероприятие "Развитие деятельности торговых представительств Российской Федерации в иностранных государствах по продвижению экономических интересов в глобальной экономике"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2730600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2730600000', 'Основное мероприятие "Создание организаций инфраструктуры поддержки субъектов малого и среднего предпринимательства, осуществляющих внешнеэкономическую деятельность"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2730700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2730700000', 'Основное мероприятие "Развитие системы подготовки, переподготовки и повышения квалификации кадров в сфере внешнеэкономической деятельности "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2740000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2740000000', 'Подпрограмма "Совершенствование системы государственного регулирования внешнеэкономической деятельности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2740100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2740100000', 'Основное мероприятие "Обеспечение эффективной реализации функций внешнеторгового регулирования в формате Таможенного союза"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2740200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2740200000', 'Основное мероприятие "Упрощение административных и налоговых правил и процедур для участников внешнеэкономической деятельности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2750000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2750000000', 'Подпрограмма "Совершенствование таможенной деятельности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2750100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2750100000', 'Основное мероприятие "Совершенствование деятельности таможенных органов Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2750139930') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2750139930', 'Предоставление путевок (пособий) на санаторно-курортное лечение и (или) денежной компенсации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2750200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2750200000', 'Основное мероприятие "Развитие административной и социальной инфраструктуры таможенных органов Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2760000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2760000000', 'Подпрограмма "Обеспечение развития системы пунктов пропуска через Государственную границу Российской Федерации для осуществления внешнеэкономической деятельности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2760100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2760100000', 'Основное мероприятие "Совершенствование системы пунктов пропуска, создание благоприятных условий для перемещения через Государственную границу грузов и пересечения ее физическими лицами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2760200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2760200000', 'Основное мероприятие "Осуществление международной деятельности Росграницы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2760300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2760300000', 'Основное мероприятие "Обеспечение деятельности центрального аппарата и территориальных органов Росграницы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2800000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2800000000', 'Государственная программа "Воспроизводство и использование природных ресурсов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2810000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2810000000', 'Подпрограмма "Воспроизводство минерально-сырьевой базы, геологическое изучение недр"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2810100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2810100000', 'Основное мероприятие "Региональные геолого-геофизические и геолого-съемочные работы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2810200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2810200000', 'Основное мероприятие "Работы специального геологического назначения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2810300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2810300000', 'Основное мероприятие "Государственный мониторинг состояния недр, гидрогеологическая и инженерно-геологическая съемка"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2810400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2810400000', 'Основное мероприятие "Государственное геологическое информационное обеспечение"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2810500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2810500000', 'Основное мероприятие "Воспроизводство минерально-сырьевой базы углеводородного сырья"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2810600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2810600000', 'Основное мероприятие "Воспроизводство минерально-сырьевой базы твердых полезных ископаемых"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2810700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2810700000', 'Основное мероприятие "Воспроизводство минерально-сырьевой базы подземных вод (питьевых и минеральных)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2810800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2810800000', 'Основное мероприятие "Воспроизводство минерально-сырьевой базы общераспространенных полезных ископаемых"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2810900000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2810900000', 'Основное мероприятие "Воспроизводство минерально-сырьевой базы и геологическое изучение недр в Крымском федеральном округе"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2811000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2811000000', 'Основное мероприятие "Научно-аналитическое и инновационное обеспечение государственной политики в сфере развития и использования минерально-сырьевой базы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2811100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2811100000', 'Основное мероприятие "Научно-техническое обеспечение геолого-разведочных работ"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2811200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2811200000', 'Основное мероприятие "Тематические и опытно-методические работы, связанные с геологическим изучением недр и воспроизводством минерально-сырьевой базы, мониторингом недропользования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2811300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2811300000', 'Основное мероприятие "Организация добычи метана угольных пластов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2811400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2811400000', 'Основное мероприятие "Координация и контроль деятельности по реализации государственной системы лицензирования пользования недрами"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2811500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2811500000', 'Основное мероприятие "Модернизация, проектирование и строительство научно-исследовательских судов и технологического оборудования для работ в Мировом океане, а также в пределах континентального шельфа, Арктики и Антарктики"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2811600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2811600000', 'Основное мероприятие "Обеспечение эффективной реализации государственных функций в сфере недропользования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2811700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2811700000', 'Основное мероприятие "Обеспечение участия Российской Федерации в международных организациях (соглашениях) в сфере геологического изучения недр и воспроизводства минерально-сырьевой базы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2820000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2820000000', 'Подпрограмма "Использование водных ресурсов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2820100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2820100000', 'Основное мероприятие "Нормативно-правовое и научно-методическое обеспечение реализации государственной политики в сфере использования водных ресурсов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2820200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2820200000', 'Основное мероприятие "Осуществление нормирования водопользования, мониторинга водных объектов и других водохозяйственных мероприятий текущего характера"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2820300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2820300000', 'Основное мероприятие "Выполнение работ по содержанию и обеспечению безопасной эксплуатации гидротехнических сооружений и охрана водохранилищ"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2820400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2820400000', 'Основное мероприятие "Обеспечение исполнения субъектами Российской Федерации переданных полномочий Российской Федерации в области водных отношений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2820451280') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2820451280', 'Субвенции на осуществление отдельных полномочий в области водных отношений')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2820500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2820500000', 'Основное мероприятие "Создание и эксплуатация защитных сооружений от наводнений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2820564290') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2820564290', 'Субсидии на содержание комплекса защитных сооружений г. Санкт-Петербурга от наводнений')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2820600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2820600000', 'Основное мероприятие "Обеспечение эффективной реализации государственных функций в сфере водных отношений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2820654140') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2820654140', 'Субвенции бюджетам Республики Крым и города федерального значения Севастополя на осуществление части полномочий Российской Федерации в области водных отношений')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2830000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2830000000', 'Подпрограмма "Сохранение и воспроизводство охотничьих ресурсов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2830100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2830100000', 'Основное мероприятие "Совершенствование нормативной правовой и методической базы в сфере сохранения и воспроизводства охотничьих ресурсов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2830200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2830200000', 'Основное мероприятие "Информационно-аналитическое обеспечение в сфере сохранения и воспроизводства охотничьих ресурсов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2830300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2830300000', 'Основное мероприятие "Обеспечение сохранения и воспроизводства охотничьих ресурсов в государственных опытных охотничьих хозяйствах"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2830400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2830400000', 'Основное мероприятие "Обеспечение эффективного исполнения субъектами Российской Федерации переданных полномочий Российской Федерации в области охоты и сохранения охотничьих ресурсов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2860000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2860000000', 'Федеральная целевая программа "Развитие водохозяйственного комплекса Российской Федерации в 2012 - 2020 годах"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2860050160') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2860050160', 'Субсидии на мероприятия федеральной целевой программы "Развитие водохозяйственного комплекса Российской Федерации в 2012 - 2020 годах"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2900000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2900000000', 'Государственная программа Российской Федерации "Развитие лесного хозяйства" на 2013 - 2020 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2910000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2910000000', 'Подпрограмма "Обеспечение использования, охраны, защиты и воспроизводства лесов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2910100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2910100000', 'Основное мероприятие "Обеспечение контроля пожарной опасности в лесах и готовности к действиям сил и средств, предназначенных для предупреждения и ликвидации чрезвычайных ситуаций в лесах, возникших вследствие лесных пожаров"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2910200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2910200000', 'Основное мероприятие "Государственный лесопатологический мониторинг в лесах, расположенных на землях лесного фонда"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2910300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2910300000', 'Основное мероприятие "Радиационный мониторинг лесов, расположенных на землях лесного фонда"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2910400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2910400000', 'Основное мероприятие "Государственный мониторинг воспроизводства лесов, формирование и хранение федерального фонда семян лесных растений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2910500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2910500000', 'Основное мероприятие "Обеспечение исполнения переданных субъектам Российской Федерации полномочий Российской Федерации в области лесных отношений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2910551290') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2910551290', 'Субвенции на осуществление отдельных полномочий в области лесных отношений')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2910551310') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2910551310', 'Субсидии на приобретение специализированной лесопожарной техники и оборудования')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2910552210') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2910552210', 'Субвенции бюджетам Республики Крым и города федерального значения Севастополя на осуществление части полномочий Российской Федерации в области лесных отношений')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2910553980') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2910553980', 'Иные межбюджетные трансферты на софинансирование расходов Республики Алтай по договору финансовой аренды (лизинга) вертолета')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2940000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2940000000', 'Подпрограмма "Стратегическое управление лесным хозяйством"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2940100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2940100000', 'Основное мероприятие "Обеспечение стратегического управления лесным хозяйством"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2940200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2940200000', 'Основное мероприятие "Научно-аналитическое обеспечение в сфере реализации государственной программы, направленное на повышение научно-технического потенциала лесного сектора экономики"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='2940300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('2940300000', 'Основное мероприятие "Обеспечение исполнения государственных функций Рослесхозом, формирование условий для участия граждан в принятии решений в области лесных отношений, развитие международного сотрудничества"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3000000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3000000000', 'Государственная программа Российской Федерации "Энергоэффективность и развитие энергетики"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3010000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3010000000', 'Подпрограмма "Энергосбережение и повышение энергетической эффективности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3010100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3010100000', 'Основное мероприятие "Создание благоприятных условий для формирования институтов и инфраструктуры, способствующих энергосбережению и повышению энергетической эффективности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3010200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3010200000', 'Основное мероприятие "Создание благоприятных условий и снижение административных и иных барьеров в целях привлечения инвестиций в область энергосбережения и повышения энергетической эффективности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3010300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3010300000', 'Основное мероприятие "Информационное обеспечение и пропаганда энергосбережения и повышения энергетической эффективности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3010400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3010400000', 'Основное мероприятие "Поддержка мероприятий (проектов) в области энергосбережения и повышения энергетической эффективности в субъектах Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3010450130') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3010450130', 'Субсидии на реализацию региональных программ в области энергосбережения и повышения энергетической эффективности')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3010500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3010500000', 'Основное мероприятие "Выполнение научно-исследовательских работ в области энергосбережения и повышения энергетической эффективности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3010600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3010600000', 'Основное мероприятие "Реализация образовательных программ в области энергосбережения и повышения энергетической эффективности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3020000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3020000000', 'Подпрограмма "Развитие и модернизация электроэнергетики"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3020100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3020100000', 'Основное мероприятие "Модернизация и новое строительство генерирующих мощностей"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3020200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3020200000', 'Основное мероприятие "Модернизация и новое строительство электросетевых объектов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3020267940') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3020267940', 'Взнос в уставный капитал открытого акционерного общества "Российские сети", г. Москва')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3020300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3020300000', 'Основное мероприятие "Повышение доступности энергетической инфраструктуры"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3020400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3020400000', 'Основное мероприятие "Ликвидация межтерриториального перекрестного субсидирования в электроэнергетике"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3020453880') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3020453880', 'Субсидии на ликвидацию перекрестного субсидирования в электроэнергетике')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3020500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3020500000', 'Основное мероприятие "Возмещение недополученных доходов сетевых организаций в результате отмены механизма "последней мили"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3030000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3030000000', 'Подпрограмма "Развитие нефтяной отрасли"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3030100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3030100000', 'Основное мероприятие "Обеспечение уровней добычи нефти на месторождениях, находящихся в стадии эксплуатации, и развитие новых центров нефтедобычи"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3030200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3030200000', 'Основное мероприятие "Строительство, модернизация, реконструкция и эксплуатация трубопроводных систем"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3030300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3030300000', 'Основное мероприятие "Строительство, модернизация, реконструкция нефтеперерабатывающих предприятий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3040000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3040000000', 'Подпрограмма "Развитие газовой отрасли"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3040100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3040100000', 'Основное мероприятие "Проведение технологического перевооружения газовой отрасли за счет внедрения энергосберегающих и энергоэффективных технологий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3040200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3040200000', 'Основное мероприятие "Реализация проектов по реконструкции существующих и строительству новых мощностей транспортировки газа"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3040300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3040300000', 'Основное мероприятие "Расширение действующих и строительство новых подземных хранилищ газа"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3040400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3040400000', 'Основное мероприятие "Создание системы сбыта сжиженного природного газа"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3040500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3040500000', 'Основное мероприятие "Разработка и внедрение новых отечественных технологий производства сжиженного природного газа"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3040600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3040600000', 'Основное мероприятие "Строительство, модернизация, реконструкция нефтегазохимических предприятий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3050000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3050000000', 'Подпрограмма "Реструктуризация и развитие угольной и торфяной промышленности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3050100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3050100000', 'Основное мероприятие "Модернизация действующих предприятий на основе инновационных и энергоэффективных технологий "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3050200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3050200000', 'Основное мероприятие "Создание новых центров угледобычи на месторождениях с благоприятными горно-геологическими условиями"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3050300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3050300000', 'Основное мероприятие "Обеспечение промышленной и экологической безопасности и охраны труда"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3050400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3050400000', 'Основное мероприятие "Развитие добычи торфа "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3050500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3050500000', 'Основное мероприятие "Развитие внутреннего рынка угольной продукции"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3050600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3050600000', 'Основное мероприятие "Укрепление позиций России на мировом рынке угля"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3050700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3050700000', 'Основное мероприятие "Реструктуризация угольной промышленности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3050735970') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3050735970', 'Дополнительное пенсионное обеспечение (негосударственные пенсии) работников организаций по добыче (переработке) угля (горючих сланцев), подразделений военизированных аварийно-спасательных частей и шахтостроительных организаций в соответствии с Федера')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3050751560') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3050751560', 'Иные межбюджетные трансферты на реализацию программ местного развития и обеспечение занятости для шахтерских городов и поселков')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3060000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3060000000', 'Подпрограмма "Развитие использования возобновляемых источников энергии"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3060100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3060100000', 'Основное мероприятие "Стимулирование производства электрической энергии генерирующими объектами, функционирующими на основе использования возобновляемых источников энергии"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3060200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3060200000', 'Основное мероприятие "Государственная поддержка технологического присоединения  генерирующих объектов, функционирующих на основе использования возобновляемых источников энергии"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3060300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3060300000', 'Основное мероприятие "Проведение оценки технического и экономического потенциала использования возобновляемых источников энергии в Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3060400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3060400000', 'Основное мероприятие "Поддержка генерации на основе использования возобновляемых источников энергии"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3070000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3070000000', 'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Энергоэффективность и развитие энергетики"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3070100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3070100000', 'Основное мероприятие "Совершенствование процессов сбора, обработки, хранения и использования информационных ресурсов топливно-энергетического комплекса и развитие государственной информационной системы топливно-энергетического комплекса"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3070200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3070200000', 'Основное мероприятие "Формирование, хранение, ведение и организация использования информационных ресурсов топливно-энергетического комплекса, организационно-технологическое сопровождение функционирования государственной информационной системы топливн')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3070300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3070300000', 'Основное мероприятие "Реализация функций аппарата ответственного исполнителя государственной программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3070400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3070400000', 'Основное мероприятие "Развитие международного сотрудничества"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3070500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3070500000', 'Основное мероприятие "Инновационное развитие организаций топливно-энергетического комплекса"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3200000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3200000000', 'Государственная программа Российской Федерации "Обеспечение государственной безопасности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3210000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3210000000', 'Подпрограмма "Государственная безопасность"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3210100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3210100000', 'Основное мероприятие "Контрразведывательная деятельность"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3210200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3210200000', 'Основное мероприятие "Борьба с терроризмом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3210300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3210300000', 'Основное мероприятие "Обеспечение экономической безопасности, борьба с преступностью и коррупцией"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3210400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3210400000', 'Основное мероприятие "Разведывательная деятельность"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3210500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3210500000', 'Основное мероприятие "Обеспечение информационной безопасности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3210600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3210600000', 'Основное мероприятие "Обеспечение реализации подпрограммы "Государственная безопасность"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3220000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3220000000', 'Подпрограмма "Защита и охрана Государственной границы Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3220100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3220100000', 'Основное мероприятие "Охрана Государственной границы, защита экономических и иных законных интересов на суше, реках и озерах Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3220200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3220200000', 'Основное мероприятие "Охрана Государственной границы, защита экономических и иных законных интересов Российской Федерации на морских направлениях"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3220300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3220300000', 'Основное мероприятие "Обеспечение реализации подпрограммы "Защита и охрана Государственной границы Российской Федерации""')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3230000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3230000000', 'Подпрограмма "Противодействие легализации (отмыванию) доходов, полученных преступным путем, и финансированию терроризма"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3230100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3230100000', 'Основное мероприятие "Укрепление и расширение международного сотрудничества в сфере противодействия легализации (отмыванию) доходов, полученных преступным путем, и финансированию терроризма"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3230200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3230200000', 'Основное мероприятие "Развитие информационно-технологического обеспечения в сфере противодействия легализации (отмыванию) доходов, полученных преступным путем, и финансированию терроризма"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3240000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3240000000', 'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Обеспечение государственной безопасности"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3240100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3240100000', 'Основное мероприятие "Содержание аппаратов управления"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3240130140') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3240130140', 'Возмещение федеральными органами исполнительной власти расходов на погребение')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3240135800') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3240135800', 'Субсидия для приобретения или строительства жилого помещения (жилых помещений), предоставляемая военнослужащим - гражданам Российской Федерации и иным лицам в соответствии с Федеральным законом от 27 мая 1998 года № 76-ФЗ "О статусе военнослужащих"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3240200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3240200000', 'Основное мероприятие "Проведение прикладных научных исследований в области национальной безопасности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3240300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3240300000', 'Основное мероприятие "Осуществление жилищного строительства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3240400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3240400000', 'Основное мероприятие "Содержание образовательных учреждений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3240500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3240500000', 'Основное мероприятие "Содержание учреждений издательств, учреждений культуры, спортивных объектов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3240600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3240600000', 'Основное мероприятие "Содержание учреждений здравоохранения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3240700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3240700000', 'Основное мероприятие "Осуществление ежемесячных денежных выплат отдельным категориям граждан"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3240730040') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3240730040', 'Компенсация в возмещение вреда гражданам, подвергшимся воздействию радиации вследствие радиационных аварий, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию радиации всл')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3240730170') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3240730170', 'Пособия, выплаты и компенсации членам семей военнослужащих, а также лицам, уволенным с военной службы без права на пенсию')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3250000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3250000000', 'Федеральная целевая программа "Антитеррор (2017 - 2021 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3260000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3260000000', 'Федеральная целевая программа "Государственная граница Российской Федерации (2012 - 2020 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3270000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3270000000', 'Федеральная целевая программа, утвержденная постановлением Правительства Российской Федерации от 10 ноября 2007 года          № 772-36')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3280000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3280000000', 'Федеральная целевая программа "Создание в Российской Федерации системы глобального мониторинга информационно-телекоммуникационной  сети Интернет на период 2014 - 2021 годов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3400000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3400000000', 'Государственная программа Российской Федерации "Социально-экономическое развитие Дальнего Востока и Байкальского региона"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='34Д0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('34Д0000000', 'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Социально-экономическое развитие Дальнего Востока и Байкальского региона" и прочие мероприятия в области сбалансированного территориального развития"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='34Д0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('34Д0100000', 'Основное мероприятие "Организационно-аналитическое и научно-методическое сопровождение государственной программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='34Д0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('34Д0200000', 'Основное мероприятие "Развитие нормативной правовой базы и формирование стратегических документов по вопросам развития Дальнего Востока и Байкальского региона"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='34Д0300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('34Д0300000', 'Основное мероприятие "Обеспечение деятельности аппарата ответственного исполнителя"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='34Ж0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('34Ж0000000', 'Федеральная целевая программа "Экономическое и социальное развитие Дальнего Востока и Байкальского региона на период до 2018 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='34Ж0052140') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('34Ж0052140', 'Финансовое обеспечение мероприятий по экономическому и социальному развитию Дальнего Востока и Байкальского региона на период до 2018 года')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='34Ж0067240') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('34Ж0067240', 'Взнос в уставный капитал открытого акционерного общества "Дальневосточная энергетическая управляющая компания", г. Владивосток, Приморский край')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='34Ж0067250') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('34Ж0067250', 'Взнос в уставный капитал открытого акционерного общества "РАО Энергетические системы Востока", г. Хабаровск')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='34И0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('34И0000000', 'Федеральная целевая программа "Социально-экономическое развитие Курильских островов (Сахалинская область) на 2007 - 2015 годы"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='34И0051000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('34И0051000', 'Субсидии на реализацию мероприятий федеральной целевой программы "Социально-экономическое развитие Курильских островов (Сахалинская область) на 2007 - 2015 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3500000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3500000000', 'Государственная программа Российской Федерации "Развитие Северо-Кавказского федерального округа" на период до 2025 года')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3510000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3510000000', 'Подпрограмма "Развитие инвестиционной привлекательности Северо-Кавказского федерального округа"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3510100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3510100000', 'Основное мероприятие "Разработка, внедрение и сопровождение комплексной информационной системы мониторинга инвестиционной деятельности в Северо-Кавказском федеральном округе"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3510200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3510200000', 'Основное мероприятие "Мониторинг и содействие реализации на территории Северо-Кавказского федерального округа инвестиционных проектов крупных компаний, государственных корпораций, акционерных обществ с государственным участием и институтов развития"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3520000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3520000000', 'Подпрограмма "Развитие особо охраняемого эколого-курортного региона Российской Федерации - Кавказские Минеральные Воды"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3520100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3520100000', 'Основное мероприятие "Создание комплекса транспортной, инженерной, коммунальной инфраструктуры в целях содействия реализации приоритетных инвестиционных проектов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3520200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3520200000', 'Основное мероприятие "Разработка и реализация мероприятий, направленных на развитие курортно-туристического кластера Кавказских Минеральных Вод"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3520300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3520300000', 'Основное мероприятие "Разработка и реализация мероприятий, способствующих созданию благоприятных условий для устойчивого развития региона Кавказских Минеральных Вод"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3530000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3530000000', 'Подпрограмма "Развитие туристического кластера в Северо-Кавказском федеральном округе, Краснодарском крае и Республике Адыгея"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3530100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3530100000', 'Основное мероприятие "Создание благоприятных условий для привлечения инвестиций в курорты туристического кластера"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3530200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3530200000', 'Основное мероприятие "Создание Всесезонного туристско-рекреационного комплекса "Мамисон" на территориях Алагирского и Ирафского районов Республики Северная Осетия - Алания ("Мамисон")"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3530300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3530300000', 'Основное мероприятие "Создание Всесезонного туристско-рекреационного комплекса "Архыз" на территориях Зеленчукского и Урупского районов Карачаево-Черкесской Республики ("Архыз")"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3530400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3530400000', 'Основное мероприятие "Создание Всесезонного туристско-рекреационного комплекса "Эльбрус-Безенги" на территориях Черекского, Чегемского, Эльбрусского и Зольского районов Кабардино-Балкарской Республики ("Эльбрус-Безенги")"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3530500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3530500000', 'Основное мероприятие "Создание Всесезонных туристско-рекреационных комплексов "Армхи" и "Цори" на территориях Джейрахского и Сунженского районов республики Ингушетия ("Армхи" и "Цори")"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3530600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3530600000', 'Основное мероприятие "Создание Всесезонного туристско-рекреационного комплекса "Лагонаки" на территориях Майкопского района Республики Адыгея и Апшеронского района Краснодарского края ("Лагонаки")"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3530700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3530700000', 'Основное мероприятие "Создание Всесезонного туристско-рекреационного комплекса "Матлас" на территориях Хунзанского района Республики Дагестан ("Матлас")"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3530800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3530800000', 'Основное мероприятие "Создание рекреационных комплексов на территориях Дербентского, Карабудахкентского, Каякентского и Магарамкентского районов Республики Дагестан ("Прибрежные курорты")"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3530900000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3530900000', 'Основное мероприятие "Содействие формированию положительного имиджа региона и продвижение туристического кластера среди потенциальных инвесторов и иных целевых аудиторий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='35Г0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('35Г0000000', 'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Развитие Северо-Кавказского федерального округа" на период до 2025 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='35Г0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('35Г0100000', 'Основное мероприятие "Организационно-аналитическое сопровождение и мониторинг реализации государственной программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='35Г0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('35Г0200000', 'Основное мероприятие "Развитие нормативной правовой базы и формирование стратегических документов по вопросам развития Северо-Кавказского федерального округа"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='35Г0300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('35Г0300000', 'Основное мероприятие "Мероприятия по завершению ранее начатых строительством объектов федеральной собственности на территории Чеченской Республики"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='35Д0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('35Д0000000', 'Федеральная целевая программа "Социально-экономическое развитие Республики Ингушетия на 2010 - 2016 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='35Д0050190') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('35Д0050190', 'Субсидии на мероприятия федеральной целевой программы "Социально-экономическое развитие Республики Ингушетия на 2010 - 2016 годы"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='35Ж0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('35Ж0000000', 'Федеральная целевая программа "Юг России (2014 - 2020 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='35Ж0051010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('35Ж0051010', 'Субсидии на реализацию мероприятий федеральной целевой программы "Юг России (2014 - 2020 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3600000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3600000000', 'Государственная программа Российской Федерации "Развитие федеративных отношений и создание условий для эффективного и ответственного управления региональными и муниципальными финансами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3610000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3610000000', 'Подпрограмма "Совершенствование системы распределения и перераспределения финансовых ресурсов между уровнями бюджетной системы Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3610100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3610100000', 'Основное мероприятие "Актуализация форм и механизмов предоставления межбюджетных трансфертов бюджетам субъектов Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3610200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3610200000', 'Основное мероприятие "Повышение эффективности предоставления нецелевых межбюджетных трансфертов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3610300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3610300000', 'Основное мероприятие "Повышение эффективности предоставления и использования межбюджетных субсидий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3610400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3610400000', 'Основное мероприятие "Повышение эффективности предоставления и использования субвенций"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3610459000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3610459000', 'Единая субвенция бюджетам субъектов Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3610500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3610500000', 'Основное мероприятие "Актуализация распределения доходных источников между уровнями бюджетной системы Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3620000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3620000000', 'Подпрограмма "Выравнивание финансовых возможностей бюджетов субъектов Российской Федерации и местных бюджетов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3620100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3620100000', 'Основное мероприятие "Выравнивание бюджетной обеспеченности субъектов Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3620150010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3620150010', 'Дотации на выравнивание бюджетной обеспеченности субъектов Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3620200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3620200000', 'Основное мероприятие "Поддержка мер по обеспечению сбалансированности бюджетов субъектов Российской Федерации и муниципальных образований и компенсация дополнительных расходов, возникших в результате решений, принятых органами власти другого уровня"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3620300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3620300000', 'Основное мероприятие "Предоставление дополнительной финансовой помощи в виде бюджетных кредитов бюджетам субъектов Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3620350020') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3620350020', 'Дотации на поддержку мер по обеспечению сбалансированности бюджетов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3620350060') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3620350060', 'Дотация в целях обеспечения сбалансированности бюджета Чеченской Республики')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3620350070') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3620350070', 'Дотация в целях обеспечения сбалансированности бюджета Омской области')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3620350090') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3620350090', 'Дотации на частичную компенсацию дополнительных расходов на повышение оплаты труда работников бюджетной сферы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3620351250') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3620351250', 'Дотации бюджету Приморского края в целях обеспечения сбалансированности бюджета городского округа Большой Камень')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3620351400') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3620351400', 'Дотации бюджету Мурманской области в целях обеспечения сбалансированности бюджета городского округа Мурманск')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3620354090') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3620354090', 'Дотация в целях обеспечения сбалансированности бюджета Республики Крым')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3620354100') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3620354100', 'Дотация в целях обеспечения сбалансированности бюджета города федерального значения Севастополя')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3620400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3620400000', 'Основное мероприятие "Создание условий для устойчивого исполнения бюджетов закрытых административно-территориальных образований"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3620450100') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3620450100', 'Дотации, связанные с особым режимом безопасного функционирования закрытых административно-территориальных образований')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3630000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3630000000', 'Подпрограмма "Содействие повышению качества управления региональными и муниципальными финансами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3630100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3630100000', 'Основное мероприятие "Поддержка реализации региональных программ повышения эффективности бюджетных расходов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3630200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3630200000', 'Основное мероприятие "Оценка качества управления региональными и муниципальными финансами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3630300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3630300000', 'Основное мероприятие "Использование мер ограничительного и стимулирующего характера, направленных на повышение качества управления региональными и муниципальными финансами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3630400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3630400000', 'Основное мероприятие "Методическая поддержка реализации мероприятий по повышению качества управления государственными финансами субъектов Российской Федерации и муниципальными финансами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3640000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3640000000', 'Подпрограмма "Совершенствование системы разграничения расходных полномочий между федеральными органами исполнительной власти, органами государственной власти субъектов Российской Федерации и органами местного самоуправления"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3640100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3640100000', 'Основное мероприятие "Создание и обеспечение ведения единого реестра публичных полномочий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3640200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3640200000', 'Основное мероприятие "Совершенствование правовой и методической базы для осуществления переданных субъектам Российской Федерации полномочий и организации эффективного контроля за осуществлением переданных субъектам Российской Федерации полномочий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3640300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3640300000', 'Основное мероприятие "Разработка механизма оценки проектов нормативных правовых актов, влияющих на развитие федеративных отношений и местного самоуправления"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3640400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3640400000', 'Основное мероприятие "Участие в рамках положений Конституции Российской Федерации в законодательной деятельности, осуществляемой на уровне Российской Федерации по вопросам совершенствования федеративных отношений и разграничения полномочий между уров')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3640500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3640500000', 'Основное мероприятие "Создание условий для эффективного осуществления органами местного самоуправления возложенных на них полномочий"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3700000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3700000000', 'Государственная программа Российской Федерации "Социально-экономическое развитие Калининградской области до 2020 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3730000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3730000000', 'Подпрограмма "Обеспечение реализации государственной программы Российской Федерации "Социально-экономическое развитие Калининградской области до 2020 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3730100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3730100000', 'Основное мероприятие "Развитие нормативной правовой базы и формирование стратегических документов по вопросам развития Калининградской области"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3730200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3730200000', 'Основное мероприятие "Нормативно-методическое и организационно-аналитическое сопровождение реализации государственной программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3740000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3740000000', 'Федеральная целевая программа развития Калининградской области на период до 2020 года')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3740050990') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3740050990', 'Субсидии на реализацию мероприятий федеральной целевой программы развития Калининградской области на период до 2020 года')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3800000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3800000000', 'Государственная программа Российской Федерации "Управление федеральным имуществом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3810000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3810000000', 'Подпрограмма "Повышение эффективности управления федеральным имуществом и приватизации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3810100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3810100000', 'Основное мероприятие "Определение целевой функции управления объектами федерального имущества"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3810200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3810200000', 'Основное мероприятие "Управление отчуждением объектов федерального имущества"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3810300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3810300000', 'Основное мероприятие "Управление развитием объектов федерального имущества"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3810400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3810400000', 'Основное мероприятие "Управление рисками в сфере реализации процессов управления федеральным имуществом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3810500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3810500000', 'Основное мероприятие "Совершенствование учета и мониторинга использования федерального имущества"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3810600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3810600000', 'Основное мероприятие "Обеспечение реализации подпрограммы"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3820000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3820000000', 'Подпрограмма "Управление государственным материальным резервом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3820100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3820100000', 'Основное мероприятие "Формирование запасов государственного материального резерва"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3820200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3820200000', 'Основное мероприятие "Обеспечение функционирования управления в сфере государственного материального резерва"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3820300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3820300000', 'Основное мероприятие "Развитие инфраструктуры системы государственного материального резерва"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3900000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3900000000', 'Государственная программа Российской Федерации "Управление государственными финансами и регулирование финансовых рынков"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3910000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3910000000', 'Подпрограмма "Обеспечение сбалансированности федерального бюджета и повышение эффективности бюджетных расходов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3910100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3910100000', 'Основное мероприятие "Внедрение долгосрочного бюджетного планирования в Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3910200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3910200000', 'Основное мероприятие "Развитие программно-целевых методов планирования и повышение эффективности бюджетных расходов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3910300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3910300000', 'Основное мероприятие "Развитие нормативно-правового и методического обеспечения оказания государственных (муниципальных) услуг"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3910400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3910400000', 'Основное мероприятие "Совершенствование системы материальной мотивации федеральных государственных гражданских  служащих и лиц, замещающих государственные должности Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3910500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3910500000', 'Основное мероприятие "Совершенствование механизмов финансового обеспечения социальной поддержки населения"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3910600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3910600000', 'Основное мероприятие "Совершенствование регулирования вопросов деятельности государственных внебюджетных фондов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3920000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3920000000', 'Подпрограмма "Нормативно-методическое обеспечение и организация бюджетного процесса"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3920100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3920100000', 'Основное мероприятие "Совершенствование бюджетного законодательства "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3920200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3920200000', 'Основное мероприятие "Нормативное правовое регулирование и организационно-методическое обеспечение бюджетного процесса на федеральном уровне"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3920300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3920300000', 'Основное мероприятие "Формирование и исполнение федерального бюджета"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3920400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3920400000', 'Основное мероприятие "Кассовое обслуживание исполнения бюджетов бюджетной системы Российской Федерации, учет операций со средствами неучастников бюджетного процесса и формирование бюджетной отчетности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3920500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3920500000', 'Основное мероприятие "Управление резервными средствами федерального бюджета"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3920520540') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3920520540', 'Резервный фонд Правительства Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3920520550') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3920520550', 'Резервный фонд Президента Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3920600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3920600000', 'Основное мероприятие "Обеспечение защиты интересов Российской Федерации в судебных разбирательствах на территории Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3920700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3920700000', 'Основное мероприятие "Повышение качества финансового менеджмента главных администраторов средств федерального бюджета"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3930000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3930000000', 'Подпрограмма "Организация и осуществление контроля и надзора в финансово-бюджетной сфере"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3930100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3930100000', 'Основное мероприятие "Нормативное правовое регулирование и методическое обеспечение по вопросам контроля и надзора в финансово-бюджетной сфере"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3930200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3930200000', 'Основное мероприятие "Осуществление внутреннего государственного (муниципального) финансового контроля"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3930300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3930300000', 'Основное мероприятие "Анализ осуществления главными администраторами средств федерального бюджета внутреннего финансового контроля и внутреннего финансового аудита"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3930400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3930400000', 'Основное мероприятие "Обеспечение реализации подпрограммы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3930500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3930500000', 'Основное мероприятие "Организация и осуществление контрольно-надзорной деятельности в сфере валютных правоотношений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3930600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3930600000', 'Основное мероприятие "Организация и осуществление внешнего контроля качества работы аудиторских организаций, проводящих обязательный аудит бухгалтерской (финансовой) отчетности организаций, определенных действующим законодательством"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3930700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3930700000', 'Основное мероприятие "Развитие информационной инфраструктуры Росфиннадзора и его территориальных органов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3940000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3940000000', 'Подпрограмма "Обеспечение функционирования и развитие налоговой системы Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3940100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3940100000', 'Основное мероприятие "Развитие налогового и таможенного законодательства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3940200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3940200000', 'Основное мероприятие "Совершенствование налогового администрирования"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3940220350') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3940220350', 'Реализация мероприятий, связанных с процедурами банкротства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3940220360') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3940220360', 'Мероприятия, связанные с распоряжением и реализацией выморочного имущества')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3940300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3940300000', 'Основное мероприятие "Разработка основных направлений налоговой политики на очередной финансовый год и плановый период"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3940400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3940400000', 'Основное мероприятие "Развитие электронного документооборота между налоговыми органами и налогоплательщиками,  повышение качества исполнения налоговых процедур и информирования налогоплательщиков"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3940500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3940500000', 'Основное мероприятие "Деофшоризация национальной экономики"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3940600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3940600000', 'Основное мероприятие "Взаимодействие с Организацией экономического сотрудничества и развития в рамках реализации плана мероприятий по противодействию размыванию налогооблагаемой базы и выводу прибыли из-под налогообложения (BEPS)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3950000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3950000000', 'Подпрограмма "Управление государственным долгом и государственными финансовыми активами Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3950100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3950100000', 'Основное мероприятие "Нормативное правовое регулирование в сфере управления государственным долгом и государственными финансовыми активами Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3950200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3950200000', 'Основное мероприятие "Обеспечение своевременности и полноты исполнения долговых обязательств Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3950227880') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3950227880', 'Процентные платежи по государственному долгу Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3950300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3950300000', 'Основное мероприятие "Управление государственным долгом, выраженным в ценных бумагах"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3950400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3950400000', 'Основное мероприятие "Оказание государственной гарантийной поддержки национальной промышленности, реализации инвестиционных проектов (в том числе региональных), экспорта, развития малого и среднего предпринимательства, выполнения гособоронзаказа"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3950420560') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3950420560', 'Государственные гарантии Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3950500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3950500000', 'Основное мероприятие "Взаимодействие с международными рейтинговыми агентствами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3950600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3950600000', 'Основное мероприятие "Обеспечение эффективного диалога с участниками национального и международного рынков капитала"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3950700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3950700000', 'Основное мероприятие "Выполнение обязательств по выплате вознаграждений агентам и консультантам "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3950720370') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3950720370', 'Выполнение других обязательств государства по выплате агентских комиссий и вознаграждения')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3950800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3950800000', 'Основное мероприятие "Обеспечение реализации межправительственных соглашений об урегулировании (погашении) задолженности Российской Федерации и бывшего СССР перед иностранными государствами-кредиторами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3950900000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3950900000', 'Основное мероприятие "Обеспечение защиты интересов Российской Федерации в международных судебных и иных юридических спорах, касающихся финансовых претензий к Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3951000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3951000000', 'Основное мероприятие "Обеспечение реализации соглашений Российской Федерации с правительствами иностранных государств-заёмщиками"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3951100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3951100000', 'Основное мероприятие "Управление средствами суверенных фондов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3951200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3951200000', 'Основное мероприятие "Нормативное правовое регулирование и мониторинг состояния государственного долга субъектов Российской Федерации и муниципального долга, обеспечение допуска на национальный долговой рынок финансово-устойчивых эмитентов государств')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3960000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3960000000', 'Подпрограмма "Развитие международного финансово-экономического сотрудничества Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3960100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3960100000', 'Основное мероприятие "Подготовка и аналитическое обеспечение участия Российской Федерации в международных мероприятиях и инициативах в финансово-экономической сфере"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3960200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3960200000', 'Основное мероприятие "Обеспечение реализации политики Российской Федерации в сфере международных финансово-экономических отношений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3960300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3960300000', 'Основное мероприятие "Координация подготовки и реализации проектов, осуществляемых в Российской Федерации при участии международных финансовых организаций"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3970000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3970000000', 'Подпрограмма "Создание и развитие государственной интегрированной информационной системы управления общественными финансами "Электронный бюджет"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3970100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3970100000', 'Основное мероприятие "Автоматизация учетной деятельности, переход на юридически значимый электронный документооборот в сфере управления общественными финансами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3970200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3970200000', 'Основное мероприятие "Создание централизованных или "облачных" технологий хранения и обработки информации, обеспечивающих необходимый уровень отказоустойчивости и катастрофоустойчивости"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3970300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3970300000', 'Основное мероприятие "Сопровождение и обеспечение текущих процессов составления и исполнения федерального бюджета, ведения бухгалтерского и управленческого учета и формирования отчетности "')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3970400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3970400000', 'Основное мероприятие "Обеспечение взаимосвязи всех видов учета и отчетности публично-правовых образований, интеграция процессов управления деятельностью публично-правовых образований в сфере управления общественными финансами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3970500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3970500000', 'Основное мероприятие "Создание и развитие Единого портала бюджетной системы Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3980000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3980000000', 'Подпрограмма "Государственное регулирование отрасли драгоценных металлов и драгоценных камней"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3980100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3980100000', 'Основное мероприятие "Выработка и совершенствование государственной политики и нормативное правовое регулирование в сфере добычи, производства, переработки, использования и обращения драгоценных металлов и драгоценных камней"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3980200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3980200000', 'Основное мероприятие "Организация формирования Государственного фонда драгоценных металлов и драгоценных камней Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3980230690') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3980230690', 'Осуществление ежемесячной денежной выплаты ветеранам')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3980300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3980300000', 'Основное мероприятие "Обеспечение осуществления федерального пробирного надзора, в том числе опробования и клеймения государственным пробирным клеймом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3990000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3990000000', 'Подпрограмма "Государственное регулирование в сфере производства и оборота этилового спирта, алкогольной и спиртосодержащей продукции"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3990100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3990100000', 'Основное мероприятие "Обеспечение реализации подпрограммы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3990200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3990200000', 'Основное мероприятие "Совершенствование нормативной правовой базы в сфере производства и оборота этилового спирта, алкогольной и спиртосодержащей продукции"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='3990300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('3990300000', 'Основное мероприятие "Совершенствование государственного контроля и надзора за производством, оборотом, качеством и безопасностью этилового спирта, алкогольной и спиртосодержащей продукции"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='39Б0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('39Б0000000', 'Подпрограмма "Эффективное функционирование финансовых рынков, банковской, страховой деятельности, схем инвестирования и защиты пенсионных накоплений"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='39Б0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('39Б0100000', 'Основное мероприятие "Развитие финансовых рынков, создание международного финансового центра"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='39Б0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('39Б0200000', 'Основное мероприятие "Регулирование банковской деятельности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='39Б0300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('39Б0300000', 'Основное мероприятие "Регулирование страховой деятельности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='39Б0400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('39Б0400000', 'Основное мероприятие "Регулирование обязательных пенсионных накоплений, деятельности негосударственных пенсионных фондов и размещения активов институтов развития"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='39Б0500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('39Б0500000', 'Основное мероприятие "Совершенствование валютного законодательства Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='39Б0600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('39Б0600000', 'Основное мероприятие "Защита прав инвесторов и потребителей финансовых услуг"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='39Б0620370') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('39Б0620370', 'Выполнение других обязательств государства по выплате агентских комиссий и вознаграждения')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='39Б0700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('39Б0700000', 'Основное мероприятие "Развитие правовой базы бухгалтерского учета и обеспечение применения международных стандартов финансовой отчетности на территории Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='39Б0800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('39Б0800000', 'Основное мероприятие "Развитие правовой базы аудиторской деятельности и создание нормативно-методологических основ применения международных стандартов аудита на территории Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='39Б0900000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('39Б0900000', 'Основное мероприятие "Осуществление государственного контроля (надзора) за деятельностью саморегулируемых организаций аудиторов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='39В0000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('39В0000000', 'Подпрограмма "Обеспечение открытости и прозрачности управления общественными финансами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='39В0100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('39В0100000', 'Основное мероприятие "Повышение открытости и доступности информации о деятельности публично-правовых образований в сфере управления общественными финансами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='39В0200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('39В0200000', 'Основное мероприятие "Формирование и публикация в открытых источниках "Бюджета для граждан"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='39В0300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('39В0300000', 'Основное мероприятие "Повышение информационной открытости деятельности исполнителей государственной программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4100000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4100000000', 'Государственная программа Российской Федерации "Внешнеполитическая деятельность"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4110000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4110000000', 'Подпрограмма "Осуществление функций по выработке и реализации государственной политики и нормативно-правовому регулированию в сфере международных отношений Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4110100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4110100000', 'Основное мероприятие "Демаркация и делимитация Государственной границы Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4110200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4110200000', 'Основное мероприятие "Восстановление, ремонт, благоустройство и уход за российскими (советскими) воинскими захоронениями за рубежом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4110300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4110300000', 'Основное мероприятие "Выполнение международных обязательств по обеспечению деятельности Бюро ЮНЕСКО в г. Москве"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4110400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4110400000', 'Основное мероприятие "Обеспечение участия Российской Федерации в деятельности международных организаций"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4110500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4110500000', 'Основное мероприятие "Поддержка соотечественников, проживающих за рубежом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4110562150') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4110562150', 'Государственная поддержка отдельных некоммерческих организаций, осуществляющих защиту прав соотечественников, проживающих за рубежом')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4110599999') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4110599999', 'Реализация направлений расходов подпрограммы государственной программы Российской Федерации, федеральной целевой программы в рамках государственной программы Российской Федерации, а также непрограммных направлений расходов федеральных государственных')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4110600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4110600000', 'Основное мероприятие "Обеспечение защиты прав Российской Федерации на дипломатическое недвижимое имущество за рубежом"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4110700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4110700000', 'Основное мероприятие "Участие воинских формирований Вооруженных Сил Российской Федерации в деятельности по поддержанию международного мира и безопасности"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4110800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4110800000', 'Основное мероприятие "Оказание гуманитарной помощи иностранным государствам"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4110827840') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4110827840', 'Доставка грузов гуманитарного характера и эвакуация российских граждан')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4110827900') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4110827900', 'Гуманитарная финансовая помощь другим государствам')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4110900000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4110900000', 'Основное мероприятие "Государственная поддержка отдельных некоммерческих организаций в сфере международного сотрудничества"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4111000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4111000000', 'Основное мероприятие "Оказание финансовой помощи Республике Южная Осетия"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4111027910') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4111027910', 'Оказание финансовой помощи в целях социально-экономического развития Республики Южная Осетия')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4111027930') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4111027930', 'Оказание финансовой помощи в целях осуществления бюджетных инвестиций Республике Южная Осетия')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4111100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4111100000', 'Основное мероприятие "Оказание финансовой помощи Республике Абхазия"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4111127920') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4111127920', 'Оказание финансовой помощи в целях социально-экономического развития Республики Абхазия')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4111127990') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4111127990', 'Оказание финансовой помощи в целях осуществления бюджетных инвестиций Республике Абхазия')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4111200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4111200000', 'Основное мероприятие "Обеспечение реализации подпрограммы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4111240010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4111240010', 'Строительство объектов за пределами территории Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4111300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4111300000', 'Основное мероприятие "Военно-техническое сотрудничество с иностранными государствами"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4120000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4120000000', 'Подпрограмма "Выполнение финансовых обязательств Российской Федерации по обеспечению деятельности межгосударственных структур, созданных государствами Содружества Независимых Государств"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4120100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4120100000', 'Основное мероприятие "Обеспечение долевого участия Российской Федерации в содержании межгосударственных структур, созданных государствами Содружества Независимых Государств"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4120200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4120200000', 'Основное мероприятие "Обеспечение долевого участия Российской Федерации в финансировании совместных мероприятий, проводимых государствами Содружества Независимых Государств"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4120300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4120300000', 'Основное мероприятие "Обеспечение долевого участия Российской Федерации в формировании бюджета Союзного государства"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4120320500') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4120320500', 'Долевой взнос в бюджет Союзного государства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4120400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4120400000', 'Основное мероприятие "Обеспечение долевого участия Российской Федерации в Организации Договора о коллективной безопасности"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4130000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4130000000', 'Подпрограмма "Осуществление деятельности в сферах международного гуманитарного сотрудничества и содействия международному развитию"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4130100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4130100000', 'Основное мероприятие "Продвижение российских науки, культуры и образования в зарубежных странах"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4130200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4130200000', 'Основное мероприятие "Распространение и укрепление позиций русского языка в мире"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4130262340') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4130262340', 'Обеспечение деятельности фонда "Русский мир"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4130300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4130300000', 'Основное мероприятие "Развитие публичной дипломатии и гуманитарных связей с государственными и негосударственными структурами иностранных государств, международными и региональными организациями"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4130400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4130400000', 'Основное мероприятие "Содействие развитию международных связей субъектов Российской Федерации и муниципальных образований"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4130500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4130500000', 'Основное мероприятие "Развитие региональной и субрегиональной интеграции"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4130600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4130600000', 'Основное мероприятие "Реализация отдельных направлений в области содействия международному развитию"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4130700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4130700000', 'Основное мероприятие "Укрепление культурно-информационного и гуманитарного присутствия России в мире"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4130800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4130800000', 'Основное мероприятие "Обеспечение реализации подпрограммы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4200000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4200000000', 'Государственная программа Российской Федерации "Юстиция"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4210000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4210000000', 'Подпрограмма "Обеспечение защиты публичных интересов, реализации прав граждан и организаций"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4210100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4210100000', 'Основное мероприятие "Совершенствование нормативной правовой базы в сфере реализации подпрограммы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4210200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4210200000', 'Основное мероприятие "Аккредитация обособленных структурных подразделений иностранных юридических лиц"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4210300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4210300000', 'Основное мероприятие "Обеспечение прав физических и юридических лиц на получение информации о нормативных правовых актах Российской Федерации, на основе проведения единой научно-технической политики в области информатизации, развития государственных')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4210400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4210400000', 'Основное мероприятие "Обеспечение исполнения решений Европейского суда по правам человека"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4210420390') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4210420390', 'Денежные компенсации истцам в случае вынесения соответствующих решений Европейским Судом по правам человека')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4210462200') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4210462200', 'Обеспечение мероприятий, связанных с направлением российских юристов для участия в работе Европейского Суда по правам человека')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4210500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4210500000', 'Основное мероприятие "Обеспечение реализации переданных субъектам Российской Федерации полномочий Российской Федерации по государственной регистрации актов гражданского состояния"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4220000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4220000000', 'Подпрограмма "Развитие судебно-экспертных учреждений Министерства юстиции Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4220100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4220100000', 'Основное мероприятие "Совершенствование нормативной правовой базы в сфере реализации подпрограммы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4220200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4220200000', 'Основное мероприятие "Организация, обеспечение и совершенствование деятельности судебно-экспертных учреждений Минюста России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4220300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4220300000', 'Основное мероприятие "Укрепление международного сотрудничества судебно-экспертных учреждений Минюста России, прохождение аккредитации на соответствие международным стандартам"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4220400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4220400000', 'Основное мероприятие "Завершение мероприятий по совершенствованию статуса государственного судебного эксперта, правового положения и организации государственных судебно-экспертных учреждений Минюста России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4230000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4230000000', 'Подпрограмма "Регулирование государственной политики в сфере исполнения уголовных наказаний"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4230100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4230100000', 'Основное мероприятие "Обеспечение социальных гарантий лиц, ранее проходивших службу в уголовно-исполнительной системе"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4230130150') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4230130150', 'Пособия лицам, являвшимся сотрудниками учреждений и органов уголовно-исполнительной системы, федеральной противопожарной службы Государственной противопожарной службы, органов по контролю за оборотом наркотических средств и психотропных веществ, тамо')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4230200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4230200000', 'Основное мероприятие "Повышение эффективности управления уголовно-исполнительной системой, использование инновационных разработок и научного потенциала"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4230300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4230300000', 'Основное мероприятие "Повышение социального статуса сотрудников уголовно-исполнительной системы, престижа службы в исправительных учреждениях"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4230400000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4230400000', 'Основное мероприятие "Развитие международного сотрудничества с пенитенциарными системами иностранных государств, международными органами и неправительственными организациями"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4230500000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4230500000', 'Основное мероприятие "Проведение социальной, психологической, воспитательной и образовательной работы с осужденными"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4230600000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4230600000', 'Основное мероприятие "Развитие системы наказаний, альтернативных лишению свободы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4230700000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4230700000', 'Основное мероприятие "Обеспечение постпенитенциарной адаптации осужденных, предотвращение рецидива преступлений"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4230735950') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4230735950', 'Обеспечение осужденных, освобождаемых от принудительных работ, ареста или лишения свободы на определенный срок, бесплатным проездом к месту жительства, продуктами питания или деньгами на время проезда')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4230800000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4230800000', 'Основное мероприятие "Обеспечение соблюдения международных стандартов обращения с осужденными в местах лишения свободы и лицами, содержащимися под стражей"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4230835950') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4230835950', 'Обеспечение осужденных, освобождаемых от принудительных работ, ареста или лишения свободы на определенный срок, бесплатным проездом к месту жительства, продуктами питания или деньгами на время проезда')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4240000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4240000000', 'Подпрограмма "Повышение качества принудительного исполнения судебных актов, актов других органов и должностных лиц и обеспечение установленного порядка деятельности судов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4240100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4240100000', 'Основное мероприятие "Организация и обеспечение принудительного исполнения судебных актов, актов других органов и должностных лиц, а также установленного порядка деятельности судов"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4240200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4240200000', 'Основное мероприятие "Модернизация системы принудительного исполнения судебных актов, актов других органов и должностных лиц"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4240300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4240300000', 'Основное мероприятие "Совершенствование нормативной правовой базы в сфере реализации подпрограммы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4250000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4250000000', 'Подпрограмма "Повышение эффективности государственного управления при реализации государственной программы Российской Федерации "Юстиция"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4250100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4250100000', 'Основное мероприятие "Координация и управление реализацией государственной программы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4250200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4250200000', 'Основное мероприятие "Обеспечение выполнения государственных функций"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4250300000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4250300000', 'Основное мероприятие "Организация взаимодействия с Гаагской конференцией по международному частному праву"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4260000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4260000000', 'Федеральная целевая программа "Развитие уголовно-исполнительной системы (2007 - 2016 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4300000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4300000000', 'Государственная программа Российской Федерации "Социально-экономическое развитие Арктической зоны Российской Федерации на период до 2020 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4310000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4310000000', 'Подпрограмма "Координация деятельности органов государственной власти в сфере социально-экономического развития Арктической зоны Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4310100000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4310100000', 'Основное мероприятие "Координация деятельности федеральных и региональных органов исполнительной власти в части повышения эффективности реализации иных государственных программ Российской Федерации и программ субъектов Российской Федерации на террито')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='4310200000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('4310200000', 'Основное мероприятие "Внедрение механизмов мониторинга и комплексного анализа состояния и перспектив развития ключевых направлений экономики в Арктической зоне Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7100000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7100000000', 'Развитие пенсионной системы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7100030010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7100030010', 'Пенсии военнослужащим, членам их семей и лицам, приравненным к ним по пенсионному обеспечению, а также пособия и иные выплаты в рамках пенсионного обеспечения')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7100030560') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7100030560', 'Материальное обеспечение специалистов ядерного оружейного комплекса Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7100030600') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7100030600', 'Выплата пенсий по государственному пенсионному обеспечению')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7100030610') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7100030610', 'Выплата доплат к пенсиям')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7100031070') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7100031070', 'Выплата пенсии некоторым категориям граждан Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7100051830') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7100051830', 'Валоризация величины расчетного пенсионного капитала')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7100051840') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7100051840', 'Возмещение расходов по выплате страховых пенсий в связи с зачетом в страховой стаж нестраховых периодов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7100051850') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7100051850', 'Софинансирование формирования пенсионных накоплений застрахованных лиц за счет средств Фонда национального благосостояния')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7100051860') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7100051860', 'Компенсация выпадающих доходов бюджету Пенсионного фонда Российской Федерации в связи с установлением пониженных тарифов страховых взносов на обязательное пенсионное страхование')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7100052060') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7100052060', 'Межбюджетные трансферты на обязательное пенсионное страхование')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7300000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7300000000', 'Непрограммные направления деятельности органов управления государственных внебюджетных фондов Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7310000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7310000000', 'Реализация государственных функций в области социальной политики')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7310020900') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7310020900', 'Обеспечение ведения специальной части индивидуальных лицевых счетов застрахованных лиц')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7310035810') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7310035810', 'Гарантийные взносы в фонд гарантирования пенсионных накоплений, уплачиваемые Пенсионным фондом Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7310035820') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7310035820', 'Передача средств пенсионных накоплений в негосударственные пенсионные фонды')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7310052090') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7310052090', 'Софинансирование социальных программ субъектов Российской Федерации, связанных с укреплением материально-технической базы учреждений социального обслуживания населения, оказанием адресной социальной помощи неработающим пенсионерам, обучением компьюте')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7320000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7320000000', 'Выполнение функций аппаратами государственных внебюджетных фондов Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7350000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7350000000', 'Международное сотрудничество')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7360000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7360000000', 'Строительство объектов социального и производственного комплексов, в том числе объектов общегражданского назначения, жилья, инфраструктуры')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370000000', 'Социальные выплаты')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030090') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030090', 'Социальная поддержка Героев Советского Союза, Героев Российской Федерации и полных кавалеров ордена Славы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030190') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030190', 'Выплата дополнительного материального обеспечения, доплат к пенсиям, пособий и компенсаций')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030350') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030350', 'Дополнительное ежемесячное материальное обеспечение некоторых категорий граждан Российской Федерации в связи с 60-летием Победы в Великой Отечественной войне 1941 - 1945 годов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030360') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030360', 'Дополнительное ежемесячное материальное обеспечение инвалидов вследствие военной травмы в соответствии с Указом Президента Российской Федерации от 1 августа 2005 года № 887 "О мерах по улучшению материального положения инвалидов вследствие военной тр')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030390') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030390', 'Компенсационные выплаты лицам, осуществляющим уход за нетрудоспособными гражданами')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030560') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030560', 'Материальное обеспечение специалистов ядерного оружейного комплекса Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030570') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030570', 'Выплата федеральной социальной доплаты к пенсии')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030580') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030580', 'Выплата страховой пенсии')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030590') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030590', 'Выплата накопительной части трудовой пенсии')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030600') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030600', 'Выплата пенсий по государственному пенсионному обеспечению')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030610') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030610', 'Выплата доплат к пенсиям')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030620') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030620', 'Доплата к пенсии членам летных экипажей воздушных судов гражданской авиации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030630') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030630', 'Единовременная выплата средств пенсионных накоплений')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030640') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030640', 'Срочная пенсионная выплата')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030650') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030650', 'Выплата пенсий, назначенных досрочно гражданам, признанным безработными')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030660') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030660', 'Доплаты к пенсии работникам организаций угольной промышленности')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030670') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030670', 'Осуществление ежемесячной денежной выплаты гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подве')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030680') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030680', 'Осуществление ежемесячной денежной выплаты инвалидам')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030690') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030690', 'Осуществление ежемесячной денежной выплаты ветеранам')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030700') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030700', 'Осуществление ежемесячной денежной выплаты гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Федеральным законом от 10 января 2002 года № 2-ФЗ "О социальных гарантиях гражданам, подвергш')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030710') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030710', 'Осуществление ежемесячной денежной выплаты гражданам, подвергшимся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Федеральным законом от 26 ноября 1998 года № 175-ФЗ "О социальной защите граждан Российской Ф')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030720') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030720', 'Осуществление ежемесячной денежной выплаты Героям Советского Союза, Героям Российской Федерации и полным кавалерам ордена Славы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030730') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030730', 'Осуществление ежемесячной денежной выплаты Героям Социалистического Труда, Героям Труда Российской Федерации и полным кавалерам ордена Трудовой Славы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030740') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030740', 'Выплата социального пособия на погребение и оказание услуг по погребению согласно гарантированному перечню этих услуг за умерших, получавших пенсии по государственному пенсионному обеспечению')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030750') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030750', 'Выплата социального пособия на погребение и оказание услуг по погребению согласно гарантированному перечню этих услуг за умерших, получавших страховую пенсию')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030760') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030760', 'Выплата социального пособия на погребение умерших неработавших пенсионеров, досрочно оформивших пенсию по предложению органов службы занятости, и оказание услуг по погребению согласно гарантированному перечню этих услуг')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030770') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030770', 'Единовременная выплата отдельным категориям граждан в связи с празднованием 65-летия Победы в Великой Отечественной войне')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030780') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030780', 'Единовременная выплата некоторым категориям граждан Российской Федерации в связи с 67-летием Победы в Великой Отечественной войне 1941 - 1945 годов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370030790') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370030790', 'Предоставление материнского (семейного) капитала')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370031030') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370031030', 'Ежемесячные выплаты лицам, осуществляющим уход за детьми-инвалидами и инвалидами с детства I группы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370031070') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370031070', 'Выплата пенсии некоторым категориям граждан Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370031150') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370031150', 'Компенсация расходов, связанных с переездом из районов Крайнего Севера и приравненных к ним местностей в другую местность на территории Российской Федерации в соответствии с законодательством Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370031160') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370031160', 'Осуществление пенсионного обеспечения отдельных категорий граждан Российской Федерации, проживающих на территориях Республики Крым и города федерального значения Севастополя')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370031170') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370031170', 'Единовременная выплата некоторым категориям граждан Российской Федерации в связи с 70-летием Победы в Великой Отечественной войне 1941 - 1945 годов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370039500') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370039500', 'Выплаты правопреемникам умерших застрахованных лиц')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370039510') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370039510', 'Выплата пенсий, назначенных Эстонской Республикой')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370039520') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370039520', 'Выплата пенсий и иных социальных выплат, назначенных Латвийской Республикой')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370039530') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370039530', 'Выплата пенсий и иных социальных выплат, назначенных Республикой Беларусь')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370039540') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370039540', 'Выплата пенсий и иных социальных выплат, назначенных Республикой Болгария')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370039550') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370039550', 'Выплата пенсий, назначенных Литовской Республикой')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370039730') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370039730', 'Направление средств материнского (семейного) капитала, ранее направленных на формирование накопительной части трудовой пенсии, на улучшение жилищных условий и получение образования ребенком (детьми)')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370051980') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370051980', 'Социальная поддержка Героев Социалистического Труда, Героев Труда Российской Федерации и полных кавалеров ордена Трудовой Славы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7370051990') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7370051990', 'Оплата стоимости проезда пенсионерам к месту отдыха и обратно один раз в два года')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7380000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7380000000', 'Иные мероприятия')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7380054000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7380054000', 'Дотация на сбалансированность, передаваемая федеральному бюджету из бюджета Федерального фонда обязательного медицинского страхования')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7700000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7700000000', 'Обеспечение функционирования Президента Российской Федерации и его администрации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7710000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7710000000', 'Президент Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7720000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7720000000', 'Администрация Президента Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7800000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7800000000', 'Обеспечение функционирования Председателя Правительства Российской Федерации и его заместителей, Аппарата Правительства Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7810000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7810000000', 'Председатель Правительства Российской Федерации и его заместители')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='7820000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('7820000000', 'Аппарат Правительства Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8800000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8800000000', 'Следственный комитет Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8890000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8890000000', 'Обеспечение функционирования СК России')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8890030010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8890030010', 'Пенсии военнослужащим, членам их семей и лицам, приравненным к ним по пенсионному обеспечению, а также пособия и иные выплаты в рамках пенсионного обеспечения')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8890030040') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8890030040', 'Компенсация в возмещение вреда гражданам, подвергшимся воздействию радиации вследствие радиационных аварий, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию радиации всл')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8890030220') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8890030220', 'Компенсации лицам, являвшимся сотрудниками Следственного комитета Российской Федерации, утратившим возможность заниматься профессиональной деятельностью, и членам семей погибших (умерших) сотрудников Следственного комитета Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8890030340') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8890030340', 'Ежемесячная доплата к пенсиям отдельным категориям пенсионеров в соответствии с Указом Президента Российской Федерации от 18 февраля 2005 года № 176 "Об установлении ежемесячной доплаты к пенсиям отдельным категориям пенсионеров"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8890030360') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8890030360', 'Дополнительное ежемесячное материальное обеспечение инвалидов вследствие военной травмы в соответствии с Указом Президента Российской Федерации от 1 августа 2005 года № 887 "О мерах по улучшению материального положения инвалидов вследствие военной тр')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8890030450') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8890030450', 'Пособие детям погибших (умерших) или пропавших без вести в связи с исполнением служебных обязанностей сотрудников следственных органов Следственного комитета Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8890039770') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8890039770', 'Приобретение путевок в организации отдыха и оздоровления детей на территории Российской Федерации или выплата денежной компенсации взамен путевок')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8890039810') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8890039810', 'Пособия и компенсации военнослужащим, приравненным к ним лицам, а также уволенным из их числа (за исключением публичных нормативных обязательств)')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8900000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8900000000', 'Обеспечение деятельности отдельных федеральных государственных органов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8920000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8920000000', 'Обеспечение визитов делегаций высших органов власти за рубеж')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8930000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8930000000', 'Общественная палата Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8990000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8990000000', 'Управление делами Президента Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8990030330') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8990030330', 'Государственные премии Российской Федерации в области науки и техники, образования и культуры в соответствии с Указом Президента Российской Федерации от 21 июня 2004 года № 785 "О совершенствовании системы государственного премирования за достижения')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8990030370') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8990030370', 'Государственная премия Российской Федерации за выдающиеся достижения в области гуманитарной деятельности')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8990030400') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8990030400', 'Премия Президента Российской Федерации в области науки и инноваций для молодых ученых')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8990030430') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8990030430', 'Премии Президента Российской Федерации для молодых деятелей культуры')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8990031130') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8990031130', 'Премии Президента Российской Федерации в области литературы и искусства за произведения для детей и юношества')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8990040010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8990040010', 'Строительство объектов за пределами территории Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8990060500') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8990060500', 'Субсидии автономной некоммерческой организации "Аналитический центр при Правительстве Российской Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8990062160') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8990062160', 'Субсидии на поддержку некоммерческих неправительственных организаций, участвующих в развитии институтов гражданского общества')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8990062220') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8990062220', 'Субсидии центрам исторического наследия президентов Российской Федерации, прекративших исполнение своих полномочий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8990064060') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8990064060', 'Субсидии организациям на возмещение расходов по обеспечению содержания и эксплуатации объектов федерального недвижимого имущества, расположенного за пределами территории Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='8990064090') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('8990064090', 'Субсидии федеральным государственным унитарным предприятиям, находящимся в ведении Управления делами Президента Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9000000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9000000000', 'Государственная судебная власть')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9010000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9010000000', 'Председатель Конституционного Суда Российской Федерации и судьи Конституционного Суда Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9020000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9020000000', 'Председатель Верховного Суда Российской Федерации и судьи Верховного Суда Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9040000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9040000000', 'Судьи')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9050000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9050000000', 'Судебный департамент при Верховном Суде Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9060000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9060000000', 'Аппараты судов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9090000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9090000000', 'Реализация функций')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9090030190') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9090030190', 'Выплата дополнительного материального обеспечения, доплат к пенсиям, пособий и компенсаций')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9090030350') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9090030350', 'Дополнительное ежемесячное материальное обеспечение некоторых категорий граждан Российской Федерации в связи с 60-летием Победы в Великой Отечественной войне 1941 - 1945 годов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9090031170') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9090031170', 'Единовременная выплата некоторым категориям граждан Российской Федерации в связи с 70-летием Победы в Великой Отечественной войне 1941 - 1945 годов')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9090038950') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9090038950', 'Пожизненное содержание судей')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9090039660') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9090039660', 'Социальные гарантии судьям')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9090039860') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9090039860', 'Социальное обеспечение детей-сирот и детей, оставшихся без попечения родителей, лиц из числа детей-сирот и детей, оставшихся без попечения родителей, обучающихся по имеющим государственную аккредитацию образовательным программам среднего профессионал')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9090051200') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9090051200', 'Субвенции на осуществление полномочий по составлению (изменению) списков кандидатов в присяжные заседатели федеральных судов общей юрисдикции в Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9100000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9100000000', 'Прокуратура Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9190000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9190000000', 'Обеспечение деятельности Прокуратуры Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9190030010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9190030010', 'Пенсии военнослужащим, членам их семей и лицам, приравненным к ним по пенсионному обеспечению, а также пособия и иные выплаты в рамках пенсионного обеспечения')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9190030040') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9190030040', 'Компенсация в возмещение вреда гражданам, подвергшимся воздействию радиации вследствие радиационных аварий, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию радиации всл')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9190030050') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9190030050', 'Меры социальной поддержки граждан, подвергшихся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Федеральным законом от 10 января 2002 года № 2-ФЗ "О социальных гарантиях гражданам, подвергшимся радиационному')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9190030190') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9190030190', 'Выплата дополнительного материального обеспечения, доплат к пенсиям, пособий и компенсаций')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9190030340') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9190030340', 'Ежемесячная доплата к пенсиям отдельным категориям пенсионеров в соответствии с Указом Президента Российской Федерации от 18 февраля 2005 года № 176 "Об установлении ежемесячной доплаты к пенсиям отдельным категориям пенсионеров"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9190030350') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9190030350', 'Дополнительное ежемесячное материальное обеспечение некоторых категорий граждан Российской Федерации в связи с 60-летием Победы в Великой Отечественной войне 1941 - 1945 годов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9190030360') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9190030360', 'Дополнительное ежемесячное материальное обеспечение инвалидов вследствие военной травмы в соответствии с Указом Президента Российской Федерации от 1 августа 2005 года № 887 "О мерах по улучшению материального положения инвалидов вследствие военной тр')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9190030390') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9190030390', 'Компенсационные выплаты лицам, осуществляющим уход за нетрудоспособными гражданами')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9190030410') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9190030410', 'Пособие детям погибших (пропавших без вести) работников органов прокуратуры')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9190031080') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9190031080', 'Возмещение органами прокуратуры Российской Федерации расходов на погребение')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9190039770') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9190039770', 'Приобретение путевок в организации отдыха и оздоровления детей на территории Российской Федерации или выплата денежной компенсации взамен путевок')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9190039810') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9190039810', 'Пособия и компенсации военнослужащим, приравненным к ним лицам, а также уволенным из их числа (за исключением публичных нормативных обязательств)')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9190039860') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9190039860', 'Социальное обеспечение детей-сирот и детей, оставшихся без попечения родителей, лиц из числа детей-сирот и детей, оставшихся без попечения родителей, обучающихся по имеющим государственную аккредитацию образовательным программам среднего профессионал')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9200000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9200000000', 'Уполномоченный по правам человека в Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9290000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9290000000', 'Обеспечение деятельности Уполномоченного по правам человека в Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9300000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9300000000', 'Счетная палата Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9390000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9390000000', 'Обеспечение деятельности Счетной палаты')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9400000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9400000000', 'Центральная избирательная комиссия Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9410039580') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9410039580', 'Денежное вознаграждение лицам, замещавшим государственные должности в Центральной избирательной комиссии Российской Федерации, в связи с истечением срока их полномочий')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9420000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9420000000', 'Проведение референдумов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9430000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9430000000', 'Проведение выборов Президента Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9440000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9440000000', 'Проведение выборов депутатов Государственной Думы Федерального Собрания Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9490000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9490000000', 'Обеспечение деятельности ЦИК России')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9490020700') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9490020700', 'Государственная автоматизированная система Российской Федерации "Выборы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9500000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9500000000', 'Совет Федерации Федерального Собрания Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9520000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9520000000', 'Члены Совета Федерации и их помощники')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9520051420') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9520051420', 'Иные межбюджетные трансферты на обеспечение членов Совета Федерации и их помощников в субъектах Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9590000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9590000000', 'Обеспечение деятельности Совета Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9590060820') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9590060820', 'Субсидии автономной некоммерческой организации "Редакция Телеканала Совета Федерации"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9590062440') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9590062440', 'Субсидии автономной некоммерческой организации "Редакция журнала "Российская Федерация сегодня", автономной некоммерческой организации "Парламентская газета"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9600000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9600000000', 'Государственная Дума Федерального Собрания  Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9620000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9620000000', 'Депутаты Государственной Думы и их помощники')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9620051410') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9620051410', 'Иные межбюджетные трансферты на обеспечение деятельности депутатов Государственной Думы и их помощников в избирательных округах')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9690000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9690000000', 'Обеспечение деятельности Государственной Думы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9690062440') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9690062440', 'Субсидии автономной некоммерческой организации "Редакция журнала "Российская Федерация сегодня", автономной некоммерческой организации "Парламентская газета"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9700000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9700000000', 'Государственная корреспонденция')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9790000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9790000000', 'Обеспечение доставки')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9790030020') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9790030020', 'Меры социальной поддержки граждан, подвергшихся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9790030120') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9790030120', 'Пособия лицам, являвшимся сотрудниками федеральной фельдъегерской связи, получившим телесные повреждения, исключающие для них возможность дальнейшего осуществления служебной деятельности, а также семьям и иждивенцам погибших (умерших) сотрудников фед')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9790030140') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9790030140', 'Возмещение федеральными органами исполнительной власти расходов на погребение')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9800000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9800000000', 'Главное управление специальных программ Президента Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9890000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9890000000', 'Обеспечение деятельности ГУСП')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9890030020') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9890030020', 'Меры социальной поддержки граждан, подвергшихся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9890030140') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9890030140', 'Возмещение федеральными органами исполнительной власти расходов на погребение')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9890030170') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9890030170', 'Пособия, выплаты и компенсации членам семей военнослужащих, а также лицам, уволенным с военной службы без права на пенсию')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9890030240') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9890030240', 'Пособия и компенсации членам семей погибших (умерших) военнослужащих (граждан, проходивших военные сборы, инвалидов вследствие военной травмы), а также лицам, которым установлена инвалидность вследствие военной травмы после увольнения с военной служб')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9900000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9900000000', 'Реализация функций иных федеральных органов государственной власти')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9910000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9910000000', 'Федеральная целевая программа "Развитие судебной системы России на 2013 - 2020 годы"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9910035830') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9910035830', 'Субсидии на приобретение жилых помещений работникам аппаратов судов и Судебного департамента при Верховном Суде Российской Федерации и его территориальных органов, нуждающимся в улучшении жилищных условий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9920000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9920000000', 'Федеральная целевая программа "Создание системы базирования Черноморского флота на территории Российской Федерации в 2005 - 2020 годах"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9940000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9940000000', 'Федеральная целевая программа "Промышленная утилизация вооружения и военной техники на 2011 - 2015 годы и на период до 2020 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9950000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9950000000', 'Федеральная целевая программа "Совершенствование системы комплектования должностей сержантов и солдат военнослужащими, переведенными на военную службу по контракту, и осуществление перехода к комплектованию должностей сержантов (старшин) Вооруженных')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9960000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9960000000', 'Федеральная целевая программа "Совершенствование федеральной системы разведки и контроля воздушного пространства Российской Федерации (2007 - 2015 годы)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9970000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9970000000', 'Федеральная целевая программа "Социально-экономическое развитие Республики Крым и г. Севастополя до 2020 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9970051880') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9970051880', 'Субсидии на реализацию мероприятий федеральной целевой программы "Социально-экономическое развитие Республики Крым и г. Севастополя до 2020 года"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9970067610') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9970067610', 'Имущественный взнос Российской Федерации в Государственную корпорацию по содействию разработке, производству и экспорту высокотехнологичной промышленной продукции "Ростех" на строительство и модернизацию объектов по производству электрической, теплов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9970068590') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9970068590', 'Взнос в уставный капитал открытого акционерного общества "Государственная транспортная лизинговая компания", г. Москва, в целях запуска программы по обновлению парка городского транспорта Республики Крым и г. Севастополя')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9980000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9980000000', 'Президентская программа "Уничтожение запасов хим. оружия в РФ" в рамках гос. программы РФ "Развитие пром. и пов. конкур."')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990000000') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990000000', 'Иные непрограммные мероприятия')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990020170') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990020170', 'Реализация проектов по разработке и обеспечению производства импортозамещающих комплектующих изделий и материалов для вооружений, военной и специальной техники')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990020290') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990020290', 'Мероприятия, связанные с реализацией задач по выполнению обязательств по сокращению и ограничению вооружений и военной техники, и прочие расходы в данной области')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990020760') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990020760', 'Проведение экспертизы инвестиционных проектов, реализуемых организациями оборонно-промышленного комплекса в рамках подпрограммы в области развития оборонно-промышленного комплекса Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990020800') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990020800', 'Обеспечение оказания гуманитарной помощи населению иностранных государств')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990020990') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990020990', 'Дополнительная поддержка организаций и граждан')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990027850') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990027850', 'Инспекционная деятельность и другие расходы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990030020') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990030020', 'Меры социальной поддержки граждан, подвергшихся воздействию радиации вследствие радиационных аварий и ядерных испытаний, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990030030') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990030030', 'Пособие по уходу за ребенком гражданам, подвергшимся воздействию радиации вследствие радиационных аварий, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию радиации вслед')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990030040') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990030040', 'Компенсация в возмещение вреда гражданам, подвергшимся воздействию радиации вследствие радиационных аварий, в соответствии с Законом Российской Федерации от 15 мая 1991 года № 1244-I "О социальной защите граждан, подвергшихся воздействию радиации всл')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990030140') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990030140', 'Возмещение федеральными органами исполнительной власти расходов на погребение')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990030240') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990030240', 'Пособия и компенсации членам семей погибших (умерших) военнослужащих (граждан, проходивших военные сборы, инвалидов вследствие военной травмы), а также лицам, которым установлена инвалидность вследствие военной травмы после увольнения с военной служб')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990031010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990031010', 'Стипендии для ученых, конструкторов, технологов и других инженерно-технических работников организаций - исполнителей государственного оборонного заказа за выдающиеся достижения в создании прорывных технологий и разработке современных образцов вооруже')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990031020') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990031020', 'Стипендии для специалистов и молодых (до 35 лет включительно) работников организаций - исполнителей государственного оборонного заказа за значительный вклад в создание прорывных технологий и разработку современных образцов вооружения, военной и специ')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990035800') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990035800', 'Субсидия для приобретения или строительства жилого помещения (жилых помещений), предоставляемая военнослужащим - гражданам Российской Федерации и иным лицам в соответствии с Федеральным законом от 27 мая 1998 года № 76-ФЗ "О статусе военнослужащих"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990035980') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990035980', 'Обеспечение инвалидов транспортными средствами')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990039570') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990039570', 'Обеспечение инвалидов техническими средствами реабилитации, включая изготовление и ремонт протезно-ортопедических изделий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990039820') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990039820', 'Компенсация членам семей погибших военнослужащих')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990040310') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990040310', 'Обеспечение военнослужащих федеральных органов исполнительной власти, в которых законом предусмотрена военная служба, служебными жилыми помещениями и жилыми помещениями в общежитиях')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990040320') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990040320', 'Строительство и приобретение жилых помещений для постоянного проживания военнослужащих федеральных органов исполнительной власти, в которых законом предусмотрена военная служба')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990049900') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990049900', 'Мероприятия, осуществляемые на основании отдельных решений Правительства Российской Федерации, в рамках непрограммных расходов федеральных органов исполнительной власти')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990050270') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990050270', 'Субсидии на мероприятия государственной программы Российской Федерации "Доступная среда" на 2011 - 2015 годы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990051180') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990051180', 'Субвенции на осуществление первичного воинского учета на территориях, где отсутствуют военные комиссариаты')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990051210') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990051210', 'Иные межбюджетные трансферты на финансовое обеспечение дорожной деятельности на автомобильных дорогах общего пользования Крымского федерального округа')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990051300') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990051300', 'Субвенции на обеспечение инвалидов техническими средствами реабилитации, включая изготовление и ремонт протезно-ортопедических изделий')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990051600') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990051600', 'Иные межбюджетные трансферты, передаваемые для компенсации дополнительных расходов, возникших в результате решений, принятых органами власти другого уровня')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990052030') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990052030', 'Обеспечение сбалансированности бюджета Федерального фонда обязательного медицинского страхования')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990052180') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990052180', 'Субсидии на компенсацию расходов энергосбытовой организации, осуществляющей покупку электрической энергии из энергосистем иностранных государств и у производителей, функционирующих на территории Крымского федерального округа')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990052240') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990052240', 'Иные межбюджетные трансферты на финансовое обеспечение мероприятий по временному социально-бытовому обустройству лиц, вынужденно покинувших территорию Украины и находящихся в пунктах временного размещения')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990052370') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990052370', 'Субсидии бюджетам Республики Крым и города федерального значения Севастополя на реализацию мероприятий региональных программ модернизации здравоохранения')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990052800') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990052800', 'Субвенции на выплату инвалидам компенсаций страховых премий по договорам обязательного страхования гражданской ответственности владельцев транспортных средств в соответствии с Федеральным законом от 25 апреля 2002 года № 40-ФЗ "Об обязательном страхо')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990054030') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990054030', 'Иные межбюджетные трансферты на восстановление поврежденных в результате крупномасштабного наводнения и паводка автомобильных дорог регионального и межмуниципального, местного значения и мостов в целях ликвидации последствий крупномасштабного наводне')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990054220') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990054220', 'Иные межбюджетные трансферты на компенсацию расходов, связанных с оказанием в 2014 - 2015 годах медицинскими организациями, подведомственными органам исполнительной власти субъектов Российской Федерации и органам местного самоуправления, гражданам Ук')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990060560') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990060560', 'Субсидии организациям оборонно-промышленного комплекса на возмещение затрат на уплату процентов по кредитам, привлекаемым ими в 2013 - 2015 годах для целей выполнения (реализации) федеральной целевой программы "Развитие оборонно-промышленного комплек')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990062270') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990062270', 'Субсидии Общероссийской общественно-государственной организации "Добровольное общество содействия армии, авиации и флоту России"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990062450') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990062450', 'Имущественный взнос Российской Федерации в некоммерческую организацию "Фонд перспективных исследований"')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990062470') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990062470', 'Субсидии на государственную поддержку общероссийских общественных организаций инвалидов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990062610') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990062610', 'Взнос в уставный капитал открытого акционерного общества "ЗВЕЗДА-РЕДУКТОР", г. Санкт-Петербург')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990063860') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990063860', 'Взнос в уставный капитал открытого акционерного общества "Салаватский химический завод", г. Салават, Республика Башкортостан')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990064210') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990064210', 'Субсидии казенным предприятиям оборонно-промышленного комплекса')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990064220') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990064220', 'Субсидии стратегическим организациям оборонно-промышленного комплекса в целях предупреждения банкротства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990064670') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990064670', 'Субсидии организациям оборонно-промышленного комплекса на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и государственной корпорации "Банк развития и внешнеэкономической деятельности (Внешэкон')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990064830') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990064830', 'Субсидии российским организациям - экспортерам промышленной продукции военного назначения на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государственной корпорации "Банк развития и внешн')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990064990') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990064990', 'Субсидии издательствам и издающим организациям на реализацию социально значимых проектов, выпуск книг, изданий, в том числе учебников и учебных пособий, для инвалидов по зрению')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990065010') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990065010', 'Субсидии редакциям печатных средств массовой информации и издающим организациям для инвалидов по зрению')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990065020') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990065020', 'Субсидии редакциям печатных средств массовой информации и издающим организациям для инвалидов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990065030') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990065030', 'Субсидии стационарам сложного протезирования на оплату дней пребывания инвалидов в стационарах')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990065040') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990065040', 'Субсидии федеральным государственным унитарным протезно-ортопедическим предприятиям на возмещение убытков, связанных с реализацией протезно-ортопедических изделий и услуг по протезированию по ценам ниже себестоимости')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990065180') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990065180', 'Имущественный взнос Российской Федерации в Государственную корпорацию по содействию разработке, производству и экспорту высокотехнологичной промышленной продукции "Ростех" в целях выполнения комплекса мероприятий по реструктуризации промышленных мощн')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990065940') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990065940', 'Имущественный взнос в уставный капитал государственной корпорации "Банк развития и внешнеэкономической деятельности (Внешэкономбанк)"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990066800') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990066800', 'Субсидии организациям оборонно-промышленного комплекса - головным исполнителям (исполнителям) государственного оборонного заказа на возмещение части затрат на уплату процентов по кредитам, полученным в российских кредитных организациях и в государств')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990066890') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990066890', 'Имущественный взнос Российской Федерации в Государственную корпорацию по содействию разработке, производству и экспорту высокотехнологичной промышленной продукции "Ростех" на проведение работ по организации производства импортозамещающих комплектующи')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990067090') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990067090', 'Субсидии организациям оборонно-промышленного комплекса на возмещение затрат на уплату процентов по кредитам, привлекаемым ими для целей выполнения (реализации) Государственной программы вооружения на 2011 - 2020 годы в рамках государственного оборонн')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990067980') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990067980', 'Субсидия открытому акционерному обществу "Телерадиокомпания Вооруженных Сил Российской Федерации "ЗВЕЗДА"')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='9990068540') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('9990068540', 'Взнос в уставный капитал открытого акционерного общества "Научно-производственное объединение "Сатурн" (г. Рыбинск, Ярославская область)')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ00110') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ00110', 'Расходы на выплаты по оплате труда работников государственных органов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ00120') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ00120', 'Расходы на выплаты по оплате труда работников территориальных органов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ00190') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ00190', 'Расходы на обеспечение функций государственных органов, в том числе территориальных органов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ00380') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ00380', 'Дополнительное финансовое обеспечение выполнения функций федеральными казенными учреждениями, находящимися за пределами Российской Федерации за счет средств, полученных от приносящей доходы деятельности')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ00390') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ00390', 'Расходы на обеспечение функций зарубежного аппарата государственных органов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ00480') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ00480', 'Дополнительное финансовое обеспечение выполнения функций федеральными казенными учреждениями, исполняющими наказания в виде лишения свободы, осуществляемое за счет средств, поступающих от привлечения осужденных к труду')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ00490') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ00490', 'Расходы на обеспечение функционирования Вооруженных Сил Российской Федерации, органов в сфере национальной безопасности и правоохранительной деятельности, войск и иных воинских формирований')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ00590') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ00590', 'Расходы на обеспечение деятельности (оказание услуг) государственных учреждений')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ20180') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ20180', 'Разработка вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ20190') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ20190', 'Закупка и ремонт вооружений, военной и специальной техники, продукции производственно-технического назначения и имущества в рамках государственного оборонного заказа')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ20200') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ20200', 'Подготовка, проведение и подведение итогов статистических обследований и переписей')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ20270') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ20270', 'Реализация мероприятий по подготовке и проведению чемпионата мира по футболу в 2018 году в Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ20400') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ20400', 'Государственный заказ на профессиональную переподготовку и повышение квалификации государственных служащих')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ20410') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ20410', 'Содержание специальных объектов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ20530') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ20530', 'Реализация межгосударственных договоров в рамках Содружества Независимых Государств')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ27940') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ27940', 'Обеспечение реализации международных обязательств Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ27950') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ27950', 'Реализация соглашений с международными финансовыми организациями')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ27960') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ27960', 'Софинансирование, связанное с реализацией соглашений с международными финансовыми организациями')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ27980') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ27980', 'Прочие расходы, связанные с международной деятельностью')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ31050') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ31050', 'Ежемесячная выплата оклада по специальному званию в течение одного года после увольнения гражданам, уволенным со службы в учреждениях и органах уголовно-исполнительной системы, федеральной противопожарной службы Государственной противопожарной службы')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ31060') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ31060', 'Ежемесячное пособие на содержание детей и ежегодное пособие на проведение летнего оздоровительного отдыха детей сотрудников учреждений и органов уголовно-исполнительной системы, федеральной противопожарной службы Государственной противопожарной служб')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ34920') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ34920', 'Накопительно-ипотечная система жилищного обеспечения военнослужащих')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ35940') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ35940', 'Единовременная социальная выплата для приобретения или строительства жилого помещения')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ35960') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ35960', 'Прочие выплаты по обязательствам государства')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ38930') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ38930', 'Стипендии Президента Российской Федерации и Правительства Российской Федерации для обучающихся по направлениям подготовки (специальностям), соответствующим приоритетным направлениям модернизации и технологического развития экономики Российской Федера')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39590') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39590', 'Пособия, выплаты и компенсации лицам, уволенным со службы в учреждениях и органах уголовно-исполнительной системы, федеральной противопожарной службы Государственной противопожарной службы, органах по контролю за оборотом наркотических средств и псих')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39630') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39630', 'Медицинская, социальная и профессиональная реабилитация пострадавших, обеспечение предупредительных мер по сокращению производственного травматизма и профессиональных заболеваний')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39640') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39640', 'Оплата медицинской помощи женщинам в период беременности, родов и в послеродовом периоде, а также профилактического медицинского осмотра ребенка в течение первого года жизни')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39680') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39680', 'Подъемное пособие при переезде военнослужащим, проходящим военную службу по контракту, на новое место военной службы в другой населенный пункт, в том числе на территорию или с территории иностранного государства, в связи с назначением на воинскую дол')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39690') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39690', 'Ежемесячные компенсационные выплаты матерям (или другим родственникам, фактически осуществляющим уход за ребенком), состоящим в трудовых отношениях на условиях найма с организациями, и женщинам-военнослужащим, находящимся в отпуске по уходу за ребенк')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39700') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39700', 'Возмещение расходов, связанных с перевозкой сотрудников органов внутренних дел, учреждений и органов уголовно-исполнительной системы, федеральной противопожарной службы Государственной противопожарной службы, граждан, уволенных со службы из этих орга')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39710') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39710', 'Возмещение учреждениям государственной и муниципальной систем здравоохранения расходов на оказание медицинской помощи военнослужащим, гражданам, призванным на военные сборы, сотрудникам органов внутренних дел Российской Федерации, федеральной противо')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39740') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39740', 'Компенсация расходов на оплату стоимости проезда и провоза багажа при переезде лиц (работников), а также членов их семей при заключении (расторжении) трудовых договоров с организациями, финансируемыми из федерального бюджета, расположенными в районах')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39870') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39870', 'Компенсация расходов на оплату стоимости проезда и провоза багажа к месту использования отпуска и обратно лицам, работающим в организациях, финансируемых из федерального бюджета, расположенных в районах Крайнего Севера и приравненных к ним местностях')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39880') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39880', 'Ежемесячное пособие по уходу за ребенком')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39890') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39890', 'Единовременное пособие женщинам, вставшим на учет в медицинских учреждениях в ранние сроки беременности')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39900') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39900', 'Единовременное пособие при рождении ребенка')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39910') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39910', 'Пособие по беременности и родам')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39920') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39920', 'Обязательное государственное страхование жизни и здоровья военнослужащих, граждан, призванных на военные сборы, лиц рядового и начальствующего состава органов внутренних дел Российской Федерации, федеральной противопожарной службы Государственной про')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39940') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39940', 'Ежемесячная денежная компенсация за наем (поднаем) жилых помещений')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39960') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39960', 'Выплата единовременного (выходного) пособия при увольнении военнослужащих и сотрудников правоохранительных органов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39970') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39970', 'Компенсация расходов на оплату жилых помещений, отопления и освещения педагогическим работникам, проживающим и работающим в сельской местности')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ39990') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ39990', 'Ежемесячная денежная выплата по оплате жилых помещений, отопления и освещения медицинским и фармацевтическим работникам федеральных государственных учреждений, подведомственных федеральным органам исполнительной власти')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ40090') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ40090', 'Создание объектов социального и производственного комплексов, в том числе объектов общегражданского назначения, жилья, инфраструктуры, и иных объектов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ40330') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ40330', 'Обеспечение имеющих специальные звания сотрудников федеральных органов исполнительной власти, в которых предусмотрена служба, приравненная к военной, служебными жилыми помещениями и жилыми помещениями в общежитиях')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ40340') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ40340', 'Строительство и приобретение жилых помещений для постоянного проживания имеющих специальные звания сотрудников федеральных органов исполнительной власти, в которых предусмотрена служба, приравненная к военной')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ51060') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ51060', 'Иные межбюджетные трансферты за счет средств резервного фонда Правительства Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ51110') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ51110', 'Субсидии на софинансирование капитальных вложений в объекты государственной собственности субъектов Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ51120') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ51120', 'Субсидии на софинансирование капитальных вложений в объекты муниципальной собственности')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ51720') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ51720', 'Иные межбюджетные трансферты за счет резервного фонда Президента Российской Федерации')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ52310') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ52310', 'Реализация программ модернизации здравоохранения субъектов Российской Федерации в части внедрения современных информационных систем в здравоохранение в целях перехода на полисы обязательного медицинского страхования единого образца')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ52320') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ52320', 'Реализация программ модернизации здравоохранения субъектов Российской Федерации в части внедрения стандартов медицинской помощи, повышения доступности амбулаторной медицинской помощи')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ52330') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ52330', 'Реализация мероприятий по модернизации государственных учреждений, оказывающих медицинскую помощь, в части укрепления материально-технической базы медицинских учреждений')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ52340') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ52340', 'Реализация мероприятий по модернизации государственных учреждений, оказывающих медицинскую помощь, в части внедрения современных информационных систем в здравоохранение в целях перехода на полисы обязательного медицинского страхования единого образца')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ52350') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ52350', 'Реализация мероприятий государственными учреждениями по внедрению современных информационных систем в здравоохранение')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ60570') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ60570', 'Мероприятия по патриотическому воспитанию граждан Российской Федерации')
GO
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ60860') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ60860', 'Премии в области литературы и искусства, образования, печатных средств массовой информации, науки и техники и иные поощрения за особые заслуги перед государством')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ60940') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ60940', 'Субсидии на возмещение расходов по содержанию специальных объектов')
IF NOT EXISTS (SELECT * FROM dbo.[KL_TARGET_ITEM] WHERE CODE ='ХХХХХ61620') 
INSERT INTO dbo.[KL_TARGET_ITEM](CODE, NAME)
VALUES ('ХХХХХ61620', 'Гранты в области науки, культуры, искусства и средств массовой информации')


GO
/****** Объект: Комментарий******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'COMM_ATTEST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'COMM_ATTEST')
	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 = 'COMM_ATTEST')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'COMM_ATTEST')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'COMM_ATTEST'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'COMM_ATTEST')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='COMM_ATTEST')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'COMM_ATTEST', 'Комментарий', 17, (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_ATTEST'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'COMM_ATTEST', NAME = 'Комментарий', ORDERS = '17', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='KU_EMPL_ATTEST'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='COMM_ATTEST'
GO
EXEC X_SET_PROP 'COMM_ATTEST', 'TITLE', 'Комментарий'
GO
EXEC X_SET_PROP 'COMM_ATTEST', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'COMM_ATTEST', 'CONTROLSOURCE', 'm.cAlias+".COMM"'
GO
EXEC X_SET_PROP 'COMM_ATTEST', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'COMM_ATTEST', 'STORAGE', 'DICTION_APP'
GO
EXEC X_SET_PROP 'COMM_ATTEST', 'TYPE_FIELD_DICT', 'VARCHAR(200)'
GO
EXEC X_SET_PROP 'COMM_ATTEST', 'SHORT_CODE_OBJ', 'COMM'
GO
EXEC X_SET_PROP 'COMM_ATTEST', 'CONTROLSOURCE_EDIT', 'm.cAlias+".COMM"'
GO
EXEC X_SET_PROP 'COMM_ATTEST', 'CONTROL_NAME_EDIT', 'atxt13'
GO
EXEC X_SET_PROP 'COMM_ATTEST', 'COMMENTARY', 'Комментарий'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
IF EXISTS (SELECT * FROM dbo.MED_POL WHERE [DATE] is NULL  OR [DATE] = '19000101'  )
   BEGIN 
   		 DELETE FROM  dbo.MED_POL WHERE [DATE] is NULL OR [DATE] = '19000101' 
   END		 
GO

GO

EXEC X_SET_PROP 'MONEY_CHANGE', 'SAVE_OBJECT_METHOD', 'U_SAVE_TABLE_PART(''KU_MONEY_SAVE'', m.cAlias,"NUMBER,SQLNULL(DATE),EMPL_LINK,SQLNULL(DATE_BEGIN),SQLNULL(DATE_END2),ORDER_LINK,SQLNULL(REF_ATT)","MONEY_CHANGE", .t.)'
GO

EXEC X_SET_PROP 'MC_DATE_END', 'VISIBLE', '15'
GO


GO
--- ОТЧЕТ: РЕЕСТР ОС ПО НАЛОГУ НА ИМУЩЕСТВО (SQL_REP_LIST_TAX_ON_OS1) --- 
DELETE FROM dbo.OBJECT_VAR WHERE LINK_SELF = (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1_NAST1')
DELETE FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1_NAST1'
GO
DELETE FROM dbo.OBJECT_VAR WHERE LINK_SELF = (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1_FIL1')
DELETE FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1_FIL1'
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'QUERY_SQL'), 'Реестр ОС по налогу на имущество', NULL, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_DIRECTORY_NA_SV'), 'SQL_REP_LIST_TAX_ON_OS1', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1_NAST1')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'QUERY_NASTRS'), 'Настройки', 2, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1'), 'SQL_REP_LIST_TAX_ON_OS1_NAST1', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1_FIL1')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'QUERY_FILTER'), 'Стандартный фильтр для запроса', 0, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1'), 'SQL_REP_LIST_TAX_ON_OS1_FIL1', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1_NAST11')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_MONTHBOX'), 'Расчетный месяц', 3, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1_NAST1'), 'SQL_REP_LIST_TAX_ON_OS1_NAST11', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1_NAST12')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_YEARBOX'), 'Расчетный год', 4, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1_NAST1'), 'SQL_REP_LIST_TAX_ON_OS1_NAST12', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1_NAST14')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_CHECKBOX'), 'Сводный отчет (ЦБ)', 6, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1_NAST1'), 'SQL_REP_LIST_TAX_ON_OS1_NAST14', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1_NAST13')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'NASTR_QUERY_CHECKBOX'), 'Группировать по налоговым ставкам', 5, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1_NAST1'), 'SQL_REP_LIST_TAX_ON_OS1_NAST13', NULL, NULL, 1
GO
IF NOT EXISTS (SELECT * FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1_FIL11')
	INSERT INTO dbo.OBJECT_VAR (OBJECT, [NAME], ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS)
	SELECT (SELECT LINK FROM dbo.S_OBJECTS WHERE CODE = 'OTBOR_QUERY_DIC_IMU_TAX_RATE'), 'Отбор ставок налога для налога на имущество', 1, (SELECT LINK FROM dbo.OBJECT_VAR WHERE CODE = 'SQL_REP_LIST_TAX_ON_OS1_FIL1'), 'SQL_REP_LIST_TAX_ON_OS1_FIL11', NULL, NULL, 1
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'INIT_OBJECT_METHOD', 'm_print_query(nLink_Var)', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'CHECK_VALUE_IN_TABLE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'AFTER_CHANGE_PROG_NASTR', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'BEFORE_CHANGE_PROG_NASTR', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'NASTR_XL_CENTER_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'NASTR_XL_DATETIME', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'NASTR_XL_FOOTER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'NASTR_XL_FREEZEPANES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'NASTR_XL_LEFT_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'NASTR_XL_PAGES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'NASTR_XL_RIGHT_HEADER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_ADDFROM', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_ADDINTO', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_ADDSELECT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_ADDWHERE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_AFTER', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_BEFORE', 'EXEC	BK_REPORT_LIST_TAX_ON_OS1
	@nMonth1	/* Расчетный месяц */,
	@cYear1	/* Год */,
	@nCheck3	/* Группировать по налоговым ставкам */,
	@nCheck2	/* Сводный отчет (ЦБ) */,
	@cVal1, @nOtborLink1	/* Отбор ставок налога для налога на имущество */', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_DATETIME', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_DISTINCT', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_FOOTER', '="Исполнитель                               " & User_FIO
                                 подпись', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_FREEZEPANES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_HEADER', '=User_Name', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_PAGES', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_PROCEDURE', '#REP_LIST_TAX_ON_OS1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_REPMAKER', 'KIRREPMAKER.XLS', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_REPORT', 'IIF(.T.,"LIST_TAX_ON_OS1.XLT","")', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_REPORT_PATH', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_SQL', 'CREATE PROCEDURE #REP_LIST_TAX_ON_OS1
	@nMonth1 int	/* Расчетный месяц */,
	@cYear1 VARCHAR(4)	/* Расчетный год */,
	@nCheck3 int	/* Группировать по налоговым ставкам */,
	@nCheck2 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_DIC_IMU_TAX_RATE''))
	SELECT @cVal1 = (SELECT VALUE FROM OBJECT_VAR_VALUES WHERE LINK_UP=@nOtborLink1 AND PROPERTY=(SELECT LINK FROM S_PROPERTY WHERE CODE=''QUERY_OTBOR_CHECK''))

EXEC	BK_REPORT_LIST_TAX_ON_OS1
	@nMonth1	/* Расчетный месяц */,
	@cYear1	/* Год */,
	@nCheck3	/* Группировать по налоговым ставкам */,
	@nCheck2	/* Сводный отчет (ЦБ) */,
	@cVal1, @nOtborLink1	/* Отбор ставок налога для налога на имущество */

END', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_SYSTEM', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_TOP', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_TOTAL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_TOTALCOL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_TOTALROW', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_AP_LIST', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'EOD_PROTOCOL', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'AFTER_REPORT_PROG', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_ADD_MODULE', 'KirRepCommon.bas', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_CODE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'QUERY_DATE_TYPE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'SQUERY_NO_SHOW', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1', 'REPORT_EXTERNAL_GENERATOR', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST1', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_FIL1', 'QUERY_NASTR_NOTE', 'Стандартный фильтр для отчета', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_FIL1', 'QUERY_VARIANT_ID', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST11', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST11', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST11', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST11', 'QUERY_NASTR_CAPTION', 'Расчетный месяц', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST11', 'QUERY_NASTR_CONTROL', 'MONTHBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST11', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST11', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST11', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST11', 'QUERY_NASTR_SOURCE', 'Текущий месяц,Расчетный месяц', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST11', 'QUERY_NASTR_SQLPARAM', '@nMonth1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST11', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST11', 'QUERY_NASTR_VALUE', 'Расчетный месяц', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST11', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST11', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST12', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST12', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST12', 'FORMAT', '9999', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST12', 'QUERY_NASTR_CAPTION', 'Расчетный год', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST12', 'QUERY_NASTR_CONTROL', 'MASKBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST12', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST12', 'QUERY_NASTR_NUMPARAM', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST12', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST12', 'QUERY_NASTR_SOURCE', 'Текущий год,Расчетный год', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST12', 'QUERY_NASTR_SQLPARAM', '@cYear1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST12', 'QUERY_NASTR_SQLTYPE', 'VARCHAR(4)', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST12', 'QUERY_NASTR_VALUE', 'Расчетный год', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST12', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST12', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST14', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST14', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST14', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST14', 'QUERY_NASTR_CAPTION', 'Сводный отчет (ЦБ)', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST14', 'QUERY_NASTR_CONTROL', 'CHECKBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST14', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST14', 'QUERY_NASTR_NUMPARAM', '2', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST14', 'QUERY_NASTR_SAVE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST14', 'QUERY_NASTR_SOURCE', 'Выкл.,Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST14', 'QUERY_NASTR_SQLPARAM', '@nCheck2', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST14', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST14', 'QUERY_NASTR_VALUE', 'Выкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST14', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST14', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST13', 'EDITABLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST13', 'SQUERY_NASTR_NON_VISIBLE', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST13', 'FORMAT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST13', 'QUERY_NASTR_CAPTION', 'Группировать по налоговым ставкам', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST13', 'QUERY_NASTR_CONTROL', 'CHECKBOX', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST13', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST13', 'QUERY_NASTR_NUMPARAM', '3', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST13', 'QUERY_NASTR_SAVE', '1', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST13', 'QUERY_NASTR_SOURCE', 'Выкл.,Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST13', 'QUERY_NASTR_SQLPARAM', '@nCheck3', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST13', 'QUERY_NASTR_SQLTYPE', 'int', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST13', 'QUERY_NASTR_VALUE', 'Вкл.', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST13', 'QUERY_NASTR_VALUE_TEXT', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_NAST13', 'SQUERY_NASTR_OPTIONAL', '0', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_FIL11', 'QUERY_NASTR_NOTE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_FIL11', 'QUERY_OTBOR_CHECK', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_FIL11', 'QUERY_OTBOR_DICTIONARY_CODE', 'DIC_IMU_TAX_RATE', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_FIL11', 'QUERY_OTBOR_FIELD', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_FIL11', 'QUERY_OTBOR_PARENT_CODE', '', 0
GO
EXEC dbo.KIR_OBJECT_VAR_SET_VALUE 'SQL_REP_LIST_TAX_ON_OS1_FIL11', 'QUERY_OTBOR_VALUE', '', 0
GO




GO
/****** Объект: Прекращение деятельности******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_LIKVID')
	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_LIKVID')
	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_LIKVID')
	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_LIKVID')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_LIKVID'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_LIKVID')	

GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORTS_ATR_LIKVID')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORTS_ATR_LIKVID', 'Прекращение деятельности', 57, (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_LIKVID', NAME = 'Прекращение деятельности', ORDERS = '57', 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_LIKVID'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LIKVID', 'NAME', 'Прекращение деятельности'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LIKVID', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("RB_VIEW_ATR_DA_NET",oForm.ALIAS_ATR, "CODE", "REPORTS_ATR_LIKVID", "", "", "", .T., 0, oForm, oObj)'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LIKVID', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LIKVID', 'CONTROL_TYPE', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LIKVID', 'SHORT_NAME', 'Прекращение деятельности'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LIKVID', 'CHECK_WHEN', 'ALIB_NEED_SPR (oObj)'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LIKVID', 'DEFAULT_VALUE', 'Нет'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LIKVID', 'MAXWIDTH', '11'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LIKVID', 'DICTIONARY', 'RB_VIEW_ATR_DA_NET'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LIKVID', 'DICTIONARY_COLUMNS_LIST', 'REPORTS_ATR_LIKVID'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LIKVID', 'DICTIONARY_FIELDS_LIST', 'CODE'
GO


/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'REPORTS_ATR_LIKVID', 'Свод-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'REPORTS_ATR_LIKVID', 'Зарплата-КС', 63,0
GO

GO
/****** Объект: Право на применение пониженного тарифа******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_LOW_TAR')
	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_LOW_TAR')
	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_LOW_TAR')
	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_LOW_TAR')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_LOW_TAR'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORTS_ATR_LOW_TAR')	

GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='REPORTS_ATR_LOW_TAR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'REPORTS_ATR_LOW_TAR', 'Право на применение пониженного тарифа', 58, (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_LOW_TAR', NAME = 'Право на применение пониженного тарифа', ORDERS = '58', 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_LOW_TAR'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LOW_TAR', 'NAME', 'Право на примен. пониж. тарифа'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LOW_TAR', 'EDIT_OBJECT_METHOD', 'A_VIBOR_01 ("RB_VIEW_ATR_DA_NET",oForm.ALIAS_ATR, "CODE", "REPORTS_ATR_LOW_TAR", "", "", "", .T., 0, oForm, oObj)'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LOW_TAR', 'VISIBLE', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LOW_TAR', 'CONTROL_TYPE', '1'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LOW_TAR', 'SHORT_NAME', 'Право на применение пониженного тарифа'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LOW_TAR', 'CHECK_WHEN', 'ALIB_NEED_SPR (oObj)'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LOW_TAR', 'DEFAULT_VALUE', 'Да'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LOW_TAR', 'MAXWIDTH', '11'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LOW_TAR', 'DICTIONARY', 'RB_VIEW_ATR_DA_NET'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LOW_TAR', 'DICTIONARY_COLUMNS_LIST', 'REPORTS_ATR_LOW_TAR'
GO
EXEC X_SET_PROP 'REPORTS_ATR_LOW_TAR', 'DICTIONARY_FIELDS_LIST', 'CODE'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'REPORTS_ATR_LOW_TAR', 'Свод-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'REPORTS_ATR_LOW_TAR', 'Зарплата-КС', 63,0
GO


GO

UPDATE S_OBJECTS 
	SET NAME = 	'Причина уточнения'
WHERE code = 'REPORTS_ATR_TYPE_KOR'

GO

EXEC X_SET_PROP 'REPORTS_ATR_TYPE_KOR', 'NAME', 'Причина уточнения'
GO

EXEC X_SET_PROP 'REPORTS_ATR_TYPE_KOR', 'SHORT_NAME', 'Причина уточнения'
GO

GO

-- Отчет "Карточка индивидуального учета сумм страховых взносов ПФР,ОМС,ФСС(2015)"
-- Сгенерировано скриптом scriptObjectVar 'REP_PERS_CARD_ESN_15'

/*** Сам отчет ***/

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= 'REP_PERS_CARD_ESN_15'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'REP_PERS_CARD_ESN_15'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Карточка индивидуального учета сумм страховых взносов ПФР,ОМС,ФСС(2015)',304, 
	(Select link from object_var where code = 'SQL_REPORT_CATALOG_SALARY'),
	'REP_PERS_CARD_ESN_15',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'REP_PERS_CARD_ESN_15') 
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= '	DECLARE @nLINK INT
	SET @nLINK = CAST(@cText1 AS INT)

	IF CONVERT(INT, @cYear1) >= 2015
       begin
		EXEC dbo.SA_PERS_CARD_ESN_15 @nLINK, @cYear1
	 end	
	ELSE 
	begin	
		DECLARE @varKSMesStr varchar(1000)
		SET @varKSMesStr = ''Формирование прервано!  Расчетный период меньше 2015 года''
		RAISERROR (@varKSMesStr,11,1)
 		RETURN 1005
	end'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#REP_PERS_CARD_ESN_15'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"PERS_CARD_ESN_15.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #REP_PERS_CARD_ESN_15
	@cText1 INT	/* Лицо */,
	@cYear1 VARCHAR(4)	/* Расчетный год */
AS
BEGIN

	DECLARE @nLINK INT
	SET @nLINK = CAST(@cText1 AS INT)

	IF CONVERT(INT, @cYear1) >= 2015
       begin
		EXEC dbo.SA_PERS_CARD_ESN_15 @nLINK, @cYear1
	 end	
	ELSE 
	begin	
		DECLARE @varKSMesStr varchar(1000)
		SET @varKSMesStr = ''Формирование прервано!  Расчетный период меньше 2015 года''
		RAISERROR (@varKSMesStr,11,1)
 		RETURN 1005
	end

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADD_MODULE'),
	VALUE= 'PERS_CARD_ESN_15.BAS'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	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 = 'REP_PERS_CARD_ESN_15') 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 = 'REP_PERS_CARD_ESN_15'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'REP_PERS_CARD_ESN_15_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'),
		'Группа настроек',1, 
		(Select link from object_var where code = 'REP_PERS_CARD_ESN_15'),
		'REP_PERS_CARD_ESN_15_NASTR_GR',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'REP_PERS_CARD_ESN_15_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_TEXTBOX'),
					'Лицо',2, 
					(Select link from object_var where code = 'REP_PERS_CARD_ESN_15_NASTR_GR'),
					'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_MAIN_PARAM'),
							(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 = 'REP_PERS_CARD_ESN_15_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_MAIN_PARAM'),
							(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 = 'REP_PERS_CARD_ESN_15_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_MAIN_PARAM'),
							(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 = 'REP_PERS_CARD_ESN_15_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_MAIN_PARAM'),
							(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 = 'REP_PERS_CARD_ESN_15_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'0'
					
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 = 'REP_PERS_CARD_ESN_15_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'REP_PERS_CARD_ESN_15_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_YEARBOX'),
					'Расчетный год',3, 
					(Select link from object_var where code = 'REP_PERS_CARD_ESN_15_NASTR_GR'),
					'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_NASTR2'),
							(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 = 'REP_PERS_CARD_ESN_15_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_NASTR2'),
							(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 = 'REP_PERS_CARD_ESN_15_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_NASTR2'),
							(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 = 'REP_PERS_CARD_ESN_15_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_NASTR2'),
							(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 = 'REP_PERS_CARD_ESN_15_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							''
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'REP_PERS_CARD_ESN_15_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_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 = 'REP_PERS_CARD_ESN_15_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_NASTR2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO







/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Индивидуальная карточка страховых взносов ПФР, ОМС, ФСС(2015)"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'REP_PERS_CARD_ESN_15')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SALARY_DOC_TREE_ROOT' AND NAME = 'Документы по зарплате')

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' AND NAME = 'Документы по зарплате'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SNV_REP_PERS_CARD_ESN_15'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'SNV_REP_PERS_CARD_ESN_15', 'Индивидуальная карточка страховых взносов ПФР, ОМС, ФСС(2015)', @ORD, NULL, 1, @LINK_SELF, 'REPORT', @OBJECT, @LINK_VAR, 3
GO




-- Отчет "Карточка индивидуального учета сумм страховых взносов ПФР,ОМС,ФСС для сотрудников с дог. ГПХ"
-- Сгенерировано скриптом scriptObjectVar 'REP_PERS_CARD_ESN_15_DGH'

/*** Сам отчет ***/

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= 'REP_PERS_CARD_ESN_15_DGH'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'REP_PERS_CARD_ESN_15_DGH'
	INSERT INTO object_var (OBJECT, NAME, ORDERS, LINK_SELF, CODE, LINK_STATE, USERS, SYS) 
	Select (Select link from s_objects where code = 'QUERY_SQL'),
	'Карточка индивидуального учета сумм страховых взносов ПФР,ОМС,ФСС для сотрудников с дог. ГПХ(2015)',304, 
	(Select link from object_var where code = 'SQL_REPORT_CATALOG_SALARY'),
	'REP_PERS_CARD_ESN_15_DGH',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'REP_PERS_CARD_ESN_15_DGH') 
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= '	DECLARE @nLINK INT
	SET @nLINK = CAST(@cText1 AS INT)

	IF CONVERT(INT, @cYear1) >= 2015
		EXEC dbo.SA_PERS_CARD_ESN_15 NULL, @cYear1, @nLINK
'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#REP_PERS_CARD_ESN_15_DGH'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"PERS_CARD_ESN_15.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #REP_PERS_CARD_ESN_15_DGH
	@cText1 INT	/* Лицо */,
	@cYear1 VARCHAR(4)	/* Расчетный год */
AS
BEGIN

	DECLARE @nLINK INT
	SET @nLINK = CAST(@cText1 AS INT)

	IF CONVERT(INT, @cYear1) >= 2015
		EXEC dbo.SA_PERS_CARD_ESN_15 NULL, @cYear1, @nLINK


END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_ADD_MODULE'),
	VALUE= 'PERS_CARD_ESN_15.BAS'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	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 = 'REP_PERS_CARD_ESN_15_DGH') 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 = 'REP_PERS_CARD_ESN_15_DGH'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'REP_PERS_CARD_ESN_15_DGH_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'),
		'Группа настроек',1, 
		(Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH'),
		'REP_PERS_CARD_ESN_15_DGH_NASTR_GR',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'REP_PERS_CARD_ESN_15_DGH_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_TEXTBOX'),
					'Лицо',2, 
					(Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_NASTR_GR'),
					'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM'),
							(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 = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM'),
							(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 = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM'),
							(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 = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM'),
							(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 = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'0'
						
					
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 = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_MAIN_PARAM'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'REP_PERS_CARD_ESN_15_DGH_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_YEARBOX'),
					'Расчетный год',3, 
					(Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_NASTR_GR'),
					'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_NASTR2'),
							(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 = 'REP_PERS_CARD_ESN_15_DGH_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_NASTR2'),
							(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 = 'REP_PERS_CARD_ESN_15_DGH_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_NASTR2'),
							(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 = 'REP_PERS_CARD_ESN_15_DGH_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_NASTR2'),
							(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 = 'REP_PERS_CARD_ESN_15_DGH_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'2015'

						
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 = 'REP_PERS_CARD_ESN_15_DGH_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_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 = 'REP_PERS_CARD_ESN_15_DGH_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'REP_PERS_CARD_ESN_15_DGH_NASTR2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO



/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Индивидуальная карточка страховых взносов ПФР, ОМС, ФСС"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = (SELECT LINK FROM OBJECT_VAR WHERE CODE = 'REP_PERS_CARD_ESN_15_DGH')

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SALARY_DGH_DOC_TREE_ROOT' AND NAME = 'Документы по физлицам с договорами ГПХ')

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_DGH_DOC_TREE_ROOT' AND NAME = 'Документы по физлицам с договорами ГПХ'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SNV1_REP_PERS_CARD_ESN_15'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'SNV1_REP_PERS_CARD_ESN_15', 'Индивидуальная карточка страховых взносов ПФР, ОМС, ФСС(2015)', @ORD, NULL, 1, @LINK_SELF, 'REPORT', @OBJECT, @LINK_VAR, 3
GO





UPDATE  DBO.OBJECT_VAR
	set NAME  = 'Карточка индивидуального учета сумм страховых взносов ПФР,ОМС,ФСС (c 2010г.) для сотрудников с дог. ГПХ'     
where code = 'REP_PERS_CARD_ESN_10_DGH'

GO


UPDATE  DBO.S_NAVIGATOR
	set NAME  = 'Индивидуальная карточка страховых взносов ПФР, ОМС, ФСС (c 2010г.)'     
where code = 'SNV1_REP_PERS_CARD_ESN_10'

GO


UPDATE  DBO.OBJECT_VAR
	set NAME  = 'Карточка индивидуального учета сумм страховых взносов ПФР,ОМС,ФСС (c 2010г.)'     
where code = 'REP_PERS_CARD_ESN_10'

GO

UPDATE  DBO.S_NAVIGATOR
	set NAME  = 'Карточка индивидуального учета сумм страховых взносов ПФР,ОМС,ФСС (c 2010г.)'     
where code = 'SNV_REP_PERS_CARD_ESN_10'

GO



UPDATE  DBO.OBJECT_VAR
	set NAME  = 'Карточка индивидуального учета сумм страховых взносов ПФР,ОМС,ФСС (c 2015г.)'     
where code = 'REP_PERS_CARD_ESN_15'

GO

UPDATE  DBO.S_NAVIGATOR
	set NAME  = 'Индивидуальная карточка страховых взносов ПФР, ОМС, ФСС (c 2015г.)'     
where code = 'SNV_REP_PERS_CARD_ESN_15'

GO



UPDATE  DBO.OBJECT_VAR
	set NAME  = 'Карточка индивидуального учета сумм страховых взносов ПФР,ОМС,ФСС для сотрудников с дог. ГПХ (с 2015г.)'     
where code = 'REP_PERS_CARD_ESN_15_DGH'

GO

UPDATE  DBO.S_NAVIGATOR
	set NAME  = 'Индивидуальная карточка страховых взносов ПФР, ОМС, ФСС (c 2015г.)'     
where code = 'SNV1_REP_PERS_CARD_ESN_15'

GO


UPDATE sn
	set ORDERS = case sn.CODE when 'SNV_SQL_REP_NDFL_CARD_2011_DGH' then 5 
					  when 'SNV_SQL_REPORT_F417_DGH' then 6 
					  when 'SNV1_REP_PERS_CARD_ESN_15' then 4 
					  else sn.ORDERS end 
from DBO.S_NAVIGATOR sn where LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SALARY_DGH_DOC_TREE_ROOT')

GO


UPDATE sn
	set ORDERS = case sn.CODE when 'SNV_FaceCardOfTheEmployee' then 8 
					  when 'SNV_EMPL_PAYS_SHEET' then 9
					  when 'SNV_InfoSalEmpl' then 10
					  when 'SNV_SJ_SPRAVKA_SSUD_SB' then 11
					  when 'SNV_SA_EMPL_PAYS' then 12
					  when 'SNV_SA_SPRAVKA_ZPGS' then  13
					  when 'SNV_SQL_REPORT_SA_SPRAVKA_BL' then 14
					  when 'SNV_SQL_REP_NDFL_CARD_2011' then 15
					  when 'SNV_SQL_SZP_SPR_REP' then 16 
					  when 'SNV_SQL_REP_SS_SVED_ZP_TAX' then 17
					  when 'SNV_SQL_REP_SPR_DOP_VZNOS' then 18
					  when 'SNV_SQL_REP_ESN_CARD' then 5
					  when 'SNV_REP_PERS_CARD_ESN_10' then 6
					  when 'SNV_REP_PERS_CARD_ESN_15' then 7
					  else sn.ORDERS end 
from DBO.S_NAVIGATOR sn where LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SALARY_DOC_TREE_ROOT')

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='SALARY_OPTIONS_OPTIONS'

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_SALARY_OPTIONS_OPTIONS]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS]

CREATE TABLE  dbo._UPD_OPT_SALARY_OPTIONS_OPTIONS (CODE VARCHAR(30), [SID] varbinary(85), VALUE VARCHAR(1000))

INSERT INTO _UPD_OPT_SALARY_OPTIONS_OPTIONS (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 = 'SALARY_OPTIONS_OPTIONS')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'SALARY_OPTIONS_OPTIONS')
	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 = 'SALARY_OPTIONS_OPTIONS')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'SALARY_OPTIONS_OPTIONS')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPTIONS'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPTIONS')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SALARY_OPTIONS_OPTIONS', 'Настройки счетов для проводок по зарплате', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SALARY_OPTIONS_OPTIONS', NAME = 'Настройки счетов для проводок по зарплате', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='CLASS_GRID_GROUP'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SALARY_OPTIONS_OPTIONS'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPT1')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SALARY_OPTIONS_OPT1', 'Счет начислений на оплату труда (999)', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SALARY_OPTIONS_OPT1', NAME = 'Счет начислений на оплату труда (999)', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SALARY_OPTIONS_OPT1'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPT2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SALARY_OPTIONS_OPT2', 'Счет для расчетов по удержаниям из з/пл (999.99)', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SALARY_OPTIONS_OPT2', NAME = 'Счет для расчетов по удержаниям из з/пл (999.99)', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SALARY_OPTIONS_OPT2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPT5')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SALARY_OPTIONS_OPT5', 'Счет ДТ для формирования проводок по начислению страховых взносов (999.99)', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SALARY_OPTIONS_OPT5', NAME = 'Счет ДТ для формирования проводок по начислению страховых взносов (999.99)', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SALARY_OPTIONS_OPT5'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPT6')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SALARY_OPTIONS_OPT6', 'Счет для расчетов отчислений ЕСН на з/пл (999.99)', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SALARY_OPTIONS_OPT6', NAME = 'Счет для расчетов отчислений ЕСН на з/пл (999.99)', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SALARY_OPTIONS_OPT6'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPT7')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SALARY_OPTIONS_OPT7', 'Счет для расчетов отчислений по травматизму (999.99)', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SALARY_OPTIONS_OPT7', NAME = 'Счет для расчетов отчислений по травматизму (999.99)', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SALARY_OPTIONS_OPT7'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPT14')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SALARY_OPTIONS_OPT14', 'Счет ДТ для формир. проводок по начисл. страх. взносов за счет резерва (999.99)', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SALARY_OPTIONS_OPT14', NAME = 'Счет ДТ для формир. проводок по начисл. страх. взносов за счет резерва (999.99)', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SALARY_OPTIONS_OPT14'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPT13')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SALARY_OPTIONS_OPT13', 'Счет для выбытия ср-в с лиц. либо расч. счета', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SALARY_OPTIONS_OPT13', NAME = 'Счет для выбытия ср-в с лиц. либо расч. счета', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_OPTIONS_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SALARY_OPTIONS_OPT13'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPTIONS', 'TITLE', 'Настройки счетов для проводок по зарплате'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPTIONS', 'EDIT_OBJECT_METHOD', 'sa_open_task_options("SALARY_OPTIONS_OPTIONS ", "Настройки счетов для проводок по зарплате")'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPTIONS', 'COMMENTARY', 'Настройки счетов для проводок по зарплате'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT1', 'TITLE', 'Счет начислений на оплату труда'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT1', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT1', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT1', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT1', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT1', 'CONTROL_NAME_EDIT', 'ATextBox1'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT1', 'INPUT_MASK', '999'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT1', 'COMMENTARY', 'Используется при автоматическом формировании проводок по начислению з/пл. Обычно принимает значение "302"'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT2', 'TITLE', 'Счет для расчетов по удержаниям из з/пл'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT2', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT2', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT2', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT2', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT2', 'CONTROL_NAME_EDIT', 'ATextBox2'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT2', 'INPUT_MASK', '999.99'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT2', 'COMMENTARY', 'Используется при автоматическом формировании проводок по удержаниям из з/пл. Обычно принимает значение "304.03"'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT5', 'TITLE', 'Счет ДТ для формирования проводок по начислению страховых взносов'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT5', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT5', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT5', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT5', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT5', 'CONTROL_NAME_EDIT', 'ATextBox3'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT5', 'INPUT_MASK', '999.99'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT5', 'COMMENTARY', 'Используется при автоматическом формировании проводок по начислению ЕСН. Обычно принимает значение "401.20"'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT6', 'TITLE', 'Счет для расчетов отчислений ЕСН на з/пл (999.99)'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT6', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT6', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT6', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT6', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT6', 'CONTROL_NAME_EDIT', 'ATextBox4'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT6', 'INPUT_MASK', '999.99'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT6', 'COMMENTARY', 'Используется при автоматическом формировании проводок по расчету отчислений ЕСН. Обычно принимает значение "303.02"'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT7', 'TITLE', 'Счет для расчетов отчислений по травматизму (999.99)'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT7', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT7', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT7', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT7', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT7', 'CONTROL_NAME_EDIT', 'ATextBox5'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT7', 'INPUT_MASK', '999.99'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT7', 'COMMENTARY', 'Используется при автоматическом формировании проводок по расчету отчислений по травматизму. Обычно принимает значение "303.06"'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT14', 'TITLE', 'Счет ДТ для формирования проводок по начислению страховых взносов за счет резерва'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT14', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT14', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT14', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT14', 'TYPE_FIELD_DICT', 'VARCHAR(20)'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT14', 'CONTROL_NAME_EDIT', 'ATextBox3'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT14', 'INPUT_MASK', '999.99'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT14', 'COMMENTARY', 'Используется при автоматическом формировании проводок по начислению страховых взносов за счет Резерва. Обычно принимает значение "401.60"'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT13', 'TITLE', 'Счет для выбытия средств с лицевого либо расчетного счета'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT13', 'EDIT_OBJECT_METHOD', 'lanc_init_object(''SA_SAL_NASTR_PROV  '',.T.)'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT13', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT13', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT13', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT13', 'TYPE_FIELD_DICT', 'INT'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT13', 'SHORT_CODE_OBJ', 'AN_OPT8'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT13', 'CONTROL_NAME_EDIT', 'AOpenSpr6'
GO
EXEC X_SET_PROP 'SALARY_OPTIONS_OPT13', 'COMMENTARY', 'Счет для выбытия средств с лицевого либо расчетного счета. Используется при автоматическом формировании проводок. Значения заданы в справочнике.'
GO
/******--Восстановить, либо установить настройки на базе пользователя ******/
DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'SALARY_OPTIONS_OPT1' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS] WHERE CODE = 'SALARY_OPTIONS_OPT1')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT1'), SID, VALUE FROM [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS] WHERE CODE = 'SALARY_OPTIONS_OPT1'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '302' FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT1'

GO

DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'SALARY_OPTIONS_OPT2' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS] WHERE CODE = 'SALARY_OPTIONS_OPT2')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT2'), SID, VALUE FROM [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS] WHERE CODE = 'SALARY_OPTIONS_OPT2'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '304.03' FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT2'

GO

DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'SALARY_OPTIONS_OPT5' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS] WHERE CODE = 'SALARY_OPTIONS_OPT5')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT5'), SID, VALUE FROM [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS] WHERE CODE = 'SALARY_OPTIONS_OPT5'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '401.20' FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT5'

GO

DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'SALARY_OPTIONS_OPT6' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS] WHERE CODE = 'SALARY_OPTIONS_OPT6')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT6'), SID, VALUE FROM [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS] WHERE CODE = 'SALARY_OPTIONS_OPT6'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '303.02' FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT6'

GO

DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'SALARY_OPTIONS_OPT7' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS] WHERE CODE = 'SALARY_OPTIONS_OPT7')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT7'), SID, VALUE FROM [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS] WHERE CODE = 'SALARY_OPTIONS_OPT7'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '303.06' FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT7'

GO

DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'SALARY_OPTIONS_OPT14' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS] WHERE CODE = 'SALARY_OPTIONS_OPT14')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT14'), SID, VALUE FROM [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS] WHERE CODE = 'SALARY_OPTIONS_OPT14'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '401.60' FROM  dbo.S_OBJECTS WHERE CODE = 'SALARY_OPTIONS_OPT14'

GO

IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_SALARY_OPTIONS_OPTIONS]

GO


/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPTIONS', 'Главный бухгалтер', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPTIONS', 'Смета-КС', 4,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPTIONS', 'Свод-КС', 5,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPTIONS', 'Зарплата-КС', 63,0
GO

/**************** УСТАНОВКА ДОСТУПА К НАСТРОЙКАМ *************/
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPT1', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPT2', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPT5', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPT6', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_OPTIONS_OPT7', 'Зарплата-КС', 63,0
GO


GO
/****** Объект: Форма № Т-51 (0301010) -  ф.0504402******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'SALARY_PAYROLL_FORMAT_T51')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'SALARY_PAYROLL_FORMAT_T51')
	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 = 'SALARY_PAYROLL_FORMAT_T51')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'SALARY_PAYROLL_FORMAT_T51')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SALARY_PAYROLL_FORMAT_T51'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SALARY_PAYROLL_FORMAT_T51')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SALARY_PAYROLL_FORMAT_T51')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SALARY_PAYROLL_FORMAT_T51', 'Форма №0504402', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_PAYROLL_FORMAT_CATALOG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='OUTPUT_FORMAT_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SALARY_PAYROLL_FORMAT_T51', NAME = 'Форма №0504402', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SALARY_PAYROLL_FORMAT_CATALOG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='OUTPUT_FORMAT_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SALARY_PAYROLL_FORMAT_T51'
GO
EXEC X_SET_PROP 'SALARY_PAYROLL_FORMAT_T51', 'TITLE', 'Расчетная ведомость(0504402)'
GO
EXEC X_SET_PROP 'SALARY_PAYROLL_FORMAT_T51', 'PRINT_OBJECT_METHOD', 'KIR_PRINT_PAYROLL_49(oForm)'
GO
EXEC X_SET_PROP 'SALARY_PAYROLL_FORMAT_T51', 'QUERY_REPMAKER', 'KirRepMakerMultiSheet.XLS'
GO
EXEC X_SET_PROP 'SALARY_PAYROLL_FORMAT_T51', 'QUERY_REPORT', 'F0504402.XLT'
GO
EXEC X_SET_PROP 'SALARY_PAYROLL_FORMAT_T51', 'QUERY_ADD_MODULE', 'KirRepT51.bas'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'SALARY_PAYROLL_FORMAT_T51', 'public', 5,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_PAYROLL_FORMAT_T51', 'Кадры-КС', 4,0
GO
EXEC DBO.W_SPERM_WRITE 'SALARY_PAYROLL_FORMAT_T51', 'Зарплата-КС', 63,0
GO


EXEC X_SET_PROP 'SALARY_PAYROLL_FORMAT_49', 'TITLE', 'Расчетно-платежная ведомость(0504401)'
GO

EXEC X_SET_PROP 'SALARY_PAYROLL_FORMAT_389', 'TITLE', 'Платежная ведомость(0504403)'
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='SAL_OPTIONS_INTEGRATION'

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_SAL_OPTIONS_INTEGRATION]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_SAL_OPTIONS_INTEGRATION]

CREATE TABLE  dbo._UPD_OPT_SAL_OPTIONS_INTEGRATION (CODE VARCHAR(30), [SID] varbinary(85), VALUE VARCHAR(1000))

INSERT INTO _UPD_OPT_SAL_OPTIONS_INTEGRATION (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 = 'SAL_OPTIONS_INTEGRATION')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[SDOC] D INNER JOIN [dbo].[S_OBJECTS] O ON D.[OBJECT] = O.[LINK] WHERE O.CODE = 'SAL_OPTIONS_INTEGRATION')
	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 = 'SAL_OPTIONS_INTEGRATION')
	AND NOT EXISTS( SELECT O.LINK FROM [dbo].[DICTION] C INNER JOIN [dbo].[S_OBJECTS] O ON C.[OBJECT] = O.[LINK] WHERE O.CODE = 'SAL_OPTIONS_INTEGRATION')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SAL_OPTIONS_INTEGRATION'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SAL_OPTIONS_INTEGRATION')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_OPTIONS_INTEGRATION')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_OPTIONS_INTEGRATION', 'Настройка интеграции ПК Зарплата-КС', 20, (SELECT LINK FROM S_OBJECTS WHERE CODE='NASTR_CATALOG'), (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'),1,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_OPTIONS_INTEGRATION', NAME = 'Настройка интеграции ПК Зарплата-КС', ORDERS = '20', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='NASTR_CATALOG'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='REFERENCE_RUN_LINK'), MANAGED = 1, INHERITED = 1
	WHERE CODE ='SAL_OPTIONS_INTEGRATION'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_OPT_INTEGR_CHANAL')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_OPT_INTEGR_CHANAL', 'Канал для передачи в ПК Смета-Смарт', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='SAL_OPTIONS_INTEGRATION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_OPT_INTEGR_CHANAL', NAME = 'Канал для передачи в ПК Смета-Смарт', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SAL_OPTIONS_INTEGRATION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_OPT_INTEGR_CHANAL'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_OPT_INTEGR_PROV_ZP_EXP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_OPT_INTEGR_PROV_ZP_EXP', 'Передача проводок по зарплате', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='SAL_OPTIONS_INTEGRATION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_OPT_INTEGR_PROV_ZP_EXP', NAME = 'Передача проводок по зарплате', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SAL_OPTIONS_INTEGRATION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_OPT_INTEGR_PROV_ZP_EXP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_OPT_INTEGR_KLASSIF_IMP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_OPT_INTEGR_KLASSIF_IMP', 'Прием классификаторов', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SAL_OPTIONS_INTEGRATION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_OPT_INTEGR_KLASSIF_IMP', NAME = 'Прием классификаторов', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SAL_OPTIONS_INTEGRATION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_OPT_INTEGR_KLASSIF_IMP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_OPT_INTEGR_IMP_KORR')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_OPT_INTEGR_IMP_KORR', 'Прием корреспондентов', 4, (SELECT LINK FROM S_OBJECTS WHERE CODE='SAL_OPTIONS_INTEGRATION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_OPT_INTEGR_IMP_KORR', NAME = 'Прием корреспондентов', ORDERS = '4', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SAL_OPTIONS_INTEGRATION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_OPT_INTEGR_IMP_KORR'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_OPT_INTEGR_KADR_EXP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_OPT_INTEGR_KADR_EXP', 'Передача кадровой информации', 5, (SELECT LINK FROM S_OBJECTS WHERE CODE='SAL_OPTIONS_INTEGRATION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_OPT_INTEGR_KADR_EXP', NAME = 'Передача кадровой информации', ORDERS = '5', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SAL_OPTIONS_INTEGRATION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_OPT_INTEGR_KADR_EXP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_OPT_INTEGR_PROV_PERECH_IMP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_OPT_INTEGR_PROV_PERECH_IMP', 'Прием проводок по перечислениям', 6, (SELECT LINK FROM S_OBJECTS WHERE CODE='SAL_OPTIONS_INTEGRATION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_OPT_INTEGR_PROV_PERECH_IMP', NAME = 'Прием проводок по перечислениям', ORDERS = '6', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SAL_OPTIONS_INTEGRATION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_OPT_INTEGR_PROV_PERECH_IMP'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SAL_OPT_INTEGR_PP_ZKR_EXP')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SAL_OPT_INTEGR_PP_ZKR_EXP', 'Передача ПП/ЗКР', 7, (SELECT LINK FROM S_OBJECTS WHERE CODE='SAL_OPTIONS_INTEGRATION'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SAL_OPT_INTEGR_PP_ZKR_EXP', NAME = 'Передача ПП/ЗКР', ORDERS = '7', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SAL_OPTIONS_INTEGRATION'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SAL_OPT_INTEGR_PP_ZKR_EXP'
GO
EXEC X_SET_PROP 'SAL_OPTIONS_INTEGRATION', 'INIT_OBJECT_METHOD', 'SALARY_FORM_LOAD(''sa_rms_contacts_options'')'
GO
EXEC X_SET_PROP 'SAL_OPT_INTEGR_CHANAL', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SAL_OPT_INTEGR_PROV_ZP_EXP', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SAL_OPT_INTEGR_PROV_ZP_EXP', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'SAL_OPT_INTEGR_KLASSIF_IMP', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SAL_OPT_INTEGR_KLASSIF_IMP', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'SAL_OPT_INTEGR_IMP_KORR', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SAL_OPT_INTEGR_IMP_KORR', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'SAL_OPT_INTEGR_KADR_EXP', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SAL_OPT_INTEGR_KADR_EXP', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'SAL_OPT_INTEGR_PROV_PERECH_IMP', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SAL_OPT_INTEGR_PROV_PERECH_IMP', 'TYPE_FIELD_DICT', 'TINYINT'
GO
EXEC X_SET_PROP 'SAL_OPT_INTEGR_PP_ZKR_EXP', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SAL_OPT_INTEGR_PP_ZKR_EXP', 'TYPE_FIELD_DICT', 'TINYINT'
GO
/******--Восстановить, либо установить настройки на базе пользователя ******/
DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'SAL_OPT_INTEGR_CHANAL' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_SAL_OPTIONS_INTEGRATION] WHERE CODE = 'SAL_OPT_INTEGR_CHANAL')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'SAL_OPT_INTEGR_CHANAL'), SID, VALUE FROM [dbo].[_UPD_OPT_SAL_OPTIONS_INTEGRATION] WHERE CODE = 'SAL_OPT_INTEGR_CHANAL'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '0' FROM  dbo.S_OBJECTS WHERE CODE = 'SAL_OPT_INTEGR_CHANAL'

GO

DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'SAL_OPT_INTEGR_KADR_EXP' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_SAL_OPTIONS_INTEGRATION] WHERE CODE = 'SAL_OPT_INTEGR_KADR_EXP')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'SAL_OPT_INTEGR_KADR_EXP'), SID, VALUE FROM [dbo].[_UPD_OPT_SAL_OPTIONS_INTEGRATION] WHERE CODE = 'SAL_OPT_INTEGR_KADR_EXP'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '0' FROM  dbo.S_OBJECTS WHERE CODE = 'SAL_OPT_INTEGR_KADR_EXP'

GO

DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'SAL_OPT_INTEGR_KLASSIF_IMP' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_SAL_OPTIONS_INTEGRATION] WHERE CODE = 'SAL_OPT_INTEGR_KLASSIF_IMP')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'SAL_OPT_INTEGR_KLASSIF_IMP'), SID, VALUE FROM [dbo].[_UPD_OPT_SAL_OPTIONS_INTEGRATION] WHERE CODE = 'SAL_OPT_INTEGR_KLASSIF_IMP'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '0' FROM  dbo.S_OBJECTS WHERE CODE = 'SAL_OPT_INTEGR_KLASSIF_IMP'

GO

DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'SAL_OPT_INTEGR_PP_ZKR_EXP' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_SAL_OPTIONS_INTEGRATION] WHERE CODE = 'SAL_OPT_INTEGR_PP_ZKR_EXP')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'SAL_OPT_INTEGR_PP_ZKR_EXP'), SID, VALUE FROM [dbo].[_UPD_OPT_SAL_OPTIONS_INTEGRATION] WHERE CODE = 'SAL_OPT_INTEGR_PP_ZKR_EXP'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '0' FROM  dbo.S_OBJECTS WHERE CODE = 'SAL_OPT_INTEGR_PP_ZKR_EXP'

GO

DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'SAL_OPT_INTEGR_PROV_PERECH_IMP' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_SAL_OPTIONS_INTEGRATION] WHERE CODE = 'SAL_OPT_INTEGR_PROV_PERECH_IMP')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'SAL_OPT_INTEGR_PROV_PERECH_IMP'), SID, VALUE FROM [dbo].[_UPD_OPT_SAL_OPTIONS_INTEGRATION] WHERE CODE = 'SAL_OPT_INTEGR_PROV_PERECH_IMP'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '0' FROM  dbo.S_OBJECTS WHERE CODE = 'SAL_OPT_INTEGR_PROV_PERECH_IMP'

GO

DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'SAL_OPT_INTEGR_PROV_ZP_EXP' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_SAL_OPTIONS_INTEGRATION] WHERE CODE = 'SAL_OPT_INTEGR_PROV_ZP_EXP')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'SAL_OPT_INTEGR_PROV_ZP_EXP'), SID, VALUE FROM [dbo].[_UPD_OPT_SAL_OPTIONS_INTEGRATION] WHERE CODE = 'SAL_OPT_INTEGR_PROV_ZP_EXP'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '0' FROM  dbo.S_OBJECTS WHERE CODE = 'SAL_OPT_INTEGR_PROV_ZP_EXP'

GO


IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_SAL_OPTIONS_INTEGRATION]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_SAL_OPTIONS_INTEGRATION]

GO


/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'SAL_OPTIONS_INTEGRATION', 'Зарплата-КС', 63,0
GO

/**************** УСТАНОВКА ДОСТУПА К НАСТРОЙКАМ *************/
EXEC DBO.W_SPERM_WRITE 'SAL_OPT_INTEGR_CHANAL', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SAL_OPT_INTEGR_KADR_EXP', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SAL_OPT_INTEGR_KLASSIF_IMP', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SAL_OPT_INTEGR_PP_ZKR_EXP', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SAL_OPT_INTEGR_PROV_PERECH_IMP', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SAL_OPT_INTEGR_PROV_ZP_EXP', 'Зарплата-КС', 63,0
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Настройка интеграции ПК Зарплата-КС"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SAL_INTEGR_SMETA_SMART_FOLDER' AND NAME = 'Интеграция с ПК Смета-Смарт')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SAL_OPTIONS_INTEGRATION')

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 = 'SAL_INTEGR_SMETA_SMART_FOLDER' AND NAME = 'Интеграция с ПК Смета-Смарт'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'NV_SAL_OPTIONS_INTEGRATION'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'NV_SAL_OPTIONS_INTEGRATION', 'Настройка интеграции ПК Зарплата-КС', @ORD, NULL, 1, @LINK_SELF, 'NASTR', @OBJECT, @LINK_VAR, 3
GO


GO
EXEC X_SET_PROP 'SAL_SFIN_CODE', 'TYPE_FIELD_DICT', 'VARCHAR(30)'
GO

GO
/****** Объект: Имущественные налоговые вычеты******/

UPDATE DBO.S_OBJECTS
SET CODE = 'SA_PROPERTY_TAX_DEDUCTIONS', NAME = 'Имущественные и социальные налоговые вычеты', ORDERS = '27', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='CATALOG_DICT_SALARY'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='DICTIONARY_CLASS'), MANAGED = 1, INHERITED = 1
WHERE CODE ='SA_PROPERTY_TAX_DEDUCTIONS'
GO

EXEC X_SET_PROP 'SA_PROPERTY_TAX_DEDUCTIONS', 'TITLE', 'Справочник имущественных и социальных налоговых вычетов'
GO

/**************** ДОБАВЛЕНИЕ В НАВИГАТОР ОБЪЕКТА "Имущественные и социальные налоговые вычеты"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SET @LINK_SELF = (SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = '4227' AND NAME = 'ДОКУМЕНТЫ')

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SA_PROPERTY_TAX_DEDUCTIONS')

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 = '4227' AND NAME = 'ДОКУМЕНТЫ'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'SA_PROPERTY_TAX_DEDUCTIONS'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'SA_PROPERTY_TAX_DEDUCTIONS', 'Имущественные и социальные налоговые вычеты', @ORD, NULL, 1, @LINK_SELF, 'DOCUMENT', @OBJECT, @LINK_VAR, 3
GO


GO
-- Отчет "Реестр приказов на отпуск"
-- Сгенерировано скриптом scriptObjectVar 'SA_REP_VACATION_REESTR'

/*** Сам отчет ***/

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= 'SA_REP_VACATION_REESTR'  

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'SA_REP_VACATION_REESTR'
	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'),
	'SA_REP_VACATION_REESTR',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'SA_REP_VACATION_REESTR') 
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'exec SA_REP_VACATION_OR_TRAVEL_REESTR 	''VACATION'', @dDateB1, @dDateE1,null, @nOption1'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#SA_REP_VACATION_REESTR'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.t.,"SA_VACATION_OR_TRAVEL_REESTR.xlt","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #SA_REP_VACATION_REESTR
	@dDateB1 datetime	/* Начало периода */,
	@dDateE1 datetime	/* Конец периода */,
	@nOption1 int	/* Вывод информации */
AS
BEGIN

exec SA_REP_VACATION_OR_TRAVEL_REESTR 	''VACATION'', @dDateB1, @dDateE1,null, @nOption1

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	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 = 'SA_REP_VACATION_REESTR') 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 = 'SA_REP_VACATION_REESTR'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SA_REP_VACATION_REESTR0' 
		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 = 'SA_REP_VACATION_REESTR'),
		'SA_REP_VACATION_REESTR0',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SA_REP_VACATION_REESTR1' 
					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'),
					'Начало периода',2, 
					(Select link from object_var where code = 'SA_REP_VACATION_REESTR0'),
					'SA_REP_VACATION_REESTR1',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 = 'SA_REP_VACATION_REESTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR1'),
							(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 = 'SA_REP_VACATION_REESTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR1'),
							(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 = 'SA_REP_VACATION_REESTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR1'),
							(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 = 'SA_REP_VACATION_REESTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR1'),
							(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 = 'SA_REP_VACATION_REESTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR1'),
							(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 = 'SA_REP_VACATION_REESTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR1'),
							(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 = 'SA_REP_VACATION_REESTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR1'),
							(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 = 'SA_REP_VACATION_REESTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR1'),
							(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 = 'SA_REP_VACATION_REESTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR1'),
							(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 = 'SA_REP_VACATION_REESTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR1'),
							(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 = 'SA_REP_VACATION_REESTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR1'),
							(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 = 'SA_REP_VACATION_REESTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR1'),
							(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 = 'SA_REP_VACATION_REESTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR1'),
							(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 = 'SA_REP_VACATION_REESTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR1'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SA_REP_VACATION_REESTR2' 
					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'),
					'Конец периода',3, 
					(Select link from object_var where code = 'SA_REP_VACATION_REESTR0'),
					'SA_REP_VACATION_REESTR2',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 = 'SA_REP_VACATION_REESTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR2'),
							(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 = 'SA_REP_VACATION_REESTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR2'),
							(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 = 'SA_REP_VACATION_REESTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR2'),
							(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 = 'SA_REP_VACATION_REESTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR2'),
							(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 = 'SA_REP_VACATION_REESTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR2'),
							(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 = 'SA_REP_VACATION_REESTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR2'),
							(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 = 'SA_REP_VACATION_REESTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR2'),
							(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 = 'SA_REP_VACATION_REESTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR2'),
							(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 = 'SA_REP_VACATION_REESTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR2'),
							(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 = 'SA_REP_VACATION_REESTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR2'),
							(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 = 'SA_REP_VACATION_REESTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR2'),
							(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 = 'SA_REP_VACATION_REESTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR2'),
							(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 = 'SA_REP_VACATION_REESTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR2'),
							(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 = 'SA_REP_VACATION_REESTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SA_REP_VACATION_REESTR3' 
					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'),
					'Вывод информации',4, 
					(Select link from object_var where code = 'SA_REP_VACATION_REESTR0'),
					'SA_REP_VACATION_REESTR3',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 = 'SA_REP_VACATION_REESTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR3'),
							(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 = 'SA_REP_VACATION_REESTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR3'),
							(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 = 'SA_REP_VACATION_REESTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR3'),
							(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 = 'SA_REP_VACATION_REESTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR3'),
							(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 = 'SA_REP_VACATION_REESTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR3'),
							(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 = 'SA_REP_VACATION_REESTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR3'),
							(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 = 'SA_REP_VACATION_REESTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR3'),
							(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 = 'SA_REP_VACATION_REESTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR3'),
							(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 = 'SA_REP_VACATION_REESTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR3'),
							(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 = 'SA_REP_VACATION_REESTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR3'),
							(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 = 'SA_REP_VACATION_REESTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR3'),
							(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 = 'SA_REP_VACATION_REESTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR3'),
							(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 = 'SA_REP_VACATION_REESTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR3'),
							(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 = 'SA_REP_VACATION_REESTR3') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SA_REP_VACATION_REESTR3'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO


GO
--- Вычеты и МРОТ
declare @PERIOD datetime

SET @PERIOD = coalesce((select Max(PERIOD) from minrot),'20000101')
IF @PERIOD < '20160101'
BEGIN
	declare @P1 int, @LINK_DED INT
				
	DECLARE @Object int, @LinkDep int
	SELECT @Object = LINK FROM dbo.S_OBJECTS WHERE CODE = 'COLUMN_REF_PAY_MROT_T1'
	SELECT @LinkDep = LINK FROM dbo.DICTIONARY_DEPARTMENT WHERE TYPE = 4
	
	Declare @nRKoef numeric(18,2), @KOEF_BL numeric(18,2), @TARIF numeric(18,2), @MROT1 numeric(18,2)
	/*прежние значения*/
	select top 1 @MROT1 =MROT1, @TARIF = TARIF, @nRKoef = KOEF, @KOEF_BL = KOEF_BL from dbo.MINROT order by PERIOD desc

	Select @MROT1 = COALESCE(@MROT1,100), @TARIF = COALESCE(@TARIF,2300), @nRKoef = COALESCE(@nRKoef,1), @KOEF_BL = COALESCE(@KOEF_BL,1)


	set @P1 = 0
	exec SALARY_SAVE_DICTIONARY_MROT @P1 output, 
			/*начало периода*/'20160101', 
			/*МРОТ общий*/@MROT1, 
			/*МРОТ для зарплаты*/6204, 
			/*Ставка первого разряда*/@TARIF, 
			/*Районный коэффициент*/@nRKoef, 
			/*Районный коэффициент для Б/Л*/@KOEF_BL, 
					@LinkDep

	IF COALESCE(@Object,0) > 0 AND COALESCE(@P1,0) > 0 BEGIN
		-- Заполняем первую вкладку
		
		SELECT TOP 1  @LINK_DED = LINK   FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '103'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,4000,400)
		
		SELECT TOP 1  @LINK_DED = LINK   FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '104'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,0,500)

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '105'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,0,3000)
	--
		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '114'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,350000,1400)

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '115'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,350000,1400)
			
		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '116'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,350000,3000)

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '117'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,350000,6000)
	--
		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '118'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,350000,2800)
		
		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '119'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,350000,2800)
			
		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '120'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,350000,6000)

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '121'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,350000,12000)			
	--
		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '122'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,350000,2800)

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '123'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,350000,2800)

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '124'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,350000,6000)

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '125'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,350000,12000)									

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '313'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,0,2000000)				

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '501'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,0,4000)				

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '502'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,0,4000)				

		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '503'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,0,4000)				
	
		SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '602'
		IF COALESCE(@LINK_DED,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P1,@LINK_DED,@Object,12000,0)	


	END

	-- Заполняем вторую вкладку
	SELECT TOP 1  @LINK_DED = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '503'
	IF COALESCE(@P1,0) > 0 AND COALESCE(@LINK_DED,0) > 0 
		EXEC SALARY_SAVE_DICTIONARY_MROT_TABLE2 @P1, @LINK_DED, 4000


	
	-- Заполняем третью вкладку
	
	DECLARE @FSS12 int

	SELECT TOP 1 @FSS12 = LINK FROM PAYS WHERE OBJECT = 3 AND WAY_CALC = 5

	IF COALESCE(@P1,0) > 0 BEGIN
		IF COALESCE(@FSS12,0) > 0
			exec SALARY_SAVE_DICTIONARY_MROT_TABLE3 @P1, @FSS12, 0, 0.12
	END


END   

IF @PERIOD = '20160101'
BEGIN

	declare @P2 int, @LINK_DED1 INT
	DECLARE @Object1 int
	SELECT @Object1 = LINK FROM dbo.S_OBJECTS WHERE CODE = 'COLUMN_REF_PAY_MROT_T1'


	SET @P2 = (select TOP 1 link from minrot where period = @PERIOD)
	
	IF COALESCE(@Object1,0) > 0 AND COALESCE(@P2,0) > 0 BEGIN
		-- Заполняем первую вкладку

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '104'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 500 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '105'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 3000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

	--
		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '114'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 1400 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '115'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 1400 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1
			
		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '116'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 3000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '117'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 6000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

	--
		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '118'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 2800 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

		
		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '119'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 2800 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1
			
		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '120'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 6000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '121'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 12000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1
	
	--
		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '122'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 2800 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '123'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 2800 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '124'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 6000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1		

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '125'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 12000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1		

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '313'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 2000000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1		

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '501'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 4000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1		

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '502'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 4000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1		

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '503'
		IF COALESCE(@LINK_DED1,0) > 0 
		Update m
			set SUMMA = 4000 
		from MINROT_DICTION  m  where LINK_MINROT = @P2 and LINK_DICTION = @LINK_DED1 and OBJECT = @Object1		

		SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '602'
		IF COALESCE(@LINK_DED1,0) > 0 
		BEGIN 
			IF exists (select * from MINROT_DICTION where LINK_DICTION = @LINK_DED1 and LINK_MINROT = @p2)
			DELETE FROM MINROT_DICTION WHERE LINK_DICTION = @LINK_DED1 and LINK_MINROT = @p2

			SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '602'
			IF COALESCE(@LINK_DED1,0) > 0 
			INSERT INTO MINROT_DICTION (LINK_MINROT,LINK_DICTION,OBJECT,PREDEL,SUMMA)
			VALUES(@P2,@LINK_DED1,@Object1,12000,0)	
		END
	END

	-- Заполняем вторую вкладку
	SELECT TOP 1  @LINK_DED1 = LINK FROM  dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '503'
	IF COALESCE(@P2,0) > 0 AND COALESCE(@LINK_DED1,0) > 0 
		EXEC SALARY_SAVE_DICTIONARY_MROT_TABLE2 @P2, @LINK_DED1, 4000
	-- Заполняем третью вкладку
	
	DECLARE @FSS12_1 int

	SELECT TOP 1 @FSS12_1 = LINK FROM PAYS WHERE OBJECT = 3 AND WAY_CALC = 5

	IF COALESCE(@P2,0) > 0 BEGIN
		IF COALESCE(@FSS12_1,0) > 0
			exec SALARY_SAVE_DICTIONARY_MROT_TABLE3 @P2, @FSS12_1, 0, 0.12
	END

END

GO
GO

---- Установка видов страховых взносов
DECLARE @LINK_OBJ INT
SET @LINK_OBJ = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS SO WHERE SO.CODE = 'COLUMN_REF_PAY_MROT_T4')

if exists (SELECT * FROM MINROT_PAYS WHERE  [OBJECT] = @LINK_OBJ AND link_minrot IN (SELECT LINK FROM  dbo.MINROT WHERE PERIOD >= '20160101' AND   PERIOD < '20990101'))
DELETE FROM MINROT_PAYS WHERE  [OBJECT] = @LINK_OBJ AND link_minrot IN (SELECT LINK FROM  dbo.MINROT 
                                                                               WHERE PERIOD >= '20160101'
                                                                               AND   PERIOD < '20990101')
GO

DECLARE @LINK_OBJ INT
SET @LINK_OBJ = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS SO WHERE SO.CODE = 'COLUMN_REF_PAY_MROT_T4')

INSERT INTO dbo.MINROT_PAYS (LINK_MINROT, LINK_PAYS, OBJECT)
SELECT M.LINK, P.LINK, @LINK_OBJ 
FROM dbo.MINROT M INNER JOIN dbo.PAYS P ON 1=1
WHERE 
	M.PERIOD >= '20160101'
	AND
	M.PERIOD < '20990101'
	AND
	P.[OBJECT] = 3 AND P.WAY_CALC IN (2,3, 6)
	AND
	NOT EXISTS (SELECT * FROM dbo.DICTIONARY_MROT_TABLE4 T4 WHERE T4.LINK_MINROT = M.LINK AND T4.REF_PAY = P.LINK)
ORDER BY
	M.LINK, P.LINK
GO


DECLARE @LINK_OBJ INT
SET @LINK_OBJ = (SELECT TOP 1 LINK FROM dbo.S_OBJECTS SO WHERE SO.CODE = 'COLUMN_REF_PAY_MROT_T4')

INSERT INTO dbo.MINROT_PAYS (LINK_MINROT, LINK_PAYS, OBJECT)
SELECT M.LINK, P.LINK, @LINK_OBJ 
FROM dbo.MINROT M INNER JOIN dbo.PAYS P ON 1=1
WHERE 
	M.PERIOD >= '20160101'
	AND
	M.PERIOD < '20990101'
	AND
	P.[OBJECT] = 3 AND P.WAY_CALC IN (10, 11)
	AND
	NOT EXISTS (SELECT * FROM dbo.DICTIONARY_MROT_TABLE4 T4 WHERE T4.LINK_MINROT = M.LINK AND T4.REF_PAY = P.LINK)
ORDER BY
	M.LINK, P.LINK
		
GO



GO

--Обновление настроек 2016 года
exec dbo.SA_SET_STATIC_NASTR '2016'
GO

------------------------------------Графики перенесли из статических настроек----------------------------------------------------------------------------------
/**Производственный график на 2014 год убран из установки фиксированных настроек , теперь ведется история */
DECLARE @YEAR INT , @TD_LINK INT, @TITLE VARCHAR(254)
--- Для баз, которые еще не устанавливали фиксированные настройки
IF EXISTS( SELECT * FROM HOLIDAYS WHERE [YEAR] = 1900  )
	UPDATE HOLIDAYS SET   [YEAR] = 2015 	
	WHERE [YEAR] = 1900 
---------------------------------------------------------------
SET @YEAR = '2014' 
--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ

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

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

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

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

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

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

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

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

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

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

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



/*Производственный график на 2015 год  убран из установки фиксированных настроек , теперь ведется история*/
		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
SET @YEAR = '2015' 		
IF NOT EXISTS ( select * from HOLIDAYS WHERE [year] = @YEAR )
begin

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

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

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

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


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

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

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

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

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

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

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

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

END

/*Производственный график на 2016 год убран из установки фиксированных настроек , теперь ведется история*/
SET @YEAR = '2016' 		
IF NOT EXISTS ( select * from HOLIDAYS WHERE [year] = @YEAR )
begin
	--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРАЗДНИЧНЫХ ДНЕЙ
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL,[YEAR])
			SELECT	'1 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 1, 1, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'2 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 2, 1, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'3 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 3, 1, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'4 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 4, 1, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'5 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 5, 1, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'6 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 6, 1, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'7 ЯНВАРЯ (РОЖДЕСТВО ХРИСТОВО)', 7, 1, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'8 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 8, 1, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'23 ФЕВРАЛЯ (ДЕНЬ ЗАЩИТНИКА ОТЕЧЕСТВА)', 23, 2, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'8 МАРТА (МЕЖДУНАРОДНЫЙ ЖЕНСКИЙ ДЕНЬ)', 8, 3, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'1 МАЯ (ПРАЗДНИК ВЕСНЫ И ТРУДА)', 1, 5, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'9 МАЯ (ДЕНЬ ПОБЕДЫ)', 9, 5, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'12 ИЮНЯ (ДЕНЬ РОССИИ)', 12, 6, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'4 НОЯБРЯ (ДЕНЬ НАРОДНОГО ЕДИНСТВА)', 4, 11, @TD_LINK, 1,@YEAR

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

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

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРЕДПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB = 'П')
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРЕДПРАЗДНИЧНЫХ ДНЕЙ ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1,[YEAR])
			SELECT	'20 ФЕВРАЛЯ', 20, 2, @TD_LINK, 2, NULL, NULL,@YEAR
			UNION ALL
			SELECT	'3 НОЯБРЯ', 3, 11, @TD_LINK, 2, NULL, NULL,@YEAR

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

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

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

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

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

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

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

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

GO

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

/*Формирование всех используемых графиков на 2016 год*/
DECLARE @Cur1 CURSOR, @LinkGrophik int, @VID_LINK int, @NAME_GR varchar(254)
DECLARE @Cur2 CURSOR, @DAY tinyint, @HOUR numeric(18,2), @TD_LINK int

DECLARE @MONTH INT, @YEAR INT
DECLARE @LINK INT, @LINK2 INT, @gDayNorm INT, @gHourNorm numeric(18,2)

DECLARE @ISMINUTES TINYINT
SET @ISMINUTES = DBO.SA_GET_OPTION_BY_CODE('TABEL_OPT10') --УЧЕТ ВРЕМЕНИ В ЧАСАХ И МИНУТАХ

SET @Cur1 = CURSOR FORWARD_ONLY

FOR select LINK, VID_LINK, [NAME] from GRAPH order by link
OPEN @Cur1
FETCH NEXT FROM @Cur1 INTO @LinkGrophik, @VID_LINK, @NAME_GR
WHILE (@@fetch_status <> -1)
BEGIN
	IF (@@fetch_status <> -2)
	BEGIN

		SELECT @YEAR = 2016, @MONTH = 1
		WHILE @MONTH <= 12
		BEGIN

			IF NOT EXISTS(SELECT @LinkGrophik FROM dbo.KD_GRAPH_TABLE WHERE [YEAR] = @YEAR AND [MONTH] = @MONTH AND LINK_GR = @LinkGrophik)
			BEGIN
				IF object_id('tempdb..#sa_tmp_graph') is not null
				drop table #sa_tmp_graph
				
				CREATE TABLE #sa_tmp_graph(CHECKED tinyint, UPD tinyint, DEL tinyint, [DAY] tinyint, [HOUR] numeric(18,2), TD_LINK int, TD_CODE varchar(10),
						TD_NAME varchar(254), PRIORITET tinyint )
				
				INSERT INTO #sa_tmp_graph(CHECKED, UPD, DEL, [DAY], [HOUR], TD_LINK, TD_CODE, TD_NAME, PRIORITET)
				exec dbo.KD_GRAPH_FILL @VID_LINK, @MONTH, @YEAR
				
				Select @gHourNorm = DBO.MINUTES_TO_NUM(SUM(DBO.NUM_TO_MINUTES([HOUR],@ISMINUTES)),@ISMINUTES) from #sa_tmp_graph where [HOUR] > 0
				Select @gDayNorm = COUNT(DISTINCT [DAY]) from #sa_tmp_graph where [HOUR] > 0
				
				IF COALESCE(@gHourNorm,0) > 0 AND coalesce(@gDayNorm,0) > 0
				BEGIN
				
					EXEC dbo.KD_GRAPH_SAVE @LinkGrophik OUT, @LINK2 OUT, @NAME_GR, @MONTH, @YEAR, @VID_LINK, @gDayNorm, @gHourNorm
		
					SET @Cur2 = CURSOR FORWARD_ONLY
					
					FOR select [DAY], [HOUR], [TD_LINK] from #sa_tmp_graph order by [DAY]
					OPEN @Cur2
					FETCH NEXT FROM @Cur2 INTO @DAY, @HOUR, @TD_LINK
					WHILE (@@fetch_status <> -1)
					BEGIN
						IF (@@fetch_status <> -2)
						BEGIN
							exec dbo.KD_GRAPH_TABLE_SAVE @LINK2, @DAY, @HOUR, @TD_LINK
						END
					
						FETCH NEXT FROM @Cur2 INTO @DAY, @HOUR, @TD_LINK
					END
					
					CLOSE @Cur2
					DEALLOCATE @Cur2
				END
			END

			Set @MONTH = @MONTH + 1
		END
		
	END
	FETCH NEXT FROM @Cur1 INTO @LinkGrophik, @VID_LINK, @NAME_GR
END

CLOSE @Cur1
DEALLOCATE @Cur1
GO




/*НАСТРОЙКИ ТАРИФОВ  2016 ГОДА*/


--Общий (НР)
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 2 --Фонд Социального Страхования
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20160101' and predel = 718000 AND TARIF = 1),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20160101','ФСС РФ',718000, 2.9, 1

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20160101','ФСС РФ',999999999, 0, 1
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 3 --Федеральный фонд медицинского страхования
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20160101','ФФОМС',999999999, 5.1, 1
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 6 --ПФ Страховая часть
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF = 1),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','ПФ Страховая часть',796000, 22, 22, 22, 1

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','ПФ Страховая часть',999999999, 10, 10, 10, 1
GO


--- солидарную часть убераем
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 8 --ПФ Солидарная часть
IF EXISTS (select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF = 1)
DELETE  FROM dbo.stavki_pf WHERE link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF = 1

IF EXISTS (select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1)
DELETE  FROM dbo.stavki_pf WHERE link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1
GO

--- Индивидуальную часть убераем
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 9 --ПФ Индивидуальная часть
IF exists(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF = 1)
DELETE  FROM dbo.stavki_pf WHERE link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF = 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)
DELETE  FROM dbo.stavki_pf WHERE link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1
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 
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','ПФ Доп.тариф №1',999999999,  9, 9, 9, 1
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 
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','ПФ Доп.тариф №2',999999999, 6, 6, 6, 1
GO

--Инвалиды (ОЗОИ)
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 2 --Фонд Социального Страхования
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20160101' and predel = 718000 AND TARIF = 3),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20160101','ФСС РФ',718000, 2.4, 3

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20160101','ФСС РФ',999999999, 0, 3
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 3 --Федеральный фонд медицинского страхования
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20160101','ФФОМС',999999999, 3.7, 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 = 6 --ПФ Страховая часть
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF = 3),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','ПФ Страховая часть',796000, 21, 21, 21, 3

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','ПФ Страховая часть',999999999, 0, 0, 0, 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 = 8 --ПФ Солидарная часть
IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF = 3)							/* 415000  */
delete from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF = 3

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3)
delete from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 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 = 9 --ПФ Индивидуальная часть
IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF = 3)								/* 415000  */
delete from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF = 3

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3)
delete from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 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 
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','ПФ Доп.тариф №1',999999999,  9, 9, 9, 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 
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','ПФ Доп.тариф №2',999999999, 6, 6, 6, 3
GO




--Упрощён. (ПНЭД)
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 2 --Фонд Социального Страхования
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20160101' and predel = 718000 AND TARIF = 2),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20160101','ФСС РФ',718000, 2.9, 2

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20160101','ФСС РФ',999999999, 0, 2
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 3 --Федеральный фонд медицинского страхования
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20160101','ФФОМС',999999999, 5.1, 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 = 6 --ПФ Страховая часть
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF = 2),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','ПФ Страховая часть',796000, 21.6, 21.6, 21.6, 2

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','ПФ Страховая часть',999999999, 10, 10, 10, 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 = 8 --ПФ Солидарная часть
IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF = 2)								/* 711000  */
DELETE FROM dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF = 2

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2)
DELETE FROM dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 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 = 9 --ПФ Индивидуальная часть
IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF =2)								/* 711000  */
DELETE from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF =2

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2)
delete from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 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 
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2  ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','ПФ Доп.тариф №1',999999999,  9, 9, 9, 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 
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2  ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','ПФ Доп.тариф №2',999999999, 6, 6, 6, 2
GO


--СМИ. (СМИ)
DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 2 --Фонд Социального Страхования
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20160101' and predel = 718000 AND TARIF = 4),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20160101','ФСС РФ',718000, 2.9, 4

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20160101','ФСС РФ',999999999, 0, 4
GO

DECLARE @link_pays int, @p1 INT
SELECT TOP 1 @link_pays = LINK FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 3 --Федеральный фонд медицинского страхования
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI @p1 output,@link_pays,'20160101','ФФОМС',999999999, 3.9, 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 = 6 --ПФ Страховая часть
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF = 4),0)
exec dbo.SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','ПФ Страховая часть',796000, 23.2, 23.2, 23.2, 4

SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','ПФ Страховая часть',999999999, 0, 0,0, 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 = 8 --ПФ Солидарная часть
IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF = 4)								/* 415000  */
DELETE FROM dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF = 4

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4)
DELETE FROM dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 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 = 9 --ПФ Индивидуальная часть
IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF =4)								/* 415000  */
DELETE from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 796000 AND TARIF =4

IF EXISTS(select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4)
delete from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 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 
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4  ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','ПФ Доп.тариф №1',999999999,  9, 9, 9, 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 
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4  ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','ПФ Доп.тариф №2',999999999, 6, 6, 6, 4
GO



/*НАСТРОЙКИ ДОП ТАРИФОВ  2015 ГОДА Со спец оценкой*/

------------------------<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
--Общий (НР)
----------------------------
DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1 со спецоценкой "О4"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'О4'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  8, 8, 8, 1,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1 со спецоценкой "В3.4"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.4'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  7, 7, 7, 1,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1 со спецоценкой "В3.3"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.3'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  6, 6, 6, 1,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1 со спецоценкой "В3.2"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.2'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  4, 4, 4, 1,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1 со спецоценкой "В3.1"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.1'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  2, 2, 2, 1,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "О4"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'О4'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 8, 8, 8, 1,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 -- Дополнительный тариф страхового взноса в ПФ 1 со спецоценкой "В3.4"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.4'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999,  7, 7, 7, 1,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 -- Дополнительный тариф страхового взноса в ПФ 1 со спецоценкой "В3.3"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.3'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 6, 6, 6, 1,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 -- Дополнительный тариф страхового взноса в ПФ 1 со спецоценкой "В3.2"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.2'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 4, 4, 4, 1,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 -- Дополнительный тариф страхового взноса в ПФ 1 со спецоценкой "В3.1"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.1'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 1 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999,  2, 2, 2, 1,@specO
GO
---------------------------------------
--Инвалиды (ОЗОИ)
---------------------------------------
DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1 со спецоценкой "О4"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'О4'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  8, 8, 8, 3,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1 со спецоценкой "В3.4"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.4'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  7, 7, 7, 3,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1 со спецоценкой "В3.3"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.3'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  6, 6, 6, 3,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1 со спецоценкой "В3.2"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.2'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  4, 4, 4, 3,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10 -- Дополнительный тариф страхового взноса в ПФ 1 со спецоценкой "В3.1"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.1'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  2, 2, 2, 3,@specO
GO


DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "О4"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'О4'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 8, 8, 8, 3,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.4"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.4'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 7, 7, 7, 3,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.3"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.3'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 6, 6, 6, 3,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.2"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.2'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 4, 4, 4, 3,@specO
GO

DECLARE @link_pays int, @p1 INT,@specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11 --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.1"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.1'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 3 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 2, 2, 2, 3,@specO
GO
---------------------------------
--Упрощён. (ПНЭД)
----------------------------------
DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10  -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "О4"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'О4'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  8, 8, 8, 2,@specO
GO

DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10  -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.4"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.4'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  7, 7, 7, 2,@specO
GO

DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10  -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.3"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.3'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  6, 6, 6, 2,@specO
GO

DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10  -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.2"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.2'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  4, 4, 4, 2,@specO
GO

DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10  -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.1"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.1'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  2, 2, 2, 2,@specO
GO



DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11  --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "О4"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'О4'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 8, 8, 8, 2,@specO
GO

DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11  --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.4"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.4'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 7, 7, 7, 2,@specO
GO

DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11  --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.3"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.3'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 6, 6, 6, 2,@specO
GO

DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11  --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.2"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.2'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 4, 4, 4, 2,@specO
GO

DECLARE @link_pays int, @p1 INT , @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11  --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.1"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.1'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 2 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 2, 2, 2, 2, @specO
GO


---------------------------------
--СМИ. (СМИ)
----------------------------------
DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10  -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "О4"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'О4'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4 AND SpecO = @specO),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  8, 8, 8, 4,@specO
GO

DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10  -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.4"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.4'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  7, 7, 7, 4,@specO
GO

DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10  -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.3"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.3'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  6, 6, 6, 4,@specO
GO

DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10  -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.2"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.2'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  4, 4, 4, 4,@specO
GO

DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 10  -- Дополнительный тариф страхового взноса в ПФ 1  со спецоценкой "В3.1"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.1'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №1',999999999,  2, 2, 2, 4,@specO
GO



DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11  --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "О4"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'О4'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 8, 8, 8, 4,@specO
GO

DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11  --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.4"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.4'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 7, 7, 7, 4,@specO
GO

DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11  --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.3"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.3'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 6, 6, 6, 4,@specO
GO

DECLARE @link_pays int, @p1 INT, @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11  --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.2"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.2'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 4, 4, 4, 4,@specO
GO

DECLARE @link_pays int, @p1 INT , @specO INT 
SELECT TOP 1 @link_pays = LINK, @p1 = 0 FROM dbo.PAYS WHERE OBJECT = 3 AND WAY_CALC = 11  --Дополнительный тариф страхового взноса в ПФ 2 со спецоценкой "В3.1"
SELECT @specO = link FROM SA_SZV4_SPR WHERE spr_code = 'SPO_USL_TRUDA' AND CODE = 'В3.1'
SET @p1 = ISNULL((select TOP 1 LINK from dbo.stavki_pf where link_pays = @link_pays and date = '20160101' and predel = 999999999 AND TARIF = 4 AND SpecO = @specO ),0)
exec SALARY_SAVE_DICTIONARY_STAVKI_PF @p1 output,@link_pays,'20160101','Доп.тариф ПФ по списку №2',999999999, 2, 2, 2, 4, @specO
GO

GO
-------------------------------------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>





--
--DECLARE @LINK INT
--SET @LINK = (SELECT TOP 1 LINK FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '201')
--exec dbo.X_SAVE_DICTIONARY_TYP_DEDUCTION 
--	@LINK,'201',
--	'Расходы по операциям с ценными бумагами, обращающимися на организованном рынке ценных бумаг',
--	'201', 3, 0
--GO
----
--DECLARE @LINK INT
--SET @LINK = (SELECT TOP 1 LINK FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '202')
--exec dbo.X_SAVE_DICTIONARY_TYP_DEDUCTION 
--	@LINK,'202',
--	'Расходы по операциям с ценными бумагами, не обращающимися на организованном рынке ценных бумаг',
--	'202', 3, 0
--GO
----
--DECLARE @LINK INT
--SET @LINK = (SELECT TOP 1 LINK FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '203')
--exec dbo.X_SAVE_DICTIONARY_TYP_DEDUCTION 
--	@LINK,'203',
--	'Расходы по операциям с ценными бумагами, не обращающимися на организованном рынке ценных бумаг, которые на момент их приобретения относились к ценным бумагам, обращающимся на организованном рынке ценных бумаг',
--	'203', 3, 0
--GO
----
--DECLARE @LINK INT
--SET @LINK = (SELECT TOP 1 LINK FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '204')
--exec dbo.X_SAVE_DICTIONARY_TYP_DEDUCTION 
--	@LINK,'204',
--	'Сумма убытка по операциям с ценными бумагами, не обращающимися на организованном рынке ценных бумаг',
--	'204', 3, 0
--GO
----
--DECLARE @LINK INT
--SET @LINK = (SELECT TOP 1 LINK FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '205')
--exec dbo.X_SAVE_DICTIONARY_TYP_DEDUCTION 
--	@LINK,'205',
--	'Сумма убытка по операциям с ценными бумагами, обращающимися на организованном рынке ценных бумаг',
--	'205', 3, 0
--GO
----
--DECLARE @LINK INT
--SET @LINK = (SELECT TOP 1 LINK FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '206')
--exec dbo.X_SAVE_DICTIONARY_TYP_DEDUCTION 
--	@LINK,'206',
--	'Расходы по операциям с финансовыми инструментами срочных сделок, которые обращаются на организованном рынке и базисным активом которых являются ценные бумаги и т.д.',
--	'206', 3, 0
--GO
----
--DECLARE @LINK INT
--SET @LINK = (SELECT TOP 1 LINK FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '207')
--exec dbo.X_SAVE_DICTIONARY_TYP_DEDUCTION 
--	@LINK,'207',
--	'Расходы по операциям с финансовыми инструментами срочных сделок, которые обращаются на организованном рынке и базисным активом которых не являются ценные бумаги  т.д.',
--	'207', 3, 0
--GO
----
--DECLARE @LINK INT
--SET @LINK = (SELECT TOP 1 LINK FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '208')
--exec dbo.X_SAVE_DICTIONARY_TYP_DEDUCTION 
--	@LINK,'208',
--	'Сумма убытка (уменьшающая налоговую базу по операциям с ценными бумагами) по операциям с финансовыми инструментами срочных сделок, которые обращаются на организованном рынке и базисным активом которых являются ценные бумаги и т.д.',
--	'208', 3, 0
--GO
----
--DECLARE @LINK INT
--SET @LINK = (SELECT TOP 1 LINK FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '209')
--exec dbo.X_SAVE_DICTIONARY_TYP_DEDUCTION 
--	@LINK,'209',
--	'Сумма убытка (уменьшающая налоговую базу по операциям с финансовыми инструментами срочных сделок) по операциям с финансовыми инструментами срочных сделок, которые обращаются на организованном рынке и базисным активом которых не являются ценные бумаги и т.д.',
--	'209', 3, 0
--GO

----
--DECLARE @LINK INT
--SET @LINK = (SELECT TOP 1 LINK FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '311')
--exec dbo.X_SAVE_DICTIONARY_TYP_DEDUCTION 
--	@LINK,'311',
--	'Расходы на новое строительство и приобретение жилья',
--	'311', 4, 0
--GO

----
--DECLARE @LINK INT
--SET @LINK = ISNULL((SELECT TOP 1 LINK FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '318'),0)
--exec dbo.X_SAVE_DICTIONARY_TYP_DEDUCTION 
--	@LINK,'318',
--	'Сумма, направленная на погашение процентов по кредитам, полученным от банков в целях рефинансирования (перекредитования) кредитов',
--	'318', 4, 0
--GO
----
--DECLARE @LINK INT
--SET @LINK = ISNULL((SELECT TOP 1 LINK FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '319'),0)
--exec dbo.X_SAVE_DICTIONARY_TYP_DEDUCTION 
--	@LINK,'319',
--	'Сумма уплаченных налогоплательщиком пенсионных взносов по договору негосударственного  пенсионного обеспечения и (или) страховых взносов по договору добровольного пенсионного страхования',
--	'319', 10, 0
--GO
----
--DECLARE @LINK INT
--SET @LINK = ISNULL((SELECT TOP 1 LINK FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '509'),0)
--exec dbo.X_SAVE_DICTIONARY_TYP_DEDUCTION 
--	@LINK,'509',
--	'Вычет из суммы доходов, полученных работниками в натуральной форме в качестве оплаты труда от сельскохозяйственных товаропроизводителей',
--	'509', 6, 0
--GO
----
--DECLARE @LINK INT
--SET @LINK = ISNULL((SELECT TOP 1 LINK FROM dbo.DICTIONARY_TYP_DEDUCTION WHERE SNAME = '607'),0)
--exec dbo.X_SAVE_DICTIONARY_TYP_DEDUCTION 
--	@LINK,'607',
--	'Вычет в сумме уплаченных работодателем страховых взносов за работника на накопительную часть трудовой пенсии',
--	'607', 9, 0
--GO

GO
--Исправление
set xact_abort on
BEGIN TRAN

--проверка периодов с основным статусом

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


;WITH T AS (
SELECT IM.LINK AS IM_LINK, E.TAB, P.FM, E.DEP_LINK, E.PERS_LINK, E.LINK AS EMPL_LINK, 
IM.[STATUS], DATE_BEGIN, IDF.DIS_DATE, 
NUM = ROW_NUMBER () OVER (PARTITION BY E.DEP_LINK, E.PERS_LINK ORDER BY DATE_BEGIN DESC),
ID = ROW_NUMBER () OVER ( ORDER BY IM.LINK DESC),
COUNT(*) OVER (PARTITION BY E.DEP_LINK, E.PERS_LINK) AS CNT
	FROM dbo.EMPL E 
		INNER JOIN PERSON P ON P.LINK = E.PERS_LINK
		INNER JOIN dbo.ITEM_MOVE IM ON E.LINK = IM.EMPL_LINK
		LEFT JOIN  dbo.ITEM_DIS_FACE IDF ON E.LINK = IDF.EMPL_LINK AND ISNULL(IDF.ACTIVE,0) = 1 
		WHERE IM.ACTIVE = 1 AND IM.NEW_FACE=1 AND (IM.[STATUS]=1 OR IM.[STATUS]=3) AND DATE_BEGIN <= dbo.DateEndOfMonth(dbo.ConvertDMY2Date(1,10,2015))
)
SELECT 
	IM_LINK, T1.TAB, T1.FM, T1.DEP_LINK, T1.PERS_LINK, T1.EMPL_LINK, T1.STATUS, T1.DATE_BEGIN, T1.DIS_DATE, J.LINK_EMPL AS ZP,S.LINK_EMPL AS DED, NUM, CNT
INTO #TMP	
FROM
	T AS T1
	LEFT JOIN (
		SELECT T2.PERS_LINK, T2.DEP_LINK, ID
		FROM
			T AS T2
		WHERE
			EXISTS (SELECT * FROM T AS T3 WHERE T2.PERS_LINK = T3.PERS_LINK AND T2.DEP_LINK = T3.DEP_LINK AND T2.NUM <> T3.NUM 
				AND(
					T2.DATE_BEGIN BETWEEN T3.DATE_BEGIN AND ISNULL(T3.DIS_DATE,'20490101')
					OR
					ISNULL(T2.DIS_DATE,'20490101') BETWEEN T3.DATE_BEGIN AND ISNULL(T3.DIS_DATE,'20490101')
					OR
					T2.DATE_BEGIN >= T3.DATE_BEGIN AND ISNULL(T2.DIS_DATE,'20490101') <= ISNULL(T3.DIS_DATE,'20490101')  
					OR
					T3.DATE_BEGIN BETWEEN T2.DATE_BEGIN AND ISNULL(T2.DIS_DATE,'20490101')
					OR
					ISNULL(T3.DIS_DATE,'20490101') BETWEEN T2.DATE_BEGIN AND ISNULL(T2.DIS_DATE,'20490101')
					OR
					T3.DATE_BEGIN >= T2.DATE_BEGIN AND ISNULL(T3.DIS_DATE,'20490101') <= ISNULL(T2.DIS_DATE,'20490101') 							
					)
				)
		) F1 ON F1.ID = T1.ID
	LEFT JOIN (SELECT J.LINK_EMPL FROM dbo.CALCULATE_JURNAL J
						WHERE YEAR(PERIOD_BEGIN) >= 2015 GROUP BY J.LINK_EMPL) J ON J.LINK_EMPL = T1.EMPL_LINK
	LEFT JOIN (SELECT S.LINK_EMPL FROM dbo.SAL_DED_MONTH S 
						WHERE YEAR(DATE_DED) >= 2015 GROUP BY S.LINK_EMPL) S ON S.LINK_EMPL = T1.EMPL_LINK
WHERE
	EXISTS (
				SELECT T2.PERS_LINK, T2.DEP_LINK, T2.NUM
				FROM
					T AS T2
				WHERE
					T2.PERS_LINK = T1.PERS_LINK AND T2.DEP_LINK = T1.DEP_LINK
					AND
					EXISTS (SELECT * FROM T AS T3 WHERE T2.PERS_LINK = T3.PERS_LINK AND T2.DEP_LINK = T3.DEP_LINK AND T2.NUM <> T3.NUM 
						AND(
							T2.DATE_BEGIN BETWEEN T3.DATE_BEGIN AND ISNULL(T3.DIS_DATE,'20490101')
							OR
							ISNULL(T2.DIS_DATE,'20490101') BETWEEN T3.DATE_BEGIN AND ISNULL(T3.DIS_DATE,'20490101')
							OR
							T2.DATE_BEGIN >= T3.DATE_BEGIN AND ISNULL(T2.DIS_DATE,'20490101') <= ISNULL(T3.DIS_DATE,'20490101')  
					
							)
							
						)
				)
	AND
	F1.ID IS NOT NULL
ORDER BY
	T1.PERS_LINK, T1.FM, DATE_BEGIN, DIS_DATE, T1.TAB
GO

---Результат проверки
--SELECT * FROM #TMP


----Ручное исправление
--ALTER TABLE dbo.ITEM_MOVE DISABLE TRIGGER ALL
--UPDATE dbo.ITEM_MOVE SET [STATUS] = 2 WHERE LINK = 17829
--ALTER TABLE dbo.ITEM_MOVE ENABLE TRIGGER ALL


---Автоматическое исправление
--
ALTER TABLE dbo.ITEM_MOVE DISABLE TRIGGER ALL

---
UPDATE IM SET [STATUS] = 2
FROM
	dbo.ITEM_MOVE IM
	INNER JOIN #TMP T ON T.IM_LINK = IM.LINK
WHERE
	ZP IS NULL AND DED IS NULL	

---
UPDATE IM SET [STATUS] = 2
FROM
dbo.ITEM_MOVE IM
INNER JOIN (
SELECT *,
	ORD = ROW_NUMBER () OVER (PARTITION BY DEP_LINK, PERS_LINK 
								ORDER BY 
									(CASE WHEN ISNULL(ZP,0)=0 THEN 0 ELSE 1 END) DESC, 
									(CASE WHEN ISNULL(DED,0)=0 THEN 0 ELSE 1 END) DESC, 
									ISNULL(DIS_DATE,'20490101') DESC,
									DATE_BEGIN asc									
									)
FROM
	#TMP
) T ON T.IM_LINK = IM.LINK
WHERE
	ORD <> 1	

ALTER TABLE dbo.ITEM_MOVE ENABLE TRIGGER ALL

COMMIT TRAN
GO



GO
/**************** ДОБАВЛЕНИЕ В НАВИГАТОР Администратор-КС ОБЪЕКТА "Автообновление программы"*************/ 
 
DECLARE @LINK_VAR INT
SET @LINK_VAR = NULL

DECLARE @LINK_SELF INT 
SELECT @LINK_SELF = LINK FROM DBO.S_NAVIGATOR WHERE CODE  = 'ADMIN'

DECLARE @OBJECT INT
SET @OBJECT = (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'REPORT_VIEW_FTP')

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 = 'ADMIN'))
SET @LINK_SNAVIGATOR = COALESCE((SELECT LINK FROM DBO.S_NAVIGATOR WHERE CODE = 'REPORT_VIEW_FTP'),0)

IF COALESCE(@LINK_SELF,0) > 0  AND COALESCE(@OBJECT,0) > 0  
 		EXEC DBO.W_ESN_UPDATEDOCUMENT @LINK_SNAVIGATOR, 'ADM_REPORT_VIEW_FTP', 'Автообновление программы', @ORD, NULL, 1, @LINK_SELF, 'RUN', @OBJECT, @LINK_VAR, 3


/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'REPORT_VIEW_FTP', 'db_owner', 63,0

EXEC X_SET_PROP 'REPORT_VIEW_FTP', 'INIT_OBJECT_METHOD', 'rn_spisok_from_ftp()'
GO

GO
/*

ПОСТАНОВЛЕНИЕ 04 июня 2015 г № 194 п О внесении изменений в постановление Правления Пенсионного фонда Российской Федерации  от 16 января 2014 года  № 2п
п.п б) п. 2.10.5. В разделе «Исчисление страхового стажа: дополнительные сведения» ПРАВЛЕНИЕ ПЕНСИОННОГО ФОНДА РОССИЙСКОЙ ФЕДЕРАЦИИ 

код территориальных условий труда или код особых условий труда 
и условий для досрочного назначения страховой пенсии не указывается

37.18. для застрахованных лиц, работающих в территориальных условиях труда или на видах работ, дающих право на досрочное назначение страховой пенсии по старости, код территориальных условий труда или код особых условий труда и условий для досрочного назначения страховой пенсии не указывается, если при отражении сведений в разделе 6.8 формы РСВ-1 указаны следующие дополнительные сведения:
- отпуск по уходу за ребенком;
- отпуск без сохранения содержания;
- отпуск без сохранения заработной платы, время простоя по вине  работника, неоплачиваемые периоды отстранения от работы (недопущения к работе), неоплачиваемый отпуск до одного года, предоставляемый педагогическим работникам, один дополнительный выходной день в месяц без сохранения заработной платы, предоставляемый женщинам, работающим в сельской местности, неоплачиваемое время участия в забастовке и другие неоплачиваемые периоды;
- повышение квалификации с отрывом от производства;
- исполнение государственных или общественных обязанностей;
- дни сдачи крови и ее компонентов и предоставленные в связи с этим дни отдыха;
- отстранение от работы (недопущение к работе) не по вине работника;
- дополнительные отпуска работникам, совмещающим работу с обучением;
- отпуск по уходу за ребенком от 1,5 до 3 лет;
- дополнительный отпуск граждан, подвергшихся воздействию радиации вследствие катастрофы на Чернобыльской АЭС;
- дополнительные выходные дни лицам, осуществляющим уход за детьми-инвалидами.»;

*/

UPDATE VV SET NOT_LGOT_EXPIR = 1
FROM
	dbo.VACATION_VID VV
	left join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK
WHERE
	COALESCE(D.WORK_D,0) = 7 -- отпуск по уходу за ребенком
	OR
	IS_DOP LIKE 'ДЕТИ'-- отпуск по уходу за ребенком
	OR
	COALESCE(VV.NO_SAL,0) = 1 -- отпуск без сохранения содержания
	OR
	IS_DOP LIKE 'АДМИНИСТР'	-- административные
	OR
	IS_DOP LIKE 'ДЛДЕТИ'	-- отпуск по уходу за ребенком от 1,5 до 3 лет
	OR
	IS_DOP LIKE 'НЕОПЛ'	-- Отпуск без сохранения содержания
GO
	
GO
EXEC X_SET_PROP 'REPORTS_ATR_LOW_TAR', 'DEFAULT_VALUE', 'Нет'
GO

GO
--Добавление системной Хозяйственной операции
--Сгенерировано скриптом: EXECUTE [dbo].UNLOAD_XOZ_OPER , @GROUP_CODE='16', @XOZ_CODE='17'





IF OBJECT_ID('TEMPDB..#TMP_XOZ_OPER_GROUP') IS NOT NULL
	DROP TABLE #TMP_XOZ_OPER_GROUP

CREATE TABLE #TMP_XOZ_OPER_GROUP (
	[CODE] char(2) NOT NULL ,
	[NAME] varchar(150) NOT NULL)

INSERT INTO #TMP_XOZ_OPER_GROUP ([CODE],[NAME]) 
VALUES('16','Оплата труда и прочие выплаты')



IF OBJECT_ID('TEMPDB..#TMP_XOZ_OPER') IS NOT NULL
	DROP TABLE #TMP_XOZ_OPER

CREATE TABLE #TMP_XOZ_OPER (
	[GROUP_CODE] char(2) NOT NULL ,
	[CODE] char(2) NOT NULL ,
	[NAME] varchar(254) NOT NULL ,
	[SYSTEM] tinyint NOT NULL ,
	[BO] tinyint NOT NULL ,
	[ZP] tinyint NOT NULL ,
	[RBS] tinyint NOT NULL ,
	[USED] tinyint NOT NULL ,
	[GZ] tinyint NOT NULL ,
	[GZ2] tinyint NOT NULL ,
	[DO] tinyint NOT NULL ,
	[BO_DT_KT] tinyint NOT NULL ,
	[DO_DT_KT] tinyint NOT NULL ,
	[BO_MIN] tinyint NOT NULL ,
	[DO_MIN] tinyint NOT NULL)

INSERT INTO #TMP_XOZ_OPER ([GROUP_CODE],[CODE],NAME,SYSTEM,BO,ZP,RBS,USED,GZ,GZ2,DO,BO_DT_KT,DO_DT_KT,BO_MIN,DO_MIN) 
VALUES('16','17','Начисление оплаты отпуска за счет резерва','1','1','1','0','1','0','0','0','0','0','0','0')


IF OBJECT_ID('TEMPDB..#TMP_XOZ_OPER_JURN') IS NOT NULL
	DROP TABLE #TMP_XOZ_OPER_JURN

CREATE TABLE #TMP_XOZ_OPER_JURN (
	[GROUP_CODE] char(2) NOT NULL ,
	[XOZ_CODE] char(2) NOT NULL ,
	[JURN_CODE] char(10) NOT NULL ,
	[GK] tinyint NOT NULL)

INSERT INTO #TMP_XOZ_OPER_JURN (GROUP_CODE,XOZ_CODE,JURN_CODE,GK) 
VALUES('16','17','06','1')


IF OBJECT_ID('TEMPDB..#TMP_CORRECT_PROV') IS NOT NULL
	DROP TABLE #TMP_CORRECT_PROV

CREATE TABLE #TMP_CORRECT_PROV (
	[GROUP_CODE] char(2) NOT NULL ,
	[XOZ_CODE] char(2) NOT NULL ,
	[CODE_DT] VARCHAR(20) NOT NULL ,
	[CODE_KT] VARCHAR(20) NOT NULL ,
	[CODE_DT_SGU] VARCHAR(20) NULL ,
	[CODE_KT_SGU] VARCHAR(20) NULL ,
	[LINK] INT  IDENTITY(1,1))

INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','17','401.60','302.11',211 ,NULL)


IF OBJECT_ID('TEMPDB..#TMP_XOZ_OPER_DOC') IS NOT NULL
	DROP TABLE #TMP_XOZ_OPER_DOC

CREATE TABLE #TMP_XOZ_OPER_DOC (
	[GROUP_CODE] char(2) NOT NULL ,
	[XOZ_CODE] char(2) NOT NULL ,
	[CODE_OBJECT] VARCHAR(30) NOT NULL ,
)


UPDATE A
SET A.NAME = B.NAME
FROM dbo.XOZ_OPER_GROUP A INNER JOIN #TMP_XOZ_OPER_GROUP B ON A.CODE LIKE B.CODE

INSERT INTO dbo.XOZ_OPER_GROUP (CODE,NAME)
SELECT CODE,NAME
FROM #TMP_XOZ_OPER_GROUP B 
WHERE NOT EXISTS (SELECT * FROM dbo.XOZ_OPER_GROUP A WHERE A.CODE LIKE B.CODE)

--Сдвиг несистемных кодов
IF OBJECT_ID('TEMPDB..#TMP_XO_USER_UPD') IS NOT NULL
	DROP TABLE #TMP_XO_USER_UPD

CREATE TABLE #TMP_XO_USER_UPD (
	LINK		INT,
	GROUP_LINK	INT,
	CODE		VARCHAR (2)
	)

INSERT INTO #TMP_XO_USER_UPD	
SELECT
	XO.LINK,
	XO.GROUP_LINK,
--	CONVERT (VARCHAR (2), CONVERT (INT, XO.CODE) + 1),
	XO.CODE
FROM dbo.XOZ_OPER XO
INNER JOIN dbo.XOZ_OPER_GROUP XOG ON (XOG.LINK = XO.GROUP_LINK)
INNER JOIN #TMP_XOZ_OPER XO1 ON (XO1.CODE = XO.CODE
	AND XO1.GROUP_CODE = XOG.CODE)
WHERE
	XO.[SYSTEM]	= 0

WHILE EXISTS (
				SELECT *
				FROM dbo.XOZ_OPER XO
				INNER JOIN #TMP_XO_USER_UPD T1 ON (T1.GROUP_LINK = XO.GROUP_LINK
					AND T1.CODE = XO.CODE)
			)
			
	UPDATE #TMP_XO_USER_UPD
	SET CODE = CONVERT (VARCHAR (2), CONVERT (INT, CODE) + 1)

UPDATE XO
SET CODE = T1.CODE
FROM dbo.XOZ_OPER XO
INNER JOIN #TMP_XO_USER_UPD T1 ON (T1.LINK = XO.LINK)



--обновление хо
UPDATE A SET 
	A.NAME = C.NAME,
	A.[SYSTEM] = C.[SYSTEM],
	A.[BO] = C.[BO],
	A.[ZP] = C.[ZP],
	A.[RBS] = C.[RBS],
	A.[USED] = C.[USED],
	A.[GZ] = C.[GZ],
	A.[GZ2] = C.[GZ2],
	A.[DO] = C.[DO],
	A.[BO_DT_KT] = C.[BO_DT_KT],
	A.[DO_DT_KT] = C.[DO_DT_KT],
	A.[BO_MIN] = C.[BO_MIN],
	A.[DO_MIN] = C.[DO_MIN]
FROM 
	dbo.XOZ_OPER A
	INNER JOIN dbo.XOZ_OPER_GROUP B ON A.GROUP_LINK = B.LINK
	INNER JOIN #TMP_XOZ_OPER C ON LTRIM(RTRIM(C.GROUP_CODE)) LIKE LTRIM(RTRIM(B.CODE)) AND LTRIM(RTRIM(C.CODE)) LIKE LTRIM(RTRIM(A.CODE))
	
	
INSERT INTO dbo.XOZ_OPER (GROUP_LINK,[CODE],NAME,SYSTEM,BO,ZP,RBS,USED,GZ,GZ2,DO,BO_DT_KT,DO_DT_KT,BO_MIN,DO_MIN)
SELECT B.LINK, A.[CODE], A.NAME, A.SYSTEM, A.BO, A.ZP, A.RBS, A.USED, A.GZ, A.GZ2, A.DO, A.BO_DT_KT, A.DO_DT_KT, A.BO_MIN, A.DO_MIN
FROM
	#TMP_XOZ_OPER A
	INNER JOIN dbo.XOZ_OPER_GROUP B ON LTRIM(RTRIM(A.GROUP_CODE)) LIKE LTRIM(RTRIM(B.CODE))
WHERE
	NOT EXISTS (SELECT * FROM dbo.XOZ_OPER C INNER JOIN dbo.XOZ_OPER_GROUP D ON C.GROUP_LINK = D.LINK
					WHERE 
						LTRIM(RTRIM(D.CODE)) LIKE LTRIM(RTRIM(B.CODE)) AND LTRIM(RTRIM(C.CODE)) LIKE LTRIM(RTRIM(A.CODE)) )


--обновляем журналы
DELETE A
FROM 
	dbo.XOZ_OPER_JURN A 
	INNER JOIN dbo.XOZ_OPER B ON B.LINK = A.XOZ_LINK
	INNER JOIN dbo.XOZ_OPER_GROUP C ON C.LINK = B.GROUP_LINK
WHERE
	EXISTS (SELECT * FROM #TMP_XOZ_OPER T WHERE LTRIM(RTRIM(T.GROUP_CODE)) LIKE LTRIM(RTRIM(C.CODE)) 
				AND LTRIM(RTRIM(T.CODE)) LIKE LTRIM(RTRIM(B.CODE)) )

INSERT INTO dbo.XOZ_OPER_JURN (XOZ_LINK,JURN_LINK,GK)
SELECT 
	A.LINK, D.LINK, C.GK
FROM
	dbo.XOZ_OPER A
	INNER JOIN dbo.XOZ_OPER_GROUP B ON A.GROUP_LINK = B.LINK
	INNER JOIN #TMP_XOZ_OPER_JURN C ON LTRIM(RTRIM(C.GROUP_CODE)) LIKE LTRIM(RTRIM(B.CODE)) AND LTRIM(RTRIM(C.XOZ_CODE)) LIKE LTRIM(RTRIM(A.CODE))
	INNER JOIN dbo.JOURNAL_OPERATION D ON LTRIM(RTRIM(D.code)) LIKE LTRIM(RTRIM(C.JURN_CODE))
WHERE
	NOT EXISTS (SELECT * FROM dbo.XOZ_OPER_JURN E WHERE E.XOZ_LINK = A.LINK AND E.JURN_LINK = D.LINK)


--обновление корректных проводок
DELETE A
FROM 
	dbo.CORRECT_PROV A 
	INNER JOIN dbo.XOZ_OPER B ON B.LINK = A.LINK_HOZ
	INNER JOIN dbo.XOZ_OPER_GROUP C ON C.LINK = B.GROUP_LINK	
WHERE
	EXISTS (SELECT * FROM #TMP_XOZ_OPER T WHERE LTRIM(RTRIM(T.GROUP_CODE)) LIKE LTRIM(RTRIM(C.CODE)) 
				AND LTRIM(RTRIM(T.CODE)) LIKE LTRIM(RTRIM(B.CODE)) )


;WITH tmp AS (
	SELECT 
	XO_LINK		= A.LINK
	,COR_PROV_LINK	= c.link
	FROM
		dbo.XOZ_OPER A
		INNER JOIN dbo.XOZ_OPER_GROUP B ON A.GROUP_LINK = B.LINK
		INNER JOIN #TMP_CORRECT_PROV C ON C.GROUP_CODE LIKE B.CODE AND C.XOZ_CODE LIKE A.CODE
) 
,DT_ACC AS (
	SELECT
		LINK	= t.LINK
		,ACC_LINK	= sa.LINK
	FROM #TMP_CORRECT_PROV t
		INNER JOIN dbo.S_ACCOUNTS sa ON sa.CODE LIKE t.CODE_DT
)
, KT_ACC AS (
	SELECT
		LINK	= t.LINK
		,ACC_LINK	= sa.LINK
	FROM #TMP_CORRECT_PROV t
		INNER JOIN dbo.S_ACCOUNTS sa ON sa.CODE LIKE t.CODE_KT
)
,DT_SGU AS (
	SELECT
		LINK		= t.link
		,SGU_LINK	= k.LINK
	FROM #TMP_CORRECT_PROV t
		INNER JOIN dbo.KOSGU k ON k.code LIKE t.CODE_DT_SGU
)
,KT_SGU AS (
	SELECT
		LINK		= t.link
		,SGU_LINK	= k.LINK
	FROM #TMP_CORRECT_PROV t
		INNER JOIN dbo.KOSGU k ON k.code LIKE t.CODE_DT_SGU
)
INSERT INTO dbo.CORRECT_PROV(LINK_HOZ, LINK_DT, LINK_KT, DT_SGU, KT_SGU)
SELECT 
	c.XO_LINK, SAD.ACC_LINK, SAK.ACC_LINK, GD.SGU_LINK, GK.SGU_LINK
FROM tmp c
	INNER JOIN dt_acc sad ON sad.LINk = c.COR_PROV_LINK
	INNER JOIN kt_acc SAK ON SAK.link = c.COR_PROV_LINK
	LEFT JOIN dt_sgu GD ON gd.LINK = c.COR_PROV_LINK
	LEFT JOIN kt_sgu GK ON gk.LINK = c.COR_PROV_LINK
WHERE
	NOT EXISTS (SELECT 1 FROM dbo.CORRECT_PROV E WHERE E.LINK_HOZ = c.XO_LINK AND E.LINK_DT = SAD.ACC_LINK AND E.LINK_KT = SAK.ACC_LINK 
			AND ISNULL(E.DT_SGU,0) = ISNULL(GD.SGU_LINK,0) AND ISNULL(E.KT_SGU,0) = ISNULL(GK.SGU_LINK,0)  )



--- Переформирование корректных проводок ---
DECLARE
	@BUFER_XO	VARCHAR (100)
	
SET @BUFER_XO = 'SYS_LOAD_XO_16_17'

INSERT INTO dbo.BUFFER ([ID], LINK)
SELECT
	@BUFER_XO,
	XO.LINK
FROM dbo.XOZ_OPER XO
INNER JOIN dbo.XOZ_OPER_GROUP XOG ON (XOG.LINK = XO.GROUP_LINK)
INNER JOIN #TMP_XOZ_OPER T1 ON (T1.GROUP_CODE = XOG.CODE
	AND T1.CODE = XO.CODE)
	

EXEC dbo.XD_CORRECT_PROV_FULL_BY_XO_BUF @BUFER_XO
GO

--Добавление системной Хозяйственной операции
--Сгенерировано скриптом: EXECUTE [dbo].UNLOAD_XOZ_OPER , @GROUP_CODE='16', @XOZ_CODE='18'





IF OBJECT_ID('TEMPDB..#TMP_XOZ_OPER_GROUP') IS NOT NULL
	DROP TABLE #TMP_XOZ_OPER_GROUP

CREATE TABLE #TMP_XOZ_OPER_GROUP (
	[CODE] char(2) NOT NULL ,
	[NAME] varchar(150) NOT NULL)

INSERT INTO #TMP_XOZ_OPER_GROUP ([CODE],[NAME]) 
VALUES('16','Оплата труда и прочие выплаты')



IF OBJECT_ID('TEMPDB..#TMP_XOZ_OPER') IS NOT NULL
	DROP TABLE #TMP_XOZ_OPER

CREATE TABLE #TMP_XOZ_OPER (
	[GROUP_CODE] char(2) NOT NULL ,
	[CODE] char(2) NOT NULL ,
	[NAME] varchar(254) NOT NULL ,
	[SYSTEM] tinyint NOT NULL ,
	[BO] tinyint NOT NULL ,
	[ZP] tinyint NOT NULL ,
	[RBS] tinyint NOT NULL ,
	[USED] tinyint NOT NULL ,
	[GZ] tinyint NOT NULL ,
	[GZ2] tinyint NOT NULL ,
	[DO] tinyint NOT NULL ,
	[BO_DT_KT] tinyint NOT NULL ,
	[DO_DT_KT] tinyint NOT NULL ,
	[BO_MIN] tinyint NOT NULL ,
	[DO_MIN] tinyint NOT NULL)

INSERT INTO #TMP_XOZ_OPER ([GROUP_CODE],[CODE],NAME,SYSTEM,BO,ZP,RBS,USED,GZ,GZ2,DO,BO_DT_KT,DO_DT_KT,BO_MIN,DO_MIN) 
VALUES('16','18','Начисление страховых взносов за счет резерва','1','1','1','0','1','0','0','0','0','0','0','0')


IF OBJECT_ID('TEMPDB..#TMP_XOZ_OPER_JURN') IS NOT NULL
	DROP TABLE #TMP_XOZ_OPER_JURN

CREATE TABLE #TMP_XOZ_OPER_JURN (
	[GROUP_CODE] char(2) NOT NULL ,
	[XOZ_CODE] char(2) NOT NULL ,
	[JURN_CODE] char(10) NOT NULL ,
	[GK] tinyint NOT NULL)

INSERT INTO #TMP_XOZ_OPER_JURN (GROUP_CODE,XOZ_CODE,JURN_CODE,GK) 
VALUES('16','18','06','1')


IF OBJECT_ID('TEMPDB..#TMP_CORRECT_PROV') IS NOT NULL
	DROP TABLE #TMP_CORRECT_PROV

CREATE TABLE #TMP_CORRECT_PROV (
	[GROUP_CODE] char(2) NOT NULL ,
	[XOZ_CODE] char(2) NOT NULL ,
	[CODE_DT] VARCHAR(20) NOT NULL ,
	[CODE_KT] VARCHAR(20) NOT NULL ,
	[CODE_DT_SGU] VARCHAR(20) NULL ,
	[CODE_KT_SGU] VARCHAR(20) NULL ,
	[LINK] INT  IDENTITY(1,1))

INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.11',226 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.11',290 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.11',213 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.10',225 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.11',221 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.11',222 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.11',223 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.11',224 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.11',225 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.10',290 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.10',213 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.10',221 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.10',222 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.10',223 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.10',224 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.09',224 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.09',225 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.09',226 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.09',290 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.09',221 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.10',226 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.08',224 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.08',225 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.08',226 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.09',213 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.09',222 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.09',223 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.07',213 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.08',290 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.08',213 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.08',221 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.08',222 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.08',223 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.07',222 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.07',223 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.07',224 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.07',225 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.07',226 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.07',290 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.07',221 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.02',222 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.02',223 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.02',224 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.02',225 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.02',226 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.02',290 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.02',213 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','18','401.60','303.02',221 ,NULL)


IF OBJECT_ID('TEMPDB..#TMP_XOZ_OPER_DOC') IS NOT NULL
	DROP TABLE #TMP_XOZ_OPER_DOC

CREATE TABLE #TMP_XOZ_OPER_DOC (
	[GROUP_CODE] char(2) NOT NULL ,
	[XOZ_CODE] char(2) NOT NULL ,
	[CODE_OBJECT] VARCHAR(30) NOT NULL ,
)


UPDATE A
SET A.NAME = B.NAME
FROM dbo.XOZ_OPER_GROUP A INNER JOIN #TMP_XOZ_OPER_GROUP B ON A.CODE LIKE B.CODE

INSERT INTO dbo.XOZ_OPER_GROUP (CODE,NAME)
SELECT CODE,NAME
FROM #TMP_XOZ_OPER_GROUP B 
WHERE NOT EXISTS (SELECT * FROM dbo.XOZ_OPER_GROUP A WHERE A.CODE LIKE B.CODE)

--Сдвиг несистемных кодов
IF OBJECT_ID('TEMPDB..#TMP_XO_USER_UPD') IS NOT NULL
	DROP TABLE #TMP_XO_USER_UPD

CREATE TABLE #TMP_XO_USER_UPD (
	LINK		INT,
	GROUP_LINK	INT,
	CODE		VARCHAR (2)
	)

INSERT INTO #TMP_XO_USER_UPD	
SELECT
	XO.LINK,
	XO.GROUP_LINK,
--	CONVERT (VARCHAR (2), CONVERT (INT, XO.CODE) + 1),
	XO.CODE
FROM dbo.XOZ_OPER XO
INNER JOIN dbo.XOZ_OPER_GROUP XOG ON (XOG.LINK = XO.GROUP_LINK)
INNER JOIN #TMP_XOZ_OPER XO1 ON (XO1.CODE = XO.CODE
	AND XO1.GROUP_CODE = XOG.CODE)
WHERE
	XO.[SYSTEM]	= 0

WHILE EXISTS (
				SELECT *
				FROM dbo.XOZ_OPER XO
				INNER JOIN #TMP_XO_USER_UPD T1 ON (T1.GROUP_LINK = XO.GROUP_LINK
					AND T1.CODE = XO.CODE)
			)
			
	UPDATE #TMP_XO_USER_UPD
	SET CODE = CONVERT (VARCHAR (2), CONVERT (INT, CODE) + 1)

UPDATE XO
SET CODE = T1.CODE
FROM dbo.XOZ_OPER XO
INNER JOIN #TMP_XO_USER_UPD T1 ON (T1.LINK = XO.LINK)



--обновление хо
UPDATE A SET 
	A.NAME = C.NAME,
	A.[SYSTEM] = C.[SYSTEM],
	A.[BO] = C.[BO],
	A.[ZP] = C.[ZP],
	A.[RBS] = C.[RBS],
	A.[USED] = C.[USED],
	A.[GZ] = C.[GZ],
	A.[GZ2] = C.[GZ2],
	A.[DO] = C.[DO],
	A.[BO_DT_KT] = C.[BO_DT_KT],
	A.[DO_DT_KT] = C.[DO_DT_KT],
	A.[BO_MIN] = C.[BO_MIN],
	A.[DO_MIN] = C.[DO_MIN]
FROM 
	dbo.XOZ_OPER A
	INNER JOIN dbo.XOZ_OPER_GROUP B ON A.GROUP_LINK = B.LINK
	INNER JOIN #TMP_XOZ_OPER C ON LTRIM(RTRIM(C.GROUP_CODE)) LIKE LTRIM(RTRIM(B.CODE)) AND LTRIM(RTRIM(C.CODE)) LIKE LTRIM(RTRIM(A.CODE))
	
	
INSERT INTO dbo.XOZ_OPER (GROUP_LINK,[CODE],NAME,SYSTEM,BO,ZP,RBS,USED,GZ,GZ2,DO,BO_DT_KT,DO_DT_KT,BO_MIN,DO_MIN)
SELECT B.LINK, A.[CODE], A.NAME, A.SYSTEM, A.BO, A.ZP, A.RBS, A.USED, A.GZ, A.GZ2, A.DO, A.BO_DT_KT, A.DO_DT_KT, A.BO_MIN, A.DO_MIN
FROM
	#TMP_XOZ_OPER A
	INNER JOIN dbo.XOZ_OPER_GROUP B ON LTRIM(RTRIM(A.GROUP_CODE)) LIKE LTRIM(RTRIM(B.CODE))
WHERE
	NOT EXISTS (SELECT * FROM dbo.XOZ_OPER C INNER JOIN dbo.XOZ_OPER_GROUP D ON C.GROUP_LINK = D.LINK
					WHERE 
						LTRIM(RTRIM(D.CODE)) LIKE LTRIM(RTRIM(B.CODE)) AND LTRIM(RTRIM(C.CODE)) LIKE LTRIM(RTRIM(A.CODE)) )


--обновляем журналы
DELETE A
FROM 
	dbo.XOZ_OPER_JURN A 
	INNER JOIN dbo.XOZ_OPER B ON B.LINK = A.XOZ_LINK
	INNER JOIN dbo.XOZ_OPER_GROUP C ON C.LINK = B.GROUP_LINK
WHERE
	EXISTS (SELECT * FROM #TMP_XOZ_OPER T WHERE LTRIM(RTRIM(T.GROUP_CODE)) LIKE LTRIM(RTRIM(C.CODE)) 
				AND LTRIM(RTRIM(T.CODE)) LIKE LTRIM(RTRIM(B.CODE)) )

INSERT INTO dbo.XOZ_OPER_JURN (XOZ_LINK,JURN_LINK,GK)
SELECT 
	A.LINK, D.LINK, C.GK
FROM
	dbo.XOZ_OPER A
	INNER JOIN dbo.XOZ_OPER_GROUP B ON A.GROUP_LINK = B.LINK
	INNER JOIN #TMP_XOZ_OPER_JURN C ON LTRIM(RTRIM(C.GROUP_CODE)) LIKE LTRIM(RTRIM(B.CODE)) AND LTRIM(RTRIM(C.XOZ_CODE)) LIKE LTRIM(RTRIM(A.CODE))
	INNER JOIN dbo.JOURNAL_OPERATION D ON LTRIM(RTRIM(D.code)) LIKE LTRIM(RTRIM(C.JURN_CODE))
WHERE
	NOT EXISTS (SELECT * FROM dbo.XOZ_OPER_JURN E WHERE E.XOZ_LINK = A.LINK AND E.JURN_LINK = D.LINK)


--обновление корректных проводок
DELETE A
FROM 
	dbo.CORRECT_PROV A 
	INNER JOIN dbo.XOZ_OPER B ON B.LINK = A.LINK_HOZ
	INNER JOIN dbo.XOZ_OPER_GROUP C ON C.LINK = B.GROUP_LINK	
WHERE
	EXISTS (SELECT * FROM #TMP_XOZ_OPER T WHERE LTRIM(RTRIM(T.GROUP_CODE)) LIKE LTRIM(RTRIM(C.CODE)) 
				AND LTRIM(RTRIM(T.CODE)) LIKE LTRIM(RTRIM(B.CODE)) )


;WITH tmp AS (
	SELECT 
	XO_LINK		= A.LINK
	,COR_PROV_LINK	= c.link
	FROM
		dbo.XOZ_OPER A
		INNER JOIN dbo.XOZ_OPER_GROUP B ON A.GROUP_LINK = B.LINK
		INNER JOIN #TMP_CORRECT_PROV C ON C.GROUP_CODE LIKE B.CODE AND C.XOZ_CODE LIKE A.CODE
) 
,DT_ACC AS (
	SELECT
		LINK	= t.LINK
		,ACC_LINK	= sa.LINK
	FROM #TMP_CORRECT_PROV t
		INNER JOIN dbo.S_ACCOUNTS sa ON sa.CODE LIKE t.CODE_DT
)
, KT_ACC AS (
	SELECT
		LINK	= t.LINK
		,ACC_LINK	= sa.LINK
	FROM #TMP_CORRECT_PROV t
		INNER JOIN dbo.S_ACCOUNTS sa ON sa.CODE LIKE t.CODE_KT
)
,DT_SGU AS (
	SELECT
		LINK		= t.link
		,SGU_LINK	= k.LINK
	FROM #TMP_CORRECT_PROV t
		INNER JOIN dbo.KOSGU k ON k.code LIKE t.CODE_DT_SGU
)
,KT_SGU AS (
	SELECT
		LINK		= t.link
		,SGU_LINK	= k.LINK
	FROM #TMP_CORRECT_PROV t
		INNER JOIN dbo.KOSGU k ON k.code LIKE t.CODE_DT_SGU
)
INSERT INTO dbo.CORRECT_PROV(LINK_HOZ, LINK_DT, LINK_KT, DT_SGU, KT_SGU)
SELECT 
	c.XO_LINK, SAD.ACC_LINK, SAK.ACC_LINK, GD.SGU_LINK, GK.SGU_LINK
FROM tmp c
	INNER JOIN dt_acc sad ON sad.LINk = c.COR_PROV_LINK
	INNER JOIN kt_acc SAK ON SAK.link = c.COR_PROV_LINK
	LEFT JOIN dt_sgu GD ON gd.LINK = c.COR_PROV_LINK
	LEFT JOIN kt_sgu GK ON gk.LINK = c.COR_PROV_LINK
WHERE
	NOT EXISTS (SELECT 1 FROM dbo.CORRECT_PROV E WHERE E.LINK_HOZ = c.XO_LINK AND E.LINK_DT = SAD.ACC_LINK AND E.LINK_KT = SAK.ACC_LINK 
			AND ISNULL(E.DT_SGU,0) = ISNULL(GD.SGU_LINK,0) AND ISNULL(E.KT_SGU,0) = ISNULL(GK.SGU_LINK,0)  )



--- Переформирование корректных проводок ---
DECLARE
	@BUFER_XO	VARCHAR (100)
	
SET @BUFER_XO = 'SYS_LOAD_XO_16_18'

INSERT INTO dbo.BUFFER ([ID], LINK)
SELECT
	@BUFER_XO,
	XO.LINK
FROM dbo.XOZ_OPER XO
INNER JOIN dbo.XOZ_OPER_GROUP XOG ON (XOG.LINK = XO.GROUP_LINK)
INNER JOIN #TMP_XOZ_OPER T1 ON (T1.GROUP_CODE = XOG.CODE
	AND T1.CODE = XO.CODE)
	

EXEC dbo.XD_CORRECT_PROV_FULL_BY_XO_BUF @BUFER_XO
GO

--Добавление системной Хозяйственной операции
--Сгенерировано скриптом: EXECUTE [dbo].UNLOAD_XOZ_OPER , @GROUP_CODE='16', @XOZ_CODE='19'





IF OBJECT_ID('TEMPDB..#TMP_XOZ_OPER_GROUP') IS NOT NULL
	DROP TABLE #TMP_XOZ_OPER_GROUP

CREATE TABLE #TMP_XOZ_OPER_GROUP (
	[CODE] char(2) NOT NULL ,
	[NAME] varchar(150) NOT NULL)

INSERT INTO #TMP_XOZ_OPER_GROUP ([CODE],[NAME]) 
VALUES('16','Оплата труда и прочие выплаты')



IF OBJECT_ID('TEMPDB..#TMP_XOZ_OPER') IS NOT NULL
	DROP TABLE #TMP_XOZ_OPER

CREATE TABLE #TMP_XOZ_OPER (
	[GROUP_CODE] char(2) NOT NULL ,
	[CODE] char(2) NOT NULL ,
	[NAME] varchar(254) NOT NULL ,
	[SYSTEM] tinyint NOT NULL ,
	[BO] tinyint NOT NULL ,
	[ZP] tinyint NOT NULL ,
	[RBS] tinyint NOT NULL ,
	[USED] tinyint NOT NULL ,
	[GZ] tinyint NOT NULL ,
	[GZ2] tinyint NOT NULL ,
	[DO] tinyint NOT NULL ,
	[BO_DT_KT] tinyint NOT NULL ,
	[DO_DT_KT] tinyint NOT NULL ,
	[BO_MIN] tinyint NOT NULL ,
	[DO_MIN] tinyint NOT NULL)

INSERT INTO #TMP_XOZ_OPER ([GROUP_CODE],[CODE],NAME,SYSTEM,BO,ZP,RBS,USED,GZ,GZ2,DO,BO_DT_KT,DO_DT_KT,BO_MIN,DO_MIN) 
VALUES('16','19','Начисление ФСС за счет резерва','1','1','1','0','1','0','0','0','0','0','0','0')


IF OBJECT_ID('TEMPDB..#TMP_XOZ_OPER_JURN') IS NOT NULL
	DROP TABLE #TMP_XOZ_OPER_JURN

CREATE TABLE #TMP_XOZ_OPER_JURN (
	[GROUP_CODE] char(2) NOT NULL ,
	[XOZ_CODE] char(2) NOT NULL ,
	[JURN_CODE] char(10) NOT NULL ,
	[GK] tinyint NOT NULL)

INSERT INTO #TMP_XOZ_OPER_JURN (GROUP_CODE,XOZ_CODE,JURN_CODE,GK) 
VALUES('16','19','06','1')


IF OBJECT_ID('TEMPDB..#TMP_CORRECT_PROV') IS NOT NULL
	DROP TABLE #TMP_CORRECT_PROV

CREATE TABLE #TMP_CORRECT_PROV (
	[GROUP_CODE] char(2) NOT NULL ,
	[XOZ_CODE] char(2) NOT NULL ,
	[CODE_DT] VARCHAR(20) NOT NULL ,
	[CODE_KT] VARCHAR(20) NOT NULL ,
	[CODE_DT_SGU] VARCHAR(20) NULL ,
	[CODE_KT_SGU] VARCHAR(20) NULL ,
	[LINK] INT  IDENTITY(1,1))

INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','19','401.60','303.06',224 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','19','401.60','303.06',225 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','19','401.60','303.06',226 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','19','401.60','303.06',290 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','19','401.60','303.06',213 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','19','401.60','303.06',221 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','19','401.60','303.06',222 ,NULL)
INSERT INTO #TMP_CORRECT_PROV (GROUP_CODE,XOZ_CODE,CODE_DT,CODE_KT,CODE_DT_SGU,CODE_KT_SGU) 
VALUES('16','19','401.60','303.06',223 ,NULL)


IF OBJECT_ID('TEMPDB..#TMP_XOZ_OPER_DOC') IS NOT NULL
	DROP TABLE #TMP_XOZ_OPER_DOC

CREATE TABLE #TMP_XOZ_OPER_DOC (
	[GROUP_CODE] char(2) NOT NULL ,
	[XOZ_CODE] char(2) NOT NULL ,
	[CODE_OBJECT] VARCHAR(30) NOT NULL ,
)


UPDATE A
SET A.NAME = B.NAME
FROM dbo.XOZ_OPER_GROUP A INNER JOIN #TMP_XOZ_OPER_GROUP B ON A.CODE LIKE B.CODE

INSERT INTO dbo.XOZ_OPER_GROUP (CODE,NAME)
SELECT CODE,NAME
FROM #TMP_XOZ_OPER_GROUP B 
WHERE NOT EXISTS (SELECT * FROM dbo.XOZ_OPER_GROUP A WHERE A.CODE LIKE B.CODE)

--Сдвиг несистемных кодов
IF OBJECT_ID('TEMPDB..#TMP_XO_USER_UPD') IS NOT NULL
	DROP TABLE #TMP_XO_USER_UPD

CREATE TABLE #TMP_XO_USER_UPD (
	LINK		INT,
	GROUP_LINK	INT,
	CODE		VARCHAR (2)
	)

INSERT INTO #TMP_XO_USER_UPD	
SELECT
	XO.LINK,
	XO.GROUP_LINK,
--	CONVERT (VARCHAR (2), CONVERT (INT, XO.CODE) + 1),
	XO.CODE
FROM dbo.XOZ_OPER XO
INNER JOIN dbo.XOZ_OPER_GROUP XOG ON (XOG.LINK = XO.GROUP_LINK)
INNER JOIN #TMP_XOZ_OPER XO1 ON (XO1.CODE = XO.CODE
	AND XO1.GROUP_CODE = XOG.CODE)
WHERE
	XO.[SYSTEM]	= 0

WHILE EXISTS (
				SELECT *
				FROM dbo.XOZ_OPER XO
				INNER JOIN #TMP_XO_USER_UPD T1 ON (T1.GROUP_LINK = XO.GROUP_LINK
					AND T1.CODE = XO.CODE)
			)
			
	UPDATE #TMP_XO_USER_UPD
	SET CODE = CONVERT (VARCHAR (2), CONVERT (INT, CODE) + 1)

UPDATE XO
SET CODE = T1.CODE
FROM dbo.XOZ_OPER XO
INNER JOIN #TMP_XO_USER_UPD T1 ON (T1.LINK = XO.LINK)



--обновление хо
UPDATE A SET 
	A.NAME = C.NAME,
	A.[SYSTEM] = C.[SYSTEM],
	A.[BO] = C.[BO],
	A.[ZP] = C.[ZP],
	A.[RBS] = C.[RBS],
	A.[USED] = C.[USED],
	A.[GZ] = C.[GZ],
	A.[GZ2] = C.[GZ2],
	A.[DO] = C.[DO],
	A.[BO_DT_KT] = C.[BO_DT_KT],
	A.[DO_DT_KT] = C.[DO_DT_KT],
	A.[BO_MIN] = C.[BO_MIN],
	A.[DO_MIN] = C.[DO_MIN]
FROM 
	dbo.XOZ_OPER A
	INNER JOIN dbo.XOZ_OPER_GROUP B ON A.GROUP_LINK = B.LINK
	INNER JOIN #TMP_XOZ_OPER C ON LTRIM(RTRIM(C.GROUP_CODE)) LIKE LTRIM(RTRIM(B.CODE)) AND LTRIM(RTRIM(C.CODE)) LIKE LTRIM(RTRIM(A.CODE))
	
	
INSERT INTO dbo.XOZ_OPER (GROUP_LINK,[CODE],NAME,SYSTEM,BO,ZP,RBS,USED,GZ,GZ2,DO,BO_DT_KT,DO_DT_KT,BO_MIN,DO_MIN)
SELECT B.LINK, A.[CODE], A.NAME, A.SYSTEM, A.BO, A.ZP, A.RBS, A.USED, A.GZ, A.GZ2, A.DO, A.BO_DT_KT, A.DO_DT_KT, A.BO_MIN, A.DO_MIN
FROM
	#TMP_XOZ_OPER A
	INNER JOIN dbo.XOZ_OPER_GROUP B ON LTRIM(RTRIM(A.GROUP_CODE)) LIKE LTRIM(RTRIM(B.CODE))
WHERE
	NOT EXISTS (SELECT * FROM dbo.XOZ_OPER C INNER JOIN dbo.XOZ_OPER_GROUP D ON C.GROUP_LINK = D.LINK
					WHERE 
						LTRIM(RTRIM(D.CODE)) LIKE LTRIM(RTRIM(B.CODE)) AND LTRIM(RTRIM(C.CODE)) LIKE LTRIM(RTRIM(A.CODE)) )


--обновляем журналы
DELETE A
FROM 
	dbo.XOZ_OPER_JURN A 
	INNER JOIN dbo.XOZ_OPER B ON B.LINK = A.XOZ_LINK
	INNER JOIN dbo.XOZ_OPER_GROUP C ON C.LINK = B.GROUP_LINK
WHERE
	EXISTS (SELECT * FROM #TMP_XOZ_OPER T WHERE LTRIM(RTRIM(T.GROUP_CODE)) LIKE LTRIM(RTRIM(C.CODE)) 
				AND LTRIM(RTRIM(T.CODE)) LIKE LTRIM(RTRIM(B.CODE)) )

INSERT INTO dbo.XOZ_OPER_JURN (XOZ_LINK,JURN_LINK,GK)
SELECT 
	A.LINK, D.LINK, C.GK
FROM
	dbo.XOZ_OPER A
	INNER JOIN dbo.XOZ_OPER_GROUP B ON A.GROUP_LINK = B.LINK
	INNER JOIN #TMP_XOZ_OPER_JURN C ON LTRIM(RTRIM(C.GROUP_CODE)) LIKE LTRIM(RTRIM(B.CODE)) AND LTRIM(RTRIM(C.XOZ_CODE)) LIKE LTRIM(RTRIM(A.CODE))
	INNER JOIN dbo.JOURNAL_OPERATION D ON LTRIM(RTRIM(D.code)) LIKE LTRIM(RTRIM(C.JURN_CODE))
WHERE
	NOT EXISTS (SELECT * FROM dbo.XOZ_OPER_JURN E WHERE E.XOZ_LINK = A.LINK AND E.JURN_LINK = D.LINK)


--обновление корректных проводок
DELETE A
FROM 
	dbo.CORRECT_PROV A 
	INNER JOIN dbo.XOZ_OPER B ON B.LINK = A.LINK_HOZ
	INNER JOIN dbo.XOZ_OPER_GROUP C ON C.LINK = B.GROUP_LINK	
WHERE
	EXISTS (SELECT * FROM #TMP_XOZ_OPER T WHERE LTRIM(RTRIM(T.GROUP_CODE)) LIKE LTRIM(RTRIM(C.CODE)) 
				AND LTRIM(RTRIM(T.CODE)) LIKE LTRIM(RTRIM(B.CODE)) )


;WITH tmp AS (
	SELECT 
	XO_LINK		= A.LINK
	,COR_PROV_LINK	= c.link
	FROM
		dbo.XOZ_OPER A
		INNER JOIN dbo.XOZ_OPER_GROUP B ON A.GROUP_LINK = B.LINK
		INNER JOIN #TMP_CORRECT_PROV C ON C.GROUP_CODE LIKE B.CODE AND C.XOZ_CODE LIKE A.CODE
) 
,DT_ACC AS (
	SELECT
		LINK	= t.LINK
		,ACC_LINK	= sa.LINK
	FROM #TMP_CORRECT_PROV t
		INNER JOIN dbo.S_ACCOUNTS sa ON sa.CODE LIKE t.CODE_DT
)
, KT_ACC AS (
	SELECT
		LINK	= t.LINK
		,ACC_LINK	= sa.LINK
	FROM #TMP_CORRECT_PROV t
		INNER JOIN dbo.S_ACCOUNTS sa ON sa.CODE LIKE t.CODE_KT
)
,DT_SGU AS (
	SELECT
		LINK		= t.link
		,SGU_LINK	= k.LINK
	FROM #TMP_CORRECT_PROV t
		INNER JOIN dbo.KOSGU k ON k.code LIKE t.CODE_DT_SGU
)
,KT_SGU AS (
	SELECT
		LINK		= t.link
		,SGU_LINK	= k.LINK
	FROM #TMP_CORRECT_PROV t
		INNER JOIN dbo.KOSGU k ON k.code LIKE t.CODE_DT_SGU
)
INSERT INTO dbo.CORRECT_PROV(LINK_HOZ, LINK_DT, LINK_KT, DT_SGU, KT_SGU)
SELECT 
	c.XO_LINK, SAD.ACC_LINK, SAK.ACC_LINK, GD.SGU_LINK, GK.SGU_LINK
FROM tmp c
	INNER JOIN dt_acc sad ON sad.LINk = c.COR_PROV_LINK
	INNER JOIN kt_acc SAK ON SAK.link = c.COR_PROV_LINK
	LEFT JOIN dt_sgu GD ON gd.LINK = c.COR_PROV_LINK
	LEFT JOIN kt_sgu GK ON gk.LINK = c.COR_PROV_LINK
WHERE
	NOT EXISTS (SELECT 1 FROM dbo.CORRECT_PROV E WHERE E.LINK_HOZ = c.XO_LINK AND E.LINK_DT = SAD.ACC_LINK AND E.LINK_KT = SAK.ACC_LINK 
			AND ISNULL(E.DT_SGU,0) = ISNULL(GD.SGU_LINK,0) AND ISNULL(E.KT_SGU,0) = ISNULL(GK.SGU_LINK,0)  )



--- Переформирование корректных проводок ---
DECLARE
	@BUFER_XO	VARCHAR (100)
	
SET @BUFER_XO = 'SYS_LOAD_XO_16_19'

INSERT INTO dbo.BUFFER ([ID], LINK)
SELECT
	@BUFER_XO,
	XO.LINK
FROM dbo.XOZ_OPER XO
INNER JOIN dbo.XOZ_OPER_GROUP XOG ON (XOG.LINK = XO.GROUP_LINK)
INNER JOIN #TMP_XOZ_OPER T1 ON (T1.GROUP_CODE = XOG.CODE
	AND T1.CODE = XO.CODE)
	

EXEC dbo.XD_CORRECT_PROV_FULL_BY_XO_BUF @BUFER_XO
GO

--Добавление системной типовой операции
--Сгенерировано скриптом: EXECUTE dbo.[UNLOAD_SHABLON_DOCUMENTS_PROV] @NAME_OPER = 'Начисление отпускных (компенсации) за счет резерва  (Дт401.60-Кт302.11)', @MODE = 'ADD', @NASTR_DOC = 0

SET NOCOUNT ON


IF OBJECT_ID('TEMPDB..#tmp_G_PROV1') IS NOT NULL
	DROP TABLE #tmp_G_PROV1


CREATE TABLE #tmp_G_PROV1 (
	[LINK] int ,
	[LINK_UP] int,
	[NAME_OPER] varchar(254),
	[ORDERS] int)

INSERT INTO #tmp_G_PROV1 (LINK,LINK_UP,NAME_OPER,ORDERS) 
VALUES(115806,3205,'Начисление отпускных (компенсации) за счет резерва  (Дт401.60-Кт302.11)',164)

IF OBJECT_ID('TEMPDB..#tmp_G_PROV2') IS NOT NULL
	DROP TABLE #tmp_G_PROV2


CREATE TABLE #tmp_G_PROV2 (
	[LINK] int,
	[LINK_UP] int,
	[NAME] varchar(254),
	[ORDERS] smallint,
	XOG_CODE VARCHAR(2),
	XO_CODE VARCHAR(2),
	STORNO TINYINT)

INSERT INTO #tmp_G_PROV2 (LINK,LINK_UP,NAME,ORDERS,XOG_CODE,XO_CODE,STORNO) 
VALUES(119893,115806,'Начисление отпускных (компенсации) за счет резерва  (Дт401.60-Кт302.11)',1, '16', '17', 0)

IF OBJECT_ID('TEMPDB..#tmp_G_PROV_AP') IS NOT NULL
	DROP TABLE #tmp_G_PROV_AP


CREATE TABLE #tmp_G_PROV_AP (
	[LINK_UP] int,
	[DB_KR] tinyint,
	[ACCOUNT] VARCHAR(20),
	[EKR] VARCHAR(3),
	[SGU] VARCHAR(3))

INSERT INTO #tmp_G_PROV_AP (LINK_UP, DB_KR, ACCOUNT, EKR, SGU)
VALUES(119893,0,'401.60', '211', '211')
INSERT INTO #tmp_G_PROV_AP (LINK_UP, DB_KR, ACCOUNT, EKR, SGU)
VALUES(119893,1,'302.11', '211', '730')

IF COLUMNPROPERTY(object_id('[dbo].[G_PROV1]'), 'LINK2', 'AllowsNull') is NOT NULL
   ALTER TABLE [dbo].[G_PROV1] DROP COLUMN [LINK2]

IF COLUMNPROPERTY(object_id('[dbo].[G_PROV1]'), 'LINK2', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[G_PROV1] ADD [LINK2] int
GO

IF OBJECT_ID('TEMPDB..#G_PROV1_REC') IS NOT NULL
	DROP TABLE #G_PROV1_REC

CREATE TABLE #G_PROV1_REC (LINK1 INT, LINK2 INT)

INSERT INTO dbo.G_PROV1 (LINK_UP, NAME_OPER, ORDERS, LINK2)
OUTPUT INSERTED.LINK, INSERTED.LINK2 INTO #G_PROV1_REC (LINK1,LINK2)	
SELECT DISTINCT LINK_UP = T.LINK, TG1.NAME_OPER, TG1.ORDERS, LINK2 = TG1.LINK  
FROM
	#tmp_G_PROV1 TG1
	INNER JOIN (SELECT TOP 1 G.LINK FROM dbo.G_PROV G INNER JOIN dbo.S_OBJECTS SO ON SO.LINK = G.[OBJECT] 
					WHERE SO.[CODE] = 'SHABLON_DOCUMENTS_PROV') T ON 1=1
WHERE
	NOT EXISTS (SELECT *
				FROM
					dbo.G_PROV1 G1
				WHERE
					RTRIM(LTRIM(G1.NAME_OPER)) = RTRIM(LTRIM(TG1.NAME_OPER)))


IF COLUMNPROPERTY(object_id('[dbo].[G_PROV2]'), 'LINK2', 'AllowsNull') is NOT NULL
   ALTER TABLE [dbo].[G_PROV2] DROP COLUMN [LINK2]

IF COLUMNPROPERTY(object_id('[dbo].[G_PROV2]'), 'LINK2', 'AllowsNull') is NULL
   ALTER TABLE [dbo].[G_PROV2] ADD [LINK2] int
GO

IF OBJECT_ID('TEMPDB..#G_PROV2_REC') IS NOT NULL
	DROP TABLE #G_PROV2_REC

CREATE TABLE #G_PROV2_REC (LINK1 INT, LINK2 INT)

INSERT INTO dbo.G_PROV2 (LINK_UP, SUMMA, QUANTITY, STORNO, NAME, ORDERS, ECON_OPER, LINK2)
OUTPUT INSERTED.LINK, INSERTED.LINK2 INTO #G_PROV2_REC (LINK1,LINK2)	
SELECT DISTINCT LINK_UP = R.LINK1, SUMMA = 0, QUANTITY = 0, STORNO = TG2.STORNO, TG2.NAME, TG2.ORDERS, ECON_OPER = X.LINK, LINK2 = TG2.LINK  
FROM
	#G_PROV1_REC R
	INNER JOIN dbo.G_PROV1 G1 ON G1.LINK = R.LINK1
	INNER JOIN #tmp_G_PROV2 TG2 ON R.LINK2 = TG2.LINK_UP  
	LEFT JOIN 
	(SELECT XO.LINK, XOG.CODE AS XOG_CODE, XO.CODE AS XO_CODE FROM [dbo].[XOZ_OPER] XO
		INNER JOIN [dbo].[XOZ_OPER_GROUP] XOG ON XO.GROUP_LINK = XOG.LINK) X 
		ON LTRIM(RTRIM(TG2.XOG_CODE)) = LTRIM(RTRIM(X.XOG_CODE)) AND LTRIM(RTRIM(TG2.XO_CODE)) = LTRIM(RTRIM(X.XO_CODE))

INSERT INTO dbo.G_PROV_AP (LINK_UP,DB_KR,ACCOUNT,EKR,SGU)
SELECT DISTINCT
	LINK_UP = R.LINK1, TGAP.DB_KR, ACCOUNT = SA.LINK, EKR = T_EKR.LINK, SGU = T_SGU.LINK
FROM
	#G_PROV2_REC R
	INNER JOIN dbo.G_PROV2 G2 ON G2.LINK = R.LINK1
	INNER JOIN dbo.G_PROV1 G1 ON G2.LINK_UP = G1.LINK
	INNER JOIN #tmp_G_PROV_AP TGAP ON G2.LINK2 = TGAP.LINK_UP
	INNER JOIN dbo.S_ACCOUNTS SA ON SA.CODE like LTRIM(RTRIM(TGAP.ACCOUNT))
	LEFT JOIN [dbo].[KOSGU] T_EKR ON T_EKR.CODE = TGAP.EKR
	LEFT JOIN [dbo].[KOSGU] T_SGU ON T_SGU.CODE = TGAP.SGU

--ЗАВЕРШАЮЩИЕ ОПЕРАЦИИ:
--1. Удаление временных колонок
IF COLUMNPROPERTY(object_id('[dbo].[G_PROV1]'), 'LINK2', 'AllowsNull') is NOT NULL
   ALTER TABLE [dbo].[G_PROV1] DROP COLUMN [LINK2]

IF COLUMNPROPERTY(object_id('[dbo].[G_PROV2]'), 'LINK2', 'AllowsNull') is NOT NULL
   ALTER TABLE [dbo].[G_PROV2] DROP COLUMN [LINK2]
GO

--2. Удаление типовых операций без проводок
DELETE FROM dbo.G_PROV1
WHERE
	EXISTS (SELECT * FROM #G_PROV1_REC R WHERE R.LINK1 = dbo.G_PROV1.LINK)
	AND NOT EXISTS (
		SELECT *
		FROM dbo.G_PROV2 G2 INNER JOIN dbo.G_PROV_AP GAP ON GAP.LINK_UP = G2.LINK
		WHERE G2.LINK_UP = dbo.G_PROV1.LINK)
GO


--Добавление в настройки документа "Типовая операция"
--Сгенерировано скриптом: EXECUTE dbo.[UNLOAD_XD_DOC_NASTR_TO] @NAME_OPER = 'Начисление отпускных (компенсации) за счет резерва  (Дт401.60-Кт302.11)'

SET NOCOUNT ON


IF OBJECT_ID('TEMPDB..#tmp_XD_DOC_NASTR_TO') IS NOT NULL
	DROP TABLE #tmp_XD_DOC_NASTR_TO


CREATE TABLE #tmp_XD_DOC_NASTR_TO (
	[SO_CODE] VARCHAR(30),
	[NAME_OPER] VARCHAR(2000),
	[OSN] tinyint)

INSERT INTO #tmp_XD_DOC_NASTR_TO ([SO_CODE], [NAME_OPER], [OSN]) 
VALUES('DOCUMENTS_SALARY', 'Начисление отпускных (компенсации) за счет резерва  (Дт401.60-Кт302.11)', 0)

IF OBJECT_ID('TEMPDB..#G_PROV1_REC') IS NOT NULL
	DROP TABLE #G_PROV1_REC

CREATE TABLE #G_PROV1_REC (LINK1 INT, LINK2 INT)

INSERT INTO dbo.DOC_NASTR (LINK, PRINT_SGU, PRINT_KBK, AN_PERIOD, AN_ORG, AN_BEGIN, AN_SHABLON) 
SELECT DISTINCT SO.LINK, PRINT_SGU=0, PRINT_KBK=0, AN_PERIOD=0, AN_ORG=0, AN_BEGIN=0, AN_SHABLON=''
FROM
	#tmp_XD_DOC_NASTR_TO T
	INNER JOIN dbo.S_OBJECTS SO ON SO.CODE LIKE T.SO_CODE
WHERE
	NOT EXISTS (SELECT * FROM dbo.DOC_NASTR DN WHERE DN.[LINK] = SO.LINK)

INSERT INTO 
	[dbo].[DOC_NASTR_T1] (LINK_UP, LINK_OPER, OSN)
SELECT 
	DN.LINK, G1.LINK, T.OSN
FROM
	#tmp_XD_DOC_NASTR_TO T
	INNER JOIN dbo.S_OBJECTS SO ON SO.CODE = T.SO_CODE
	INNER JOIN dbo.DOC_NASTR DN ON DN.[LINK] = SO.LINK
	INNER JOIN dbo.G_PROV1 G1 ON G1.NAME_OPER = T.[NAME_OPER]
	INNER JOIN dbo.G_PROV G ON G.LINK = G1.LINK_UP
	INNER JOIN dbo.S_OBJECTS SO2 ON SO2.LINK = G.[OBJECT] AND SO2.CODE = 'SHABLON_DOCUMENTS_PROV'
WHERE
	NOT EXISTS ( SELECT * FROM [dbo].[DOC_NASTR_T1] N WHERE N.LINK_UP = DN.LINK AND N.[LINK_OPER] = G1.LINK)

GO

--установить для всех видов начисления отпускных типовую операцию за счет резерва
UPDATE P
SET P.LINK_OPER3 = G1.LINK
FROM
	dbo.S_OBJECTS SO
	INNER JOIN dbo.G_PROV G ON G.[OBJECT] = SO.LINK
	INNER JOIN dbo.G_PROV1 G1 ON G1.LINK_UP = G.LINK
	INNER JOIN dbo.PAYS P ON P.WAY_CALC = 15
WHERE
	SO.CODE = 'SHABLON_DOCUMENTS_PROV'
	AND
	G1.NAME_OPER = 'Начисление отпускных (компенсации) за счет резерва  (Дт401.60-Кт302.11)'
GO


GO
/****** Объект: Нумерация пачек с общей пачки РСВ-1******/


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='SA_SZV4_OPT3'

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_SA_SZV4_OPT3]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_SA_SZV4_OPT3]

CREATE TABLE  dbo._UPD_OPT_SA_SZV4_OPT3 (CODE VARCHAR(30), [SID] varbinary(85), VALUE VARCHAR(1000))

INSERT INTO _UPD_OPT_SA_SZV4_OPT3 (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 = 'SA_SZV4_OPT3')
	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_OPT3')
	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_OPT3')
	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_OPT3')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_OPT3'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'SA_SZV4_OPT3')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='SA_SZV4_OPT3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'SA_SZV4_OPT3', 'Нумерация пачек с общей пачки РСВ-1', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV4_OPTIONS'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,0
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'SA_SZV4_OPT3', NAME = 'Нумерация пачек с общей пачки РСВ-1', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SA_SZV4_OPTIONS'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='SA_SZV4_OPT3'
GO
EXEC X_SET_PROP 'SA_SZV4_OPT3', 'TITLE', 'Нумерация пачек с общей пачки РСВ-1'
GO
EXEC X_SET_PROP 'SA_SZV4_OPT3', 'VISIBLE', '2'
GO
EXEC X_SET_PROP 'SA_SZV4_OPT3', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'SA_SZV4_OPT3', 'STORAGE', 'S_OPTIONS'
GO
EXEC X_SET_PROP 'SA_SZV4_OPT3', 'TYPE_FIELD_DICT', 'tinyint'
GO
EXEC X_SET_PROP 'SA_SZV4_OPT3', 'CONTROL_NAME_EDIT', 'ACheckBox3'
GO
EXEC X_SET_PROP 'SA_SZV4_OPT3', 'COMMENTARY', 'Настройка устанавливает порядок нумерации пачек. При установленной настройке нумерация начнется с пачки с ведомостью РСВ-1.'
GO
/******--Восстановить, либо установить настройки на базе пользователя ******/
DELETE FROM dbo.S_OPTIONS WHERE SID IS NULL AND EXISTS (SELECT * FROM  dbo.S_OBJECTS SO WHERE SO.CODE = 'SA_SZV4_OPT3' AND SO.LINK = [OBJECT])
GO

IF EXISTS (SELECT * FROM [dbo].[_UPD_OPT_SA_SZV4_OPT3] WHERE CODE = 'SA_SZV4_OPT3')
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT (SELECT TOP 1 LINK FROM  dbo.S_OBJECTS WHERE CODE = 'SA_SZV4_OPT3'), SID, VALUE FROM [dbo].[_UPD_OPT_SA_SZV4_OPT3] WHERE CODE = 'SA_SZV4_OPT3'
ELSE 
	INSERT INTO dbo.S_OPTIONS ([OBJECT],SID,VALUE)
	SELECT LINK, NULL, '1' FROM  dbo.S_OBJECTS WHERE CODE = 'SA_SZV4_OPT3'

GO


IF exists(select * from sysobjects where id = object_id('[dbo].[_UPD_OPT_SA_SZV4_OPT3]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	DROP TABLE [dbo].[_UPD_OPT_SA_SZV4_OPT3]

GO


/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/
EXEC DBO.W_SPERM_WRITE 'SA_SZV4_OPT3', 'Кадры-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SA_SZV4_OPT3', 'Зарплата-КС', 63,0
GO
EXEC DBO.W_SPERM_WRITE 'SA_SZV4_OPT3', 'Кадры-КС (чтение)', 5,26
GO


GO
/**Производственный график на 2014 год убран из установки фиксированных настроек , теперь ведется история */
DECLARE @YEAR INT , @TD_LINK INT, @TITLE VARCHAR(254)
--- Для баз, которые еще не устанавливали фиксированные настройки
IF EXISTS( SELECT * FROM HOLIDAYS WHERE [YEAR] = 1900  )
	UPDATE HOLIDAYS SET   [YEAR] = 2015 	
	WHERE [YEAR] = 1900 
---------------------------------------------------------------
SET @YEAR = '2014' 
--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ

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

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

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

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

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

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

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

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

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

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

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



/*Производственный график на 2015 год  убран из установки фиксированных настроек , теперь ведется история*/
		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
SET @YEAR = '2015' 		
IF NOT EXISTS ( select * from HOLIDAYS WHERE [year] = @YEAR )
begin

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

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

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

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


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

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

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

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

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

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

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

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

END

/*Производственный график на 2016 год убран из установки фиксированных настроек , теперь ведется история*/
SET @YEAR = '2016' 		
IF NOT EXISTS ( select * from HOLIDAYS WHERE [year] = @YEAR )
begin
	--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE WORK_D = 11)
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРАЗДНИЧНЫХ ДНЕЙ
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL,[YEAR])
			SELECT	'1 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 1, 1, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'2 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 2, 1, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'3 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 3, 1, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'4 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 4, 1, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'5 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 5, 1, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'6 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 6, 1, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'7 ЯНВАРЯ (РОЖДЕСТВО ХРИСТОВО)', 7, 1, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'8 ЯНВАРЯ (НОВОГОДНИЕ КАНИКУЛЫ)', 8, 1, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'23 ФЕВРАЛЯ (ДЕНЬ ЗАЩИТНИКА ОТЕЧЕСТВА)', 23, 2, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'8 МАРТА (МЕЖДУНАРОДНЫЙ ЖЕНСКИЙ ДЕНЬ)', 8, 3, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'1 МАЯ (ПРАЗДНИК ВЕСНЫ И ТРУДА)', 1, 5, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'9 МАЯ (ДЕНЬ ПОБЕДЫ)', 9, 5, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'12 ИЮНЯ (ДЕНЬ РОССИИ)', 12, 6, @TD_LINK, 1,@YEAR
			UNION ALL
			SELECT	'4 НОЯБРЯ (ДЕНЬ НАРОДНОГО ЕДИНСТВА)', 4, 11, @TD_LINK, 1,@YEAR

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

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

		--ОПРЕДЛЕНИЕ ССЫЛКИ НА ПРЕДПРАЗДНИЧНЫЙ ТИП ДНЯ
		SET @TD_LINK = (SELECT TOP 1 LINK FROM TYP_DAYS WHERE SYMB = 'П')
		IF COALESCE(@TD_LINK,0) > 0
			-- ДОБАЛЕНИЕ НОВЫХ ПРЕДПРАЗДНИЧНЫХ ДНЕЙ ГОД
			INSERT	HOLIDAYS (NAME, DAY, MONTH, TD_LINK, TYPE_HOL, DAY1, MONTH1,[YEAR])
			SELECT	'20 ФЕВРАЛЯ', 20, 2, @TD_LINK, 2, NULL, NULL,@YEAR
			UNION ALL
			SELECT	'3 НОЯБРЯ', 3, 11, @TD_LINK, 2, NULL, NULL,@YEAR

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

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

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

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

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

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

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

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

GO
		
GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА:  Справочник План счетов для фломы 0503175 С КОДОМ R_SPR_0503175_2015------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_0503175_2015'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_0503175_2015', ' Справочник План счетов для фломы 0503175', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник  Справочник План счетов для фломы 0503175 (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_0503175_2015]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_0503175_2015' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_0503175_2015] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503175_2015')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503175_2015'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_2015', ' Справочник План счетов для фломы 0503175', 208, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_2015', NAME = ' Справочник План счетов для фломы 0503175', ORDERS = '208', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_2015'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_2015_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_2015_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_2015_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_2015_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_2015_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_2015_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_2015_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_2015_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_2015_Name'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015', 'TITLE', ' Справочник План счетов для фломы 0503175'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_0503175_2015'')'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_0503175_2015'')'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015', 'SERVER_TABLE_NAME', 'R_SPR_0503175_2015'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_0503175_2015'''
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_2015', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_2015', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_2015', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_2015', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503175_2015',0,' Справочник План счетов для фломы 0503175','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='FORM_2011' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503175_2015',@link_self,' Справочник План счетов для фломы 0503175','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_0503175_2015')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_0503175_2015')
delete report_kbk where code_form= 'R_SPR_0503175_2015'
declare @LS int
insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211000',0,'R_SPR_0503175_2015',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211200',0,'R_SPR_0503175_2015',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211210',0,'R_SPR_0503175_2015',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211211',0,'R_SPR_0503175_2015',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211212',0,'R_SPR_0503175_2015',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211213',0,'R_SPR_0503175_2015',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211220',0,'R_SPR_0503175_2015',1,'Принятые обязательства по оплате работ, услуг',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211221',0,'R_SPR_0503175_2015',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211222',0,'R_SPR_0503175_2015',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211223',0,'R_SPR_0503175_2015',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211224',0,'R_SPR_0503175_2015',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211225',0,'R_SPR_0503175_2015',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211226',0,'R_SPR_0503175_2015',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211230',0,'R_SPR_0503175_2015',1,'Принятые обязательства по обслуживанию государственного (муниципального) долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211231',0,'R_SPR_0503175_2015',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211232',0,'R_SPR_0503175_2015',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211240',0,'R_SPR_0503175_2015',1,'Принятые обязательства по безвозмездным перечисления организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211241',0,'R_SPR_0503175_2015',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211242',0,'R_SPR_0503175_2015',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211250',0,'R_SPR_0503175_2015',1,'Принятые обязательства по безвозмездным перечисления бюджетам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211251',0,'R_SPR_0503175_2015',1,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', '20140101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211252',0,'R_SPR_0503175_2015',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211253',0,'R_SPR_0503175_2015',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211260',0,'R_SPR_0503175_2015',1,'Принятые бюджетные обязательства по социальному обеспечению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211262',0,'R_SPR_0503175_2015',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211263',0,'R_SPR_0503175_2015',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211290',0,'R_SPR_0503175_2015',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211300',0,'R_SPR_0503175_2015',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211310',0,'R_SPR_0503175_2015',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211320',0,'R_SPR_0503175_2015',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211330',0,'R_SPR_0503175_2015',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211340',0,'R_SPR_0503175_2015',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211500',0,'R_SPR_0503175_2015',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211510',0,'R_SPR_0503175_2015',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211520',0,'R_SPR_0503175_2015',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211530',0,'R_SPR_0503175_2015',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211540',0,'R_SPR_0503175_2015',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211550',0,'R_SPR_0503175_2015',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211800',0,'R_SPR_0503175_2015',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211810',0,'R_SPR_0503175_2015',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211820',0,'R_SPR_0503175_2015',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212000',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212200',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212210',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212211',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212212',0,'R_SPR_0503175_2015',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212213',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212220',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по оплате работ, услуг',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212221',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212222',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212223',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212224',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212225',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212226',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212230',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по обслуживанию долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212231',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212232',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212240',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212241',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212242',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212250',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по безвозмездным перечислениям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212252',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212253',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212260',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по социальному обеспечению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212262',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212263',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212290',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212300',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212310',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212320',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212330',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212340',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212500',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212510',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212520',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212530',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212540',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по предоставлению займов (ссуд)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212550',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212800',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212810',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по погашению задолженности перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212820',0,'R_SPR_0503175_2015',1,'Принятые денежные обязательства по погашению задолженности перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '888888888',0,'R_SPR_0503175_2015',1,'Всего',0,'',0,'','', '20140101',NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_0503175_2015'

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Справочник План счетов для фломы 0503175 т3 С КОДОМ R_SPR_0503175_2015_t3------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_0503175_2015_t3'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_0503175_2015_t3', 'Справочник План счетов для фломы 0503175 т3', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Справочник План счетов для фломы 0503175 т3 (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_0503175_2015_t3]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_0503175_2015_t3' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_0503175_2015_t3] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503175_2015_t3')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503175_2015_t3'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_t3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_2015_t3', 'Справочник План счетов для фломы 0503175 т3', 216, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_2015_t3', NAME = 'Справочник План счетов для фломы 0503175 т3', ORDERS = '216', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_2015_t3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_t3_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_2015_t3_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_t3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_2015_t3_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_t3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_2015_t3_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_t3_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_2015_t3_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_t3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_2015_t3_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_t3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_2015_t3_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_t3_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_2015_t3_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_t3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_2015_t3_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_t3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_2015_t3_Name'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_t3', 'TITLE', 'Справочник План счетов для фломы 0503175 т3'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_t3', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_0503175_2015_t3'')'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_t3', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_0503175_2015_t3'')'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_t3', 'SERVER_TABLE_NAME', 'R_SPR_0503175_2015_t3'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_t3', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_0503175_2015_t3'''
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_t3_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_t3_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_t3_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_t3_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_t3_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_t3_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_t3_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_t3_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_t3_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_t3_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_t3_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_2015_t3', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_2015_t3', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_2015_t3', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_2015_t3', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503175_2015_t3',0,'Справочник План счетов для фломы 0503175 т3','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='FORM_2011' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503175_2015_t3',@link_self,'Справочник План счетов для фломы 0503175 т3','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_0503175_2015_t3')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_0503175_2015_t3')
delete report_kbk where code_form= 'R_SPR_0503175_2015_t3'
declare @LS int
insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211000',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211200',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211210',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211211',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211212',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211213',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211220',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по оплате работ, услуг',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211221',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211222',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211223',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211224',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211225',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211226',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211230',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по обслуживанию государственного (муниципального) долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211231',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211232',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211240',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по безвозмездным перечисления организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211241',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211242',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211250',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по безвозмездным перечисления бюджетам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211251',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', '20140101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211252',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211253',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211260',0,'R_SPR_0503175_2015_t3',1,'Принятые бюджетные обязательства по социальному обеспечению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211262',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211263',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211290',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211300',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211310',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211320',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211330',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211340',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211500',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211510',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211520',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211530',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211540',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211550',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211800',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211810',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211820',0,'R_SPR_0503175_2015_t3',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '888888888',0,'R_SPR_0503175_2015_t3',1,'Всего',0,'',0,'','', '20140101',NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_0503175_2015_t3'

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА:  Справочник План счетов для фломы 0503175 т4 С КОДОМ R_SPR_0503175_2015_T4------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_0503175_2015_T4'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_0503175_2015_T4', ' Справочник План счетов для фломы 0503175 т4', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник  Справочник План счетов для фломы 0503175 т4 (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_0503175_2015_T4]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_0503175_2015_T4' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_0503175_2015_T4] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503175_2015_T4')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503175_2015_T4'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_T4')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_2015_T4', ' Справочник План счетов для фломы 0503175 т4', 215, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_2015_T4', NAME = ' Справочник План счетов для фломы 0503175 т4', ORDERS = '215', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_2015_T4'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_T4_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_2015_T4_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_T4'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_2015_T4_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_T4'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_2015_T4_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_T4_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_2015_T4_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_T4'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_2015_T4_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_T4'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_2015_T4_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_T4_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_2015_T4_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_T4'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_2015_T4_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_2015_T4'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_2015_T4_Name'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_T4', 'TITLE', ' Справочник План счетов для фломы 0503175 т4'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_T4', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_0503175_2015_T4'')'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_T4', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_0503175_2015_T4'')'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_T4', 'SERVER_TABLE_NAME', 'R_SPR_0503175_2015_T4'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_T4', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_0503175_2015_T4'''
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_T4_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_T4_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_T4_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_T4_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_T4_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_T4_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_T4_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_T4_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_T4_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_T4_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_0503175_2015_T4_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_2015_T4', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_2015_T4', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_2015_T4', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_2015_T4', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503175_2015_T4',0,' Справочник План счетов для фломы 0503175 т4','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='FORM_2011' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503175_2015_T4',@link_self,' Справочник План счетов для фломы 0503175 т4','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_0503175_2015_T4')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_0503175_2015_T4')
delete report_kbk where code_form= 'R_SPR_0503175_2015_T4'
declare @LS int
insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217000',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217211',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по заработной плате на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217212',0,'R_SPR_0503175_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217213',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217221',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по услугам связи на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217222',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по транспортным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217223',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по коммунальным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217224',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217225',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217226',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217231',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217232',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217241',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217242',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217252',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217253',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217262',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217263',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217290',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по прочим расходам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217310',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217320',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217330',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217340',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217510',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217520',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217530',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217540',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217550',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217560',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217610',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217620',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217630',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217640',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217650',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217660',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227000',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227211',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по заработной плате  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227212',0,'R_SPR_0503175_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227213',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227221',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по услугам связи  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227222',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227223',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227224',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227225',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227226',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227231',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227232',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227241',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227242',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227252',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227253',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227262',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227263',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227290',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по прочим расходам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227310',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227320',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227330',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227340',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227510',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227520',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227530',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227540',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227550',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227560',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227610',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227620',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227630',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227640',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227650',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227660',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237000',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237211',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237212',0,'R_SPR_0503175_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237213',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237221',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237222',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237223',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237224',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237225',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237226',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237231',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237232',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237241',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237242',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237252',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237253',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237262',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237263',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237290',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237310',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237320',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237330',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237340',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237510',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237520',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237530',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237540',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237550',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237560',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237610',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237620',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237630',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237640',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237650',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237660',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247000',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247211',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247212',0,'R_SPR_0503175_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247213',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247221',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247222',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247223',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247224',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247225',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247226',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247231',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247232',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247241',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247242',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247252',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247253',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247262',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247263',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247290',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247310',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247320',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247330',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247340',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247510',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247520',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247530',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247540',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247550',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247560',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247610',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247620',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247630',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247640',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247650',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247660',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297000',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297211',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по заработной плате  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297212',0,'R_SPR_0503175_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297213',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297221',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по услугам связи  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297222',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297223',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297224',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297225',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297226',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297231',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297232',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297241',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297242',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297252',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297253',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297262',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297263',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297290',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства по прочим расходам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297310',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297320',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297330',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297340',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297510',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297520',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297530',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297540',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297550',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297560',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297610',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297620',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297630',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297640',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297650',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297660',0,'R_SPR_0503175_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '888888888',0,'R_SPR_0503175_2015_T4',1,'Всего',0,'',0,'','', '20140101',NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_0503175_2015_T4'

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Причина_неисполнения_0503175G_015_т1,2 С КОДОМ R_SPR_0503175_REASON_12------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_0503175_REASON_12'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_0503175_REASON_12', 'Причина_неисполнения_0503175G_015_т1,2', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Причина_неисполнения_0503175G_015_т1,2 (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_0503175_REASON_12]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_0503175_REASON_12' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_0503175_REASON_12] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503175_REASON_12')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503175_REASON_12'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_12')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_REASON_12', 'Причина_неисполнения_0503175G_015_т1,2', 210, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_REASON_12', NAME = 'Причина_неисполнения_0503175G_015_т1,2', ORDERS = '210', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_REASON_12'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_12_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_REASON_12_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_12'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_REASON_12_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_12'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_REASON_12_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_12_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_REASON_12_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_12'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_REASON_12_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_12'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_REASON_12_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_12_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_REASON_12_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_12'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_REASON_12_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_12'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_REASON_12_Name'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_12', 'TITLE', 'Причина_неисполнения_0503175G_015_т1,2'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_12', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_0503175_REASON_12'')'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_12', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_0503175_REASON_12'')'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_12', 'SERVER_TABLE_NAME', 'R_SPR_0503175_REASON_12'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_12', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_0503175_REASON_12'''
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_12_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_12_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_12_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_12_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_12_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_12_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_12_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_12_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_12_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_12_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_12_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_REASON_12', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_REASON_12', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_REASON_12', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_REASON_12', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503175_REASON_12',0,'Причина_неисполнения_0503175G_015_т1,2','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='FORM_2011' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503175_REASON_12',@link_self,'Причина_неисполнения_0503175G_015_т1,2','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_0503175_REASON_12')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_0503175_REASON_12')
delete report_kbk where code_form= 'R_SPR_0503175_REASON_12'
declare @LS int
insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '01',0,'R_SPR_0503175_REASON_12',1,'контрагентами нарушены сроки выполнения работ, работы по договору в установленный срок не выполнены',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '02',0,'R_SPR_0503175_REASON_12',1,'документы на оплату контрагентом представлены по окончанию отчетного периода',0,'',0,'','', '20150101',NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_0503175_REASON_12'

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Причина_неисполнения_0503175G_015_т3 С КОДОМ R_SPR_0503175_REASON_3------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_0503175_REASON_3'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_0503175_REASON_3', 'Причина_неисполнения_0503175G_015_т3', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Причина_неисполнения_0503175G_015_т3 (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_0503175_REASON_3]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_0503175_REASON_3' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_0503175_REASON_3] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503175_REASON_3')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503175_REASON_3'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_REASON_3', 'Причина_неисполнения_0503175G_015_т3', 211, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_REASON_3', NAME = 'Причина_неисполнения_0503175G_015_т3', ORDERS = '211', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_REASON_3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_3_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_REASON_3_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_REASON_3_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_REASON_3_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_3_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_REASON_3_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_REASON_3_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_REASON_3_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_3_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503175_REASON_3_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503175_REASON_3_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503175_REASON_3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503175_REASON_3_Name'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_3', 'TITLE', 'Причина_неисполнения_0503175G_015_т3'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_3', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_0503175_REASON_3'')'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_3', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_0503175_REASON_3'')'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_3', 'SERVER_TABLE_NAME', 'R_SPR_0503175_REASON_3'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_3', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_0503175_REASON_3'''
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_3_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_3_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_3_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_3_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_3_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_3_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_3_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_3_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_3_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_3_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_0503175_REASON_3_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_REASON_3', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_REASON_3', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_REASON_3', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503175_REASON_3', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503175_REASON_3',0,'Причина_неисполнения_0503175G_015_т3','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='FORM_2011' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503175_REASON_3',@link_self,'Причина_неисполнения_0503175G_015_т3','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_0503175_REASON_3')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_0503175_REASON_3')
delete report_kbk where code_form= 'R_SPR_0503175_REASON_3'
declare @LS int
insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '01',0,'R_SPR_0503175_REASON_3',1,'тест',0,'',0,'','', '20150101',NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_0503175_REASON_3'

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Номер (код) счета бюджетного учета_0503775G_т1,2 С КОДОМ R_SPR_0503775_ACC_2015_T1_2------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_0503775_ACC_2015_T1_2'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_0503775_ACC_2015_T1_2', 'Номер (код) счета бюджетного учета_0503775G_т1,2', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Номер (код) счета бюджетного учета_0503775G_т1,2 (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_0503775_ACC_2015_T1_2]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_0503775_ACC_2015_T1_2' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_0503775_ACC_2015_T1_2] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503775_ACC_2015_T1_2')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503775_ACC_2015_T1_2'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T1_2')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503775_ACC_2015_T1_2', 'Номер (код) счета бюджетного учета_0503775G_т1,2', 217, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503775_ACC_2015_T1_2', NAME = 'Номер (код) счета бюджетного учета_0503775G_т1,2', ORDERS = '217', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503775_ACC_2015_T1_2'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T1_2_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503775_ACC_2015_T1_2_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T1_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503775_ACC_2015_T1_2_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T1_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503775_ACC_2015_T1_2_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T1_2_CO')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503775_ACC_2015_T1_2_CO', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T1_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503775_ACC_2015_T1_2_CO', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T1_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503775_ACC_2015_T1_2_CO'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T1_2_Na')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503775_ACC_2015_T1_2_Na', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T1_2'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503775_ACC_2015_T1_2_Na', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T1_2'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503775_ACC_2015_T1_2_Na'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T1_2', 'TITLE', 'Номер (код) счета бюджетного учета_0503775G_т1,2'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T1_2', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_0503775_ACC_2015_T1_2'')'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T1_2', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_0503775_ACC_2015_T1_2'')'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T1_2', 'SERVER_TABLE_NAME', 'R_SPR_0503775_ACC_2015_T1_2'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T1_2', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_0503775_ACC_2015_T1_2'''
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T1_2_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T1_2_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T1_2_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T1_2_CO', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T1_2_CO', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T1_2_CO', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T1_2_CO', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T1_2_Na', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T1_2_Na', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T1_2_Na', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T1_2_Na', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_0503775_ACC_2015_T1_2', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503775_ACC_2015_T1_2', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503775_ACC_2015_T1_2', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503775_ACC_2015_T1_2', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503775_ACC_2015_T1_2',0,'Номер (код) счета бюджетного учета_0503775G_т1,2','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='FORM_2011' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503775_ACC_2015_T1_2',@link_self,'Номер (код) счета бюджетного учета_0503775G_т1,2','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_0503775_ACC_2015_T1_2')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_0503775_ACC_2015_T1_2')
delete report_kbk where code_form= 'R_SPR_0503775_ACC_2015_T1_2'
declare @LS int
insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211000',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211200',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211210',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211211',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211212',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211213',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211220',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по оплате работ, услуг',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211221',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211222',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211223',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211224',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211225',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211226',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211230',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию государственного (муниципального) долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211231',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211232',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211240',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211241',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211242',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211250',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления бюджетам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211251',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', '20140101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211252',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211253',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211260',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые бюджетные обязательства по социальному обеспечению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211261',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','', '20140101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211262',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211263',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211290',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211300',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211310',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211320',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211330',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211340',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211500',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211510',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211520',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211530',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211540',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211550',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211800',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211810',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211820',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212000',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212200',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212210',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212211',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212212',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212213',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212220',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по оплате работ, услуг',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212221',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212222',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212223',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212224',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212225',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212226',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212230',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212231',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212232',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212240',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212241',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212242',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212250',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212252',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212253',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212260',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по социальному обеспечению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212262',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212263',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212290',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212300',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212310',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212320',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212330',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212340',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212500',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212510',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212520',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212530',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212540',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по предоставлению займов (ссуд)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212550',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212800',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212810',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению задолженности перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050212820',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению задолженности перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211000',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211200',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211210',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211211',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211212',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211213',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211220',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по оплате работ, услуг',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211221',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211222',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211223',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211224',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211225',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211226',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211230',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию государственного (муниципального) долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211231',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211232',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211240',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211241',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211242',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211250',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления бюджетам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211251',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', '20140101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211252',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211253',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211260',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые бюджетные обязательства по социальному обеспечению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211262',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211263',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211290',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211300',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211310',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211320',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211330',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211340',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211500',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211510',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211520',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211530',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211540',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211550',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211800',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211810',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211820',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212000',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212200',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212210',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212211',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212212',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212213',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212220',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по оплате работ, услуг',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212221',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212222',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212223',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212224',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212225',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212226',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212230',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212231',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212232',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212240',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212241',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212242',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212250',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212252',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212253',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212260',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по социальному обеспечению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212262',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212263',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212290',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212300',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212310',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212320',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212330',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212340',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212500',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212510',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212520',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212530',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212540',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по предоставлению займов (ссуд)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212550',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212800',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212810',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению задолженности перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150212820',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению задолженности перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211000',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211200',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211210',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211211',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211212',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211213',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211221',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211222',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211223',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211224',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211225',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211226',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211231',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211232',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211241',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211242',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211252',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211253',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211262',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211263',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211290',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211300',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211310',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211320',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211330',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211340',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211500',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211510',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211520',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211530',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211540',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211550',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211800',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211810',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211820',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212000',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212200',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по расходам',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212210',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212211',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212212',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212213',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212221',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212222',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212223',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212224',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212225',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212226',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212231',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212232',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212241',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212242',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212252',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212253',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212262',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212263',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212290',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212300',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212310',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212320',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212330',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212340',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212500',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212510',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212520',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212530',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212540',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по предоставлению займов (ссуд)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212550',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212800',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212810',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению задолженности перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250212820',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению задолженности перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211000',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211200',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211210',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211211',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211212',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211213',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211221',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211222',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211223',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211224',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211225',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211226',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211231',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211232',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211241',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211242',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211252',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211253',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211262',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211263',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211290',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211300',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211310',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211320',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211330',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211340',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211500',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211510',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211520',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211530',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211540',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211550',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211800',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211810',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211820',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212000',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212200',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212210',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212211',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212212',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212213',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212221',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212222',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212223',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212224',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212225',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212226',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212231',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212232',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212241',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212242',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212252',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212253',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212262',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212263',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212290',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212300',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212310',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212320',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212330',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212340',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212500',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212510',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212520',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212530',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212540',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по предоставлению займов (ссуд)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212550',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212800',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212810',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению задолженности перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350212820',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению задолженности перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211000',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211200',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211210',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211211',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211212',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211213',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211221',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211222',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211223',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211224',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211225',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211226',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211231',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211232',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211241',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211242',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211252',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211253',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211262',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211263',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211290',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211300',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211310',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211320',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211330',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211340',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211500',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211510',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211520',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211530',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211540',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211550',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211800',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211810',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211820',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212000',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212200',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212210',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212211',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212212',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212213',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212221',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212222',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212223',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212224',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212225',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212226',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212231',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212232',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212241',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212242',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212252',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212253',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212262',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212263',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212290',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212300',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212310',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212320',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212330',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212340',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212500',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212510',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212520',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212530',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212540',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по предоставлению займов (ссуд)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212550',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212800',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212810',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению задолженности перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450212820',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению задолженности перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211000',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211200',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211210',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211211',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211212',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211213',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211221',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211222',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211223',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211224',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211225',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211226',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211231',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211232',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211241',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211242',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211252',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211253',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211262',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211263',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211290',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211300',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211310',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211320',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211330',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211340',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211500',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211510',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211520',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211530',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211540',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211550',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211800',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211810',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211820',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212000',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212200',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212210',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212211',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212212',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212213',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212221',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212222',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212223',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212224',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212225',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212226',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212231',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212232',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212241',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212242',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212252',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212253',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212262',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212263',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212290',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212300',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212310',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212320',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212330',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212340',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212500',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212510',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212520',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212530',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212540',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по предоставлению займов (ссуд)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212550',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212800',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212810',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению задолженности перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550212820',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению задолженности перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211000',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211200',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211210',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211211',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211212',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211213',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211221',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211222',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211223',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211224',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211225',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211226',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211231',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211232',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211241',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211242',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211252',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211253',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211262',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211263',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211290',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211300',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211310',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211320',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211330',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211340',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211500',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211510',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211520',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211530',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211540',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211550',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211800',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211810',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211820',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212000',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212200',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212210',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212211',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212212',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212213',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212221',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212222',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212223',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212224',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212225',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212226',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212231',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212232',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212241',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212242',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212252',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212253',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212262',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212263',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212290',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212300',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212310',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212320',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212330',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212340',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212500',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212510',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212520',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212530',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212540',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по предоставлению займов (ссуд)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212550',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212800',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212810',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению задолженности перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650212820',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению задолженности перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211000',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211200',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211210',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211211',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211212',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211213',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211221',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211222',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211223',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211224',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211225',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211226',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211231',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211232',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211241',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211242',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211252',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211253',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211262',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211263',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211290',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211300',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211310',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211320',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211330',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211340',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211500',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211510',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211520',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211530',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211540',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211550',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211800',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211810',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211820',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212000',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212200',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212210',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по оплате труда и начисления на  выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212211',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212212',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные бюджетные обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212213',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212221',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212222',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212223',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212224',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212225',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212226',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по прочим работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212231',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212232',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по обслуживанию долговых обязательств перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212241',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212242',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212252',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212253',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212262',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212263',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212290',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212300',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212310',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212320',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212330',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212340',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212500',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212510',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212520',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212530',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212540',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по предоставлению займов (ссуд)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212550',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212800',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212810',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению задолженности перед резидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750212820',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Принятые денежные обязательства по погашению задолженности перед нерезидентами',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '888888888',0,'R_SPR_0503775_ACC_2015_T1_2',1,'Всего',0,'',0,'','', '20140101',NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_0503775_ACC_2015_T1_2'

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Номер (код) счета бюджетного учета_0503775G_т3 С КОДОМ R_SPR_0503775_ACC_2015_T3------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_0503775_ACC_2015_T3'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_0503775_ACC_2015_T3', 'Номер (код) счета бюджетного учета_0503775G_т3', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Номер (код) счета бюджетного учета_0503775G_т3 (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_0503775_ACC_2015_T3]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_0503775_ACC_2015_T3' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_0503775_ACC_2015_T3] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503775_ACC_2015_T3')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503775_ACC_2015_T3'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503775_ACC_2015_T3', 'Номер (код) счета бюджетного учета_0503775G_т3', 218, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503775_ACC_2015_T3', NAME = 'Номер (код) счета бюджетного учета_0503775G_т3', ORDERS = '218', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503775_ACC_2015_T3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T3_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503775_ACC_2015_T3_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503775_ACC_2015_T3_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503775_ACC_2015_T3_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T3_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503775_ACC_2015_T3_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503775_ACC_2015_T3_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503775_ACC_2015_T3_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T3_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503775_ACC_2015_T3_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503775_ACC_2015_T3_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503775_ACC_2015_T3_Name'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T3', 'TITLE', 'Номер (код) счета бюджетного учета_0503775G_т3'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T3', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_0503775_ACC_2015_T3'')'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T3', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_0503775_ACC_2015_T3'')'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T3', 'SERVER_TABLE_NAME', 'R_SPR_0503775_ACC_2015_T3'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T3', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_0503775_ACC_2015_T3'''
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T3_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T3_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T3_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T3_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T3_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T3_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T3_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T3_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T3_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T3_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T3_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_0503775_ACC_2015_T3', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503775_ACC_2015_T3', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503775_ACC_2015_T3', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503775_ACC_2015_T3', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503775_ACC_2015_T3',0,'Номер (код) счета бюджетного учета_0503775G_т3','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='FORM_2011' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503775_ACC_2015_T3',@link_self,'Номер (код) счета бюджетного учета_0503775G_т3','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_0503775_ACC_2015_T3')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_0503775_ACC_2015_T3')
delete report_kbk where code_form= 'R_SPR_0503775_ACC_2015_T3'
declare @LS int
insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211000',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211200',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211210',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211211',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211212',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211213',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211220',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по оплате работ, услуг',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211221',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211222',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211223',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211224',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211225',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211226',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211230',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию государственного (муниципального) долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211231',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211232',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211240',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211241',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211242',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211250',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления бюджетам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211251',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', '20140101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211252',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211253',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211260',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые бюджетные обязательства по социальному обеспечению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211261',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пенсиям, пособиям и выплатам по пенсионному, социальному и медицинскому страхованию населения',0,'',0,'','', '20140101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211262',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211263',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211290',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211300',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211310',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211320',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211330',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211340',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211500',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211510',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211520',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211530',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211540',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211550',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211800',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211810',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050211820',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211000',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211200',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211210',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211211',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211212',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211213',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211220',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по оплате работ, услуг',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211221',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211222',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211223',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211224',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211225',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211226',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211230',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию государственного (муниципального) долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211231',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211232',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211240',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211241',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211242',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211250',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления бюджетам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211251',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям другим бюджетам бюджетной системы Российской Федерации',0,'',0,'','', '20140101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211252',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211253',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211260',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые бюджетные обязательства по социальному обеспечению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211262',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211263',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211290',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211300',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211310',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211320',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211330',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211340',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211500',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211510',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211520',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211530',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211540',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211550',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211800',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211810',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150211820',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211000',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211200',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211210',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211211',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211212',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211213',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211221',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211222',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211223',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211224',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211225',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211226',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211231',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211232',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211241',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211242',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211252',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211253',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211262',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211263',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211290',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211300',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211310',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211320',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211330',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211340',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211500',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211510',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211520',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211530',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211540',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211550',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211800',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211810',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250211820',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211000',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211200',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211210',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211211',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211212',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211213',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211221',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211222',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211223',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211224',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211225',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211226',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211231',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211232',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211241',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211242',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211252',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211253',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211262',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211263',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211290',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211300',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211310',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211320',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211330',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211340',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211500',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211510',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211520',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211530',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211540',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211550',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211800',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211810',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350211820',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211000',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211200',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211210',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211211',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211212',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211213',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211221',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211222',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211223',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211224',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211225',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211226',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211231',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211232',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211241',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211242',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211252',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211253',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211262',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211263',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211290',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211300',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211310',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211320',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211330',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211340',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211500',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211510',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211520',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211530',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211540',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211550',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211800',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211810',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450211820',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211000',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211200',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211210',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211211',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211212',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211213',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211221',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211222',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211223',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211224',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211225',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211226',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211231',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211232',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211241',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211242',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211252',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211253',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211262',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211263',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211290',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211300',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211310',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211320',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211330',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211340',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211500',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211510',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211520',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211530',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211540',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211550',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211800',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211810',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550211820',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211000',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211200',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211210',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211211',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211212',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211213',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211221',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211222',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211223',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211224',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211225',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211226',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211231',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211232',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211241',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211242',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211252',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211253',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211262',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211263',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211290',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211300',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211310',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211320',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211330',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211340',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211500',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211510',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211520',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211530',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211540',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211550',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211800',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211810',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650211820',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211000',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211200',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211210',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по оплате труда и начислениям на выплаты по оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211211',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по заработной плате',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211212',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим выплатам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211213',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по начислениям на выплаты по  оплате труда',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211221',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства  по услугам связи',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211222',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по транспортным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211223',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по коммунальным услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211224',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по арендной плате за пользование имуществом',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211225',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по работам, услугам по содержанию имущества',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211226',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим  работам, услугам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211231',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию внутреннего долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211232',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по обслуживанию внешнего государственного долга',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211241',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления государственным и муниципальным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211242',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по безвозмездным перечисления организациям, за исключением государственных и муниципальных организаций',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211252',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211253',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по перечислениям международным организациям',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211262',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пособиям по социальной помощи населению',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211263',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211290',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по прочим расходам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211300',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению нефинансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211310',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211320',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211330',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211340',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211500',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211510',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по изменению (увеличению) остатка денежных средств учреждения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211520',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211530',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211540',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по предоставлению бюджетных кредитов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211550',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по приобретению иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211800',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению долговых обязательств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211810',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению задолженности по внутреннему долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750211820',0,'R_SPR_0503775_ACC_2015_T3',1,'Принятые обязательства по погашению задолженности по внешнему государственному  долгу',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '888888888',0,'R_SPR_0503775_ACC_2015_T3',1,'Всего',0,'',0,'','', '20140101',NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_0503775_ACC_2015_T3'

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Номер (код) счета бюджетного учета_0503775G_т4 С КОДОМ R_SPR_0503775_ACC_2015_T4------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_0503775_ACC_2015_T4'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_0503775_ACC_2015_T4', 'Номер (код) счета бюджетного учета_0503775G_т4', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Номер (код) счета бюджетного учета_0503775G_т4 (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_0503775_ACC_2015_T4]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_0503775_ACC_2015_T4' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_0503775_ACC_2015_T4] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503775_ACC_2015_T4')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503775_ACC_2015_T4'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T4')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503775_ACC_2015_T4', 'Номер (код) счета бюджетного учета_0503775G_т4', 219, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503775_ACC_2015_T4', NAME = 'Номер (код) счета бюджетного учета_0503775G_т4', ORDERS = '219', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503775_ACC_2015_T4'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T4_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503775_ACC_2015_T4_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T4'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503775_ACC_2015_T4_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T4'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503775_ACC_2015_T4_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T4_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503775_ACC_2015_T4_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T4'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503775_ACC_2015_T4_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T4'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503775_ACC_2015_T4_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T4_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503775_ACC_2015_T4_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T4'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503775_ACC_2015_T4_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_ACC_2015_T4'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503775_ACC_2015_T4_Name'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T4', 'TITLE', 'Номер (код) счета бюджетного учета_0503775G_т4'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T4', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_0503775_ACC_2015_T4'')'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T4', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_0503775_ACC_2015_T4'')'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T4', 'SERVER_TABLE_NAME', 'R_SPR_0503775_ACC_2015_T4'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T4', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_0503775_ACC_2015_T4'''
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T4_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T4_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T4_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T4_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T4_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T4_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T4_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T4_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T4_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T4_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_0503775_ACC_2015_T4_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_0503775_ACC_2015_T4', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503775_ACC_2015_T4', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503775_ACC_2015_T4', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503775_ACC_2015_T4', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503775_ACC_2015_T4',0,'Номер (код) счета бюджетного учета_0503775G_т4','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='FORM_2011' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503775_ACC_2015_T4',@link_self,'Номер (код) счета бюджетного учета_0503775G_т4','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_0503775_ACC_2015_T4')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_0503775_ACC_2015_T4')
delete report_kbk where code_form= 'R_SPR_0503775_ACC_2015_T4'
declare @LS int
insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050217660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050227660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050237660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050247660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '050297660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150217660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150227660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150237660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150247660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '150297660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250217660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250227660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250237660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250247660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '250297660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350217660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350227660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350237660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350247660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '350297660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450217660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450227660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450237660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450247660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '450297660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550217660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550227660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550237660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550247660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '550297660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650217660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650227660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650237660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650247660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '650297660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам на текущий финансовый год',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750217660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на текущий финансовый год - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на первый год, следующий за текущим (на очередной финансовый год)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750227660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на первый год, следующий за текущим (на очередной финансовый год) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

GO
declare @LS int

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за текущим (первый год, следующий за очередным)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750237660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за текущим (первый год, следующий за очередным) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на второй год, следующий за очередным',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750247660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на второй год, следующий за очередным - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297000',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297211',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по заработной плате  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297212',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые бюджетные обязательства по прочим выплатам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297213',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по начислениям на выплаты по оплате труда  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297221',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по услугам связи  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297222',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по транспортным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297223',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по коммунальным услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297224',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по арендной плате за пользование имуществом  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297225',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по работам, услугам по содержанию имущества  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297226',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим работам, услугам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297231',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед резидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297232',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по обслуживанию долговых обязательств перед нерезидентами  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297241',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям государственным и муниципальным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297242',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по безвозмездным перечислениям организациям, за исключением государственных и муниципальных организаций  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297252',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям наднациональным организациям и правительствам иностранных государств  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297253',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по перечислениям международным организациям  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297262',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пособиям по социальной помощи населению  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297263',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по пенсиям, пособиям, выплачиваемым организациями сектора государственного управления  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297290',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства по прочим расходам  на иные очередные годы (за пределами планового периода)',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297310',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости основных средств',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297320',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости нематериальных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297330',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости непроизведенных активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297340',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости материальных запасов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297510',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Поступление на счета бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297520',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297530',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297540',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение задолженности по бюджетным кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297550',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297560',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Увеличение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297610',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Выбытие со счетов бюджетов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297620',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости ценных бумаг, кроме акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297630',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости акций и иных форм участия в капитале',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297640',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение задолженности по бюджетным ссудам и кредитам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297650',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение стоимости иных финансовых активов',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '750297660',0,'R_SPR_0503775_ACC_2015_T4',1,'Принимаемые обязательства на иные очередные годы (за пределами планового периода) - Уменьшение прочей дебиторской задолженности',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '888888888',0,'R_SPR_0503775_ACC_2015_T4',1,'Всего',0,'',0,'','', '20140101',NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_0503775_ACC_2015_T4'

GO


GO
------------------- ВЫГРУЗКА СПРАВОЧНИКА: Причина_неисполнения_0503775G_2015_т3 С КОДОМ R_SPR_0503775_REASON_3------------------------

------------------- ДАННЫЕ О СПРАВОЧНИКЕ ------------------------
if object_id('tempdb..#Cols_tmp') Is NOT NULL drop table #Cols_tmp
if object_id('tempdb..#Data_tmp') Is NOT NULL drop table #Data_tmp
create table #Cols_tmp (Code varchar(50), orders tinyint, Source varchar(254), Name varchar(254), Const varchar(254), First tinyint, Cnt tinyint)
create table #Data_tmp (Table_From varchar(254), Filter varchar(254))

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('CODE', 1, 'Code', 'Код', '', 0,0)

insert #Cols_tmp (Code, orders, Source, Name, Const,First, Cnt)
values ('Name', 2, 'Name', 'Наименование', '', 0,0)

declare @link int
select @link = link from report_spr where code = 'R_SPR_0503775_REASON_3'
exec dbo.RO_SPR_SAVE @link, 'R_SPR_0503775_REASON_3', 'Причина_неисполнения_0503775G_2015_т3', '#Cols_tmp', '#Data_tmp', 1


GO



------------------- ВЬЮХА ------------------------

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


GO

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

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

	справочник Причина_неисполнения_0503775G_2015_т3 (сгенерировано Редактором справочников)

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

CREATE     VIEW dbo.[R_SPR_0503775_REASON_3]

AS

SELECT  max(LINK) as Link, max(Link_Self) as Link_Self,Code as [CODE],max(Name) as [NAME], begin_date, end_date FROM [dbo].[RO_KBK_HIST_VIEW] [REPORT_KBK] WHERE CODE_FORM = 'R_SPR_0503775_REASON_3' GROUP BY Code, begin_date, end_date

GO


GRANT SELECT ON dbo.[R_SPR_0503775_REASON_3] TO PUBLIC


GO


------------------- S_OBJECTS ------------------------
IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503775_REASON_3')
		DELETE FROM DBO.S_OBJECTS WHERE CODE = 'R_SPR_0503775_REASON_3'
GO


IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503775_REASON_3')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503775_REASON_3', 'Причина_неисполнения_0503775G_2015_т3', 220, (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503775_REASON_3', NAME = 'Причина_неисполнения_0503775G_2015_т3', ORDERS = '220', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='SPR_SYSTEM_2011'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='WEB_DICTIONARY_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503775_REASON_3'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503775_REASON_3_M')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503775_REASON_3_M', 'Маркер', 1, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_REASON_3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503775_REASON_3_M', NAME = 'Маркер', ORDERS = '1', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_REASON_3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503775_REASON_3_M'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503775_REASON_3_CODE')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503775_REASON_3_CODE', 'Код', 2, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_REASON_3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503775_REASON_3_CODE', NAME = 'Код', ORDERS = '2', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_REASON_3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503775_REASON_3_CODE'
GO
IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='R_SPR_0503775_REASON_3_Name')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'R_SPR_0503775_REASON_3_Name', 'Наименование', 3, (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_REASON_3'), (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'),0,1
ELSE
	UPDATE DBO.S_OBJECTS
	SET CODE = 'R_SPR_0503775_REASON_3_Name', NAME = 'Наименование', ORDERS = '3', LINK_SELF = (SELECT LINK FROM S_OBJECTS WHERE CODE='R_SPR_0503775_REASON_3'), LINK_CLASS = (SELECT LINK FROM S_OBJECTS WHERE CODE='EDIT_FIELD_CLASS'), MANAGED = 0, INHERITED = 0
	WHERE CODE ='R_SPR_0503775_REASON_3_Name'
GO
EXEC X_SET_PROP 'R_SPR_0503775_REASON_3', 'TITLE', 'Причина_неисполнения_0503775G_2015_т3'
GO
EXEC X_SET_PROP 'R_SPR_0503775_REASON_3', 'INIT_OBJECT_METHOD', 'x_spisok(''R_SPR_0503775_REASON_3'')'
GO
EXEC X_SET_PROP 'R_SPR_0503775_REASON_3', 'SELECT_RECORDS_METHOD', 'X_SELECT_DICTIONS(''R_SPR_0503775_REASON_3'')'
GO
EXEC X_SET_PROP 'R_SPR_0503775_REASON_3', 'SERVER_TABLE_NAME', 'R_SPR_0503775_REASON_3'
GO
EXEC X_SET_PROP 'R_SPR_0503775_REASON_3', 'SELECT_RECORDS_METHOD_SQL', 'WEB_SELECT_DICTIONARY @cDicCode=''R_SPR_0503775_REASON_3'''
GO
EXEC X_SET_PROP 'R_SPR_0503775_REASON_3_M', 'VISIBLE', '9'
GO
EXEC X_SET_PROP 'R_SPR_0503775_REASON_3_M', 'CONTROLSOURCE', 'm.cAlias + ".checked"'
GO
EXEC X_SET_PROP 'R_SPR_0503775_REASON_3_M', 'FIELD_DATA', 'CHECKED'
GO
EXEC X_SET_PROP 'R_SPR_0503775_REASON_3_CODE', 'TITLE', 'Код'
GO
EXEC X_SET_PROP 'R_SPR_0503775_REASON_3_CODE', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503775_REASON_3_CODE', 'CONTROLSOURCE', 'm.cAlias + ".CODE"'
GO
EXEC X_SET_PROP 'R_SPR_0503775_REASON_3_CODE', 'FIELD_DATA', 'CODE'
GO
EXEC X_SET_PROP 'R_SPR_0503775_REASON_3_Name', 'TITLE', 'Наименование'
GO
EXEC X_SET_PROP 'R_SPR_0503775_REASON_3_Name', 'VISIBLE', '31'
GO
EXEC X_SET_PROP 'R_SPR_0503775_REASON_3_Name', 'CONTROLSOURCE', 'm.cAlias + ".Name"'
GO
EXEC X_SET_PROP 'R_SPR_0503775_REASON_3_Name', 'FIELD_DATA', 'Name'
GO
EXEC DBO.W_SPERM_WRITE 'R_SPR_0503775_REASON_3', 'Свод-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503775_REASON_3', 'Смета-КС', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503775_REASON_3', 'Свод-КС - получатель', 63,0
GO

EXEC DBO.W_SPERM_WRITE 'R_SPR_0503775_REASON_3', 'Свод-КС - ограниченый доступ к организациям', 63,0
GO


------------------- ДАННЫЕ СПРАВОЧНИКА ------------------------
exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503775_REASON_3',0,'Причина_неисполнения_0503775G_2015_т3','HEADER'
GO

declare @link_self int
 select @link_self=link from report_kbk where code='FORM_2011' and code_form='HEADER'
 exec RN_SAVE_REPORT_KBK 0,'R_SPR_0503775_REASON_3',@link_self,'Причина_неисполнения_0503775G_2015_т3','HEADER'
GO
delete report_control_protokol
delete report_kbk_hist where link_up in (select link from report_kbk where code_form= 'R_SPR_0503775_REASON_3')
delete report_kbk_cashe where link_up in (select link from report_kbk where code_form= 'R_SPR_0503775_REASON_3')
delete report_kbk where code_form= 'R_SPR_0503775_REASON_3'
declare @LS int
insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1001',0,'R_SPR_0503775_REASON_3',1,'Изменение численности получателей выплат по публичным нормативным обязательствам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '1002',0,'R_SPR_0503775_REASON_3',1,'Индексация выплат по публичным нормативным обязательствам',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2001',0,'R_SPR_0503775_REASON_3',1,'Судебные решения',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '2002',0,'R_SPR_0503775_REASON_3',1,'Установление административного наказания в виде административного штрафа',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '3001',0,'R_SPR_0503775_REASON_3',1,'Проведение реорганизационных мероприятий',0,'',0,'','', '20150101',NULL,0

insert report_kbk (code,link_self,code_form,childrens,name,imageindex,code_str,property,add_info,long_name,begin_date, end_date, orders)
select '9000',0,'R_SPR_0503775_REASON_3',1,'Иные причины',0,'',0,'','', '20150101',NULL,0

exec dbo.[RO_KBK_CASHE_UPDATE] @vcCodeForm = 'R_SPR_0503775_REASON_3'

GO


GO
-- Отчет "Справка о неиспользованных отпусках"
-- Сгенерировано скриптом scriptObjectVar 'SQL_VAC_USED'

/*** Сам отчет ***/

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

 
GO
    
	DELETE FROM OBJECT_VAR WHERE CODE = 'SQL_VAC_USED'
	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 = 'KADRY_SQL_CATALOG'),
	'SQL_VAC_USED',NULL, NULL, 1
	

	UPDATE S_NAVIGATOR
	SET LINK_VAR = (SELECT TOP 1 LINK FROM object_var WHERE CODE = 'SQL_VAC_USED') 
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_BEFORE'),
	VALUE= 'SELECT * FROM dbo.ku_EmplNormVacationR(@dDate1) where dep_link = dbo.bk_getdepZB()  and year(per_beg) =  year(@dDate1) 
	        order by  CASE @nOption1 WHEN  1 then SUB_NAME 
									 WHEN  2 then tab								 
									 WHEN  3 then FIO end'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_PROCEDURE'),
	VALUE= '#SQL_VAC_USED'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_REPORT'),
	VALUE= 'IIF(.T.,"REP_K_20033.XLT","")'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	PROPERTY= (Select LINK from s_property where code = 'QUERY_SQL'),
	VALUE= 'CREATE PROCEDURE #SQL_VAC_USED
	@dDate1 datetime	/* Дата */,
	@nOption1 int	/* Сортировать по */
AS
BEGIN

SELECT * FROM dbo.ku_EmplNormVacationR(@dDate1) where dep_link = dbo.bk_getdepZB()  and year(per_beg) =  year(@dDate1) 
order by  CASE @nOption1 WHEN  1 then SUB_NAME 
						 WHEN  2 then tab								 
						 WHEN  3 then FIO end 

END'
	
	
	DELETE  FROM object_var_values WHERE LINK_UP = ( Select link from object_var OV where code = 'SQL_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	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_VAC_USED') 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_VAC_USED'),
	PROPERTY= (Select LINK from s_property where code = 'REPORT_EXTERNAL_GENERATOR'),
	VALUE= '0'
	
/***   Группа настроек    ***/
     
		DELETE FROM object_var WHERE CODE = 'SQL_VAC_USED_GR_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_VAC_USED'),
		'SQL_VAC_USED_GR_NASTR',NULL, NULL, 1
		
GO
/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_VAC_USED_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'),
					'Дата',2, 
					(Select link from object_var where code = 'SQL_VAC_USED_GR_NASTR'),
					'SQL_VAC_USED_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_VAC_USED_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_SQLPARAM'),
							'@dDate1'
						
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_VAC_USED_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_NASTR1'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'Текущая дата'

						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_VAC_USED_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR1') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_NASTR1'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO

/***   Настройка из группы   ***/
		
					DELETE FROM object_var WHERE CODE = 'SQL_VAC_USED_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_OPTIONGROUP'),
					'Сортировать по',11, 
					(Select link from object_var where code = 'SQL_VAC_USED_GR_NASTR'),
					'SQL_VAC_USED_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_VAC_USED_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_NASTR2'),
							(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_VAC_USED_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_NASTR2'),
							(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_VAC_USED_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_NASTR2'),
							(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_VAC_USED_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_NASTR2'),
							(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_VAC_USED_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_NASTR2'),
							(Select link from s_property where code = 'QUERY_NASTR_VALUE'),
							'подразделению'
						
GO
						
						DELETE FROM OBJECT_VAR_VALUES WHERE PROPERTY = (Select link from s_property where code = 'QUERY_NASTR_VALUE_TEXT') and LINK_UP = (Select link from object_var where code = 'SQL_VAC_USED_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_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_VAC_USED_NASTR2') 
						INSERT INTO OBJECT_VAR_VALUES(LINK_UP, PROPERTY, VALUE)
						Select ( Select link from object_var where code = 'SQL_VAC_USED_NASTR2'),
							(Select link from s_property where code = 'SQUERY_NASTR_OPTIONAL'),
							'0'
						
GO
GO
	IF EXISTS( SELECT * FROM DBO.STAFF WHERE isnull(DAYS_VAC_O,0)= 0)
	BEGIN	
		UPDATE S
			SET DAYS_VAC_O =  case when isnull(gossl,0)=0 and isnull(GR_GOS_LINK,0) = 0 then 28 else case when GG.code in (1, 2) then 35 else 30 end END
		from DBO.STAFF s
		LEFT OUTER JOIN dbo.GR_GOS GG ON GG.LINK = S.gr_gos_link 
		WHERE isnull(s.DAYS_VAC_O,0) = 0 
	END 
	
GO
	
GO
-- Сгенерировано х.п. RA_EXPORT_FORM_STRUCT. (июн 22 2015  8:15:23:947AM)
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Выгрузка структуры формы отчетности : РСВ-1 (Расчет по начисленным и уплаченным страховым взносам на ОПС и в ФСС (ФЗ от 24 июля 2009 г. № 212-ФЗ))
-- Дата ввода : 20140101
-- Дата окончания действия : 20150629
-- Версия : 2015-06-22 08:15:23.947
-- Параметры выгрузки :
-- только обновить  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] = 'РСВ-1' AND [START_DATE] = '20140101'

IF @dOLD_UPDATE_DATE > CONVERT(DATETIME,'2015-06-22 08:15:23.947',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]                = 'Расчет по начисленным и уплаченным страховым взносам на ОПС и в ФСС (ФЗ от 24 июля 2009 г. № 212-ФЗ)',
    [ExportCode]          = '          ',
    [START_DATE]          = '20140101',
    [END_DATE]            = '20150629',
    [PERIODIC]            = 2,
    [ISSVOD]              = 0,
    [ISEXPORTED]          = 0,
    [ISUSERFORM]          = 1,
    [IsKonsolid]          = 0,
    [IS_AUTOFILL]         = 0,
    [PRINT_OBJECT_METHOD] = 'sa_print_rsv_1_pfr_2014()',
    [QUERY_ADD_MODULE]    = 'RSV_1_PFR_2014.bas',
    [QUERY_BEFORE]        = '',
    [QUERY_REPMAKER]      = 'KirRepMakerMultiSheet.XLS',
    [QUERY_REPORT]        = 'RSV-1-PFR_2014.XLT',
    [QUERY_REPORT_PATH]   = '',
    [DECRIPT_PROC]        = NULL,
    [EXPORT_PROC]         = 'i_report_export_nalog',
    [IsRemoteAccess]      = 0,
    [PARAM_EXPORT]        = NULL,
    [PARAM_IMPORT]        = NULL,
    [OBJECT]              = NULL,
    [ATRIBUTS]            = 'REPORTS_ATR_PERS_UCH,REPORTS_ATR_TYPE_KOR',
    [SvodProc]            = NULL,
    [COMMENT]             = '',
    [PRINT_OBJECT_METHOD_NEW] = NULL,
    [QUERY_BEFORE_PRINT_NEW]  = 'RN_PRINT_RSV1',
    [QUERY_REPORT_NEW]        = '',
    [IS_CALC]        = 1
WHERE [LINK_FORM] = @iLINK_FORM


UPDATE dbo.[REPORT_FORMS] SET [UPDATE_DATE] = CONVERT(DATETIME,'2015-06-22 08:15:23.947',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 = '2015-06-22 08:15:23.947'
	BEGIN
		SELECT @vcMessage = 'Форма РСВ-1 с версией от ' + @vcMessage + ' уже существует. Обновление отклонено.'
	END
	ELSE BEGIN
		SELECT @vcMessage = 'Форма РСВ-1 с версией от ' + @vcMessage + ' не может быть обновлена версией от 2015-06-22 08:15:23.947. Обновление отклонено.'
	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
		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 (61.00, 'Форма № Т-2 (личная карточка)', 2688.00, 'SYS_T2_FORM', NULL, 0.00, 18221.00, NULL, 'SQUERY_USER', 'SYS_KADRY_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 (62.00, 'Лицо', 2686.00, 'SYS_2452199_0I80Z7IRM', NULL, 999.00, 61.00, 26.00, 'SQUERY_FIELD', 'SYS_T2_FORM', 'SYS_2452192_0I10UEPZ6', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (432.00, 'Специальность 1', 2686.00, 'SYS_2452214_0IN0VTJYG', NULL, 999.00, 61.00, 430.00, 'SQUERY_FIELD', 'SYS_T2_FORM', 'SYS_2452214_0IN0VNJGU', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (436.00, 'Специальность 2', 2686.00, 'SYS_2452214_0IN0VTR34', NULL, 999.00, 61.00, 431.00, 'SQUERY_FIELD', 'SYS_T2_FORM', 'SYS_2452214_0IN0VNSU4', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (465.00, 'ОКСО - 1', 2686.00, 'SYS_2452214_0IN0YNBKY', NULL, 999.00, 61.00, 463.00, 'SQUERY_FIELD', 'SYS_T2_FORM', 'SYS_2452214_0IN0YKWDY', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (469.00, 'ОКСО - 2', 2686.00, 'SYS_2452214_0IN0YNF73', NULL, 999.00, 61.00, 464.00, 'SQUERY_FIELD', 'SYS_T2_FORM', 'SYS_2452214_0IN0YKZXV', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1655.00, 'Размер листа', 2700.00, 'SYS_2452381_0NC13J9F8', NULL, 5.00, 61.00, 44.00, 'SQUERY_LINK_NASTR', 'SYS_T2_FORM', 'SYS_2452195_0I40MW571', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2088.00, 'Форма личной карточки', 2700.00, 'SYS_2452454_0PD0ISDF4', NULL, 6.00, 61.00, 44.00, 'SQUERY_LINK_NASTR', 'SYS_T2_FORM', 'SYS_2452195_0I40MW571', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (2089.00, 'Показать оклад', 2700.00, 'SYS_2452454_0PD0P4I3N', NULL, 7.00, 61.00, 49.00, 'SQUERY_LINK_NASTR', 'SYS_T2_FORM', 'SYS_2452195_0I40N8IJQ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (3593.00, 'Дата составления', 2698.00, 'SYS_815448_737109263', NULL, 1.00, 61.00, 3589.00, 'SQUERY_NASTR', 'SYS_T2_FORM', 'SYS_2452561_0SC0QQGOJ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (3594.00, 'Ссылка на лицо', 2698.00, 'SYS_T2_FORM_MAIN_PARAM', NULL, 2.00, 61.00, 3590.00, 'SQUERY_NASTR', 'SYS_T2_FORM', 'SYS_2452561_0SC0QQQDN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5791.00, 'Организация - ключ', 2686.00, 'SYS_2452716_0WP0SUNOB', NULL, 999.00, 61.00, 3423.00, 'SQUERY_FIELD', 'SYS_T2_FORM', '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 (5985.00, 'Квалификация 1', 2686.00, 'SYS_2452744_0XH0N9G5B', NULL, 999.00, 61.00, 5983.00, 'SQUERY_FIELD', 'SYS_T2_FORM', 'SYS_2452744_0XH0N6EVQ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5989.00, 'Квалификация 2', 2686.00, 'SYS_2452744_0XH0N9IL0', NULL, 999.00, 61.00, 5984.00, 'SQUERY_FIELD', 'SYS_T2_FORM', 'SYS_2452744_0XH0N6LMT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (9749.00, 'Дата приема', 2686.00, 'SYS_24BCA28F-D442-4C5A-B123-E14B5F73FD9E', NULL, 999.00, 61.00, 9748.00, 'SQUERY_FIELD', 'SYS_T2_FORM', 'SYS_BD490B9C-1A62-4B44-823E-A31AEDC52DD3', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11257.00, 'Послевуз. обр. - тип', 2689.00, 'SYS_2453114_17T0YPW9F', NULL, 999.00, 61.00, 11234.00, 'SQUERY_CALC_FIELD', 'SYS_T2_FORM', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11258.00, 'Послевуз. обр. - № док.', 2689.00, 'SYS_2453114_17T0YQI0V', NULL, 999.00, 61.00, 11234.00, 'SQUERY_CALC_FIELD', 'SYS_T2_FORM', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11259.00, 'Послевуз. обр. - наим. уч. зав', 2689.00, 'SYS_2453114_17T0YR570', NULL, 999.00, 61.00, 11234.00, 'SQUERY_CALC_FIELD', 'SYS_T2_FORM', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11260.00, 'Послевуз. обр. - специальность', 2689.00, 'SYS_2453114_17T0YRKJH', NULL, 999.00, 61.00, 11234.00, 'SQUERY_CALC_FIELD', 'SYS_T2_FORM', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11261.00, 'Послевуз. обр. - спец2', 2689.00, 'SYS_2453114_17T0YS28O', NULL, 999.00, 61.00, 11234.00, 'SQUERY_CALC_FIELD', 'SYS_T2_FORM', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11262.00, 'Послевуз. обр. - дата док.', 2689.00, 'SYS_2453114_17T0YYAAN', NULL, 999.00, 61.00, 11234.00, 'SQUERY_CALC_FIELD', 'SYS_T2_FORM', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11263.00, 'Послевуз. обр. - год оконч', 2689.00, 'SYS_2453114_17T0Z1MMF', NULL, 999.00, 61.00, 11234.00, 'SQUERY_CALC_FIELD', 'SYS_T2_FORM', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (63.00, '', 2693.00, 'SYS_2452199_0I80Z7J1C', NULL, 0.00, 62.00, 26.00, 'SQUERY_LINK_BASE', 'SYS_2452199_0I80Z7IRM', 'SYS_2452192_0I10UEPZ6', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (64.00, '', 2691.00, 'SYS_2452199_0I80Z7J26', NULL, 0.00, 62.00, 26.00, 'SQUERY_LINK_SOURCE', 'SYS_2452199_0I80Z7IRM', 'SYS_2452192_0I10UEPZ6', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (65.00, '', 2695.00, 'SYS_2452199_0I80Z7J2T', NULL, 0.00, 62.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452199_0I80Z7IRM', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (66.00, 'Фамилия', 2686.00, 'SYS_2452199_0I80Z7JL6', NULL, 999.00, 62.00, 27.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452192_0I10UFUAJ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (70.00, 'Имя', 2686.00, 'SYS_2452199_0I80Z7SAC', NULL, 999.00, 62.00, 28.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452192_0I10UGYIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (74.00, 'Отчество', 2686.00, 'SYS_2452199_0I80Z7WXW', NULL, 999.00, 62.00, 29.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452192_0I10UHD76', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (78.00, 'Дата рождения', 2686.00, 'SYS_2452199_0I80Z9M6T', NULL, 999.00, 62.00, 31.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452192_0I10X289K', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (82.00, 'Табельный номер', 2686.00, 'SYS_2452199_0I80ZD5TT', NULL, 999.00, 62.00, 32.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452192_0I10X9UPG', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (87.00, 'Пол', 2686.00, 'SYS_2452199_0I810CBQY', NULL, 999.00, 62.00, 86.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452199_0I8109IND', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (92.00, 'Дата составления', 2686.00, 'SYS_2452199_0I810RPWN', NULL, 999.00, 62.00, 91.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452199_0I810I5B6', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (98.00, 'Гражданство', 2686.00, 'SYS_2452200_0I90GVZUP', NULL, 999.00, 62.00, 96.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452200_0I90GNGTY', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (103.00, 'Место рождения', 2686.00, 'SYS_2452200_0I90IRJ3W', NULL, 999.00, 62.00, 102.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452200_0I90INCEK', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (108.00, 'Профессия', 2686.00, 'SYS_2452201_0IA0LXM0C', NULL, 999.00, 62.00, 107.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452200_0I90UF5AS', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (116.00, 'Семейное положение', 2686.00, 'SYS_2452201_0IA0MTHO8', NULL, 999.00, 62.00, 112.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452201_0IA0MD8LC', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (120.00, 'Документ - вид', 2686.00, 'SYS_2452201_0IA0MTQ0Q', NULL, 999.00, 62.00, 113.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452201_0IA0MJZ6R', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (124.00, 'Документ - дата', 2686.00, 'SYS_2452201_0IA0MTSDM', NULL, 999.00, 62.00, 115.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452201_0IA0ML22C', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (128.00, 'Документ - номер', 2686.00, 'SYS_2452201_0IA0MUAIY', NULL, 999.00, 62.00, 114.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452201_0IA0MKHKM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (135.00, 'ВУС', 2686.00, 'SYS_2452201_0IA0O7G4P', NULL, 999.00, 62.00, 38.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452193_0I20J1WP6', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (139.00, 'Звание', 2686.00, 'SYS_2452201_0IA0O7QNK', NULL, 999.00, 62.00, 132.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452201_0IA0NU9K4', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (143.00, 'Годность к военной службе', 2686.00, 'SYS_2452201_0IA0O9U0G', NULL, 999.00, 62.00, 134.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452201_0IA0O2KXN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (147.00, 'РВК', 2686.00, 'SYS_2452201_0IA0O9Z2A', NULL, 999.00, 62.00, 59.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452198_0I70S6A2B', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (151.00, 'Специальный учет', 2686.00, 'SYS_2452201_0IA0OA497', NULL, 999.00, 62.00, 37.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452193_0I20IYZNL', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (155.00, 'Звание - код', 2686.00, 'SYS_2452201_0IA0OSUPP', NULL, 999.00, 62.00, 133.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452201_0IA0NUGXQ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (165.00, 'Стаж а-1', 2686.00, 'SYS_2452201_0IA0V6RBC', NULL, 999.00, 62.00, 159.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452201_0IA0TZ59V', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (169.00, 'Стаж непрерывный', 2686.00, 'SYS_2452201_0IA0V7CJH', NULL, 999.00, 62.00, 160.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452201_0IA0U19UV', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (173.00, 'Стаж общий', 2686.00, 'SYS_2452201_0IA0V7UXZ', NULL, 999.00, 62.00, 161.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452201_0IA0U1NVH', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (177.00, 'Стаж г-1', 2686.00, 'SYS_2452201_0IA0V83YQ', NULL, 999.00, 62.00, 162.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452201_0IA0U3G7V', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (206.00, 'Семейное положение - код', 2686.00, 'SYS_2452202_0IB0TMHPA', NULL, 999.00, 62.00, 163.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452201_0IA0U3QCC', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (212.00, 'Адрес по паспорту', 2686.00, 'SYS_2452203_0IC0O01TS', NULL, 999.00, 62.00, 210.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452202_0IB0WNPH6', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (216.00, 'Адрес фактический', 2686.00, 'SYS_2452203_0IC0O0AJT', NULL, 999.00, 62.00, 211.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452203_0IC0NY0TB', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (221.00, 'Домашний телефон', 2686.00, 'SYS_2452203_0IC0ONKUH', NULL, 999.00, 62.00, 220.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452203_0IC0OI4K0', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (230.00, 'Доп - 1', 2686.00, 'SYS_2452205_0IE0KK2U6', NULL, 999.00, 62.00, 225.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452205_0IE0KF7UY', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (234.00, 'Доп - 2', 2686.00, 'SYS_2452205_0IE0KK79I', NULL, 999.00, 62.00, 226.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452205_0IE0KFGIY', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (238.00, 'Доп - 3', 2686.00, 'SYS_2452205_0IE0KKB12', NULL, 999.00, 62.00, 227.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452205_0IE0KFK05', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (242.00, 'Доп - 4', 2686.00, 'SYS_2452205_0IE0KKEJ2', NULL, 999.00, 62.00, 228.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452205_0IE0KFTKJ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (246.00, 'Доп - 5', 2686.00, 'SYS_2452205_0IE0KKGS6', NULL, 999.00, 62.00, 229.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452205_0IE0KFWWM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (268.00, 'Гражданство (код)', 2686.00, 'SYS_2452207_0IG0GM1JJ', NULL, 999.00, 62.00, 97.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452200_0I90GS8J9', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (272.00, 'Образование', 2686.00, 'SYS_2452207_0IG0HM647', NULL, 999.00, 62.00, 42.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452194_0I30N3BF2', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (284.00, 'Диплом - 1', 2686.00, 'SYS_2452207_0IG0LXRI8', NULL, 999.00, 62.00, 278.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452207_0IG0LPXK0', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (288.00, 'Диплом - 2', 2686.00, 'SYS_2452207_0IG0LXUWD', NULL, 999.00, 62.00, 282.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452207_0IG0LQP5O', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (292.00, 'Год окончания - 1', 2686.00, 'SYS_2452207_0IG0LXYXA', NULL, 999.00, 62.00, 279.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452207_0IG0LQ1NN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (296.00, 'Год окончания - 2', 2686.00, 'SYS_2452207_0IG0LY172', NULL, 999.00, 62.00, 283.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452207_0IG0LQTXE', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (300.00, 'Учебное заведение 1 - 1', 2686.00, 'SYS_2452207_0IG0LY7I6', NULL, 999.00, 62.00, 276.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452207_0IG0LPNJ6', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (304.00, 'Учебное заведение 1 - 2', 2686.00, 'SYS_2452207_0IG0LY9FS', NULL, 999.00, 62.00, 277.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452207_0IG0LPRPO', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (308.00, 'Учебное заведение 2 - 1', 2686.00, 'SYS_2452207_0IG0LYDHF', NULL, 999.00, 62.00, 280.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452207_0IG0LQ50O', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (312.00, 'Учебное заведение 2 - 2', 2686.00, 'SYS_2452207_0IG0LYG8O', NULL, 999.00, 62.00, 281.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452207_0IG0LQ7XP', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (325.00, 'Категория запаса', 2686.00, 'SYS_2452207_0IG0SJ0SM', NULL, 999.00, 62.00, 324.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452207_0IG0PBD72', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (329.00, 'Состав воинского учета', 2686.00, 'SYS_2452207_0IG0SJ73O', NULL, 999.00, 62.00, 35.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452193_0I20IQTIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (337.00, 'ИНН', 2686.00, 'SYS_2452207_0IG0TIJUB', NULL, 999.00, 62.00, 335.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452207_0IG0TC1P4', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (341.00, 'Номер СПУ', 2686.00, 'SYS_2452207_0IG0TIR37', NULL, 999.00, 62.00, 336.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452207_0IG0TF7WU', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (426.00, 'Дата увольнения', 2686.00, 'SYS_2452214_0IN0UBYHW', NULL, 999.00, 62.00, 425.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452214_0IN0TRHT2', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (433.00, '', 2693.00, 'SYS_2452214_0IN0VTMIT', NULL, 0.00, 432.00, 430.00, 'SQUERY_LINK_BASE', 'SYS_2452214_0IN0VTJYG', 'SYS_2452214_0IN0VNJGU', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (434.00, '', 2691.00, 'SYS_2452214_0IN0VTMJ9', NULL, 0.00, 432.00, 430.00, 'SQUERY_LINK_SOURCE', 'SYS_2452214_0IN0VTJYG', 'SYS_2452214_0IN0VNJGU', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (435.00, '', 2695.00, 'SYS_2452214_0IN0VTMJS', NULL, 0.00, 432.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452214_0IN0VTJYG', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (437.00, '', 2693.00, 'SYS_2452214_0IN0VTR5L', NULL, 0.00, 436.00, 431.00, 'SQUERY_LINK_BASE', 'SYS_2452214_0IN0VTR34', 'SYS_2452214_0IN0VNSU4', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (438.00, '', 2691.00, 'SYS_2452214_0IN0VTR5W', NULL, 0.00, 436.00, 431.00, 'SQUERY_LINK_SOURCE', 'SYS_2452214_0IN0VTR34', 'SYS_2452214_0IN0VNSU4', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (439.00, '', 2695.00, 'SYS_2452214_0IN0VTR68', NULL, 0.00, 436.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452214_0IN0VTR34', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (466.00, '', 2693.00, 'SYS_2452214_0IN0YNBPE', NULL, 0.00, 465.00, 463.00, 'SQUERY_LINK_BASE', 'SYS_2452214_0IN0YNBKY', 'SYS_2452214_0IN0YKWDY', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (467.00, '', 2691.00, 'SYS_2452214_0IN0YNBQG', NULL, 0.00, 465.00, 463.00, 'SQUERY_LINK_SOURCE', 'SYS_2452214_0IN0YNBKY', 'SYS_2452214_0IN0YKWDY', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (468.00, '', 2695.00, 'SYS_2452214_0IN0YNBQY', NULL, 0.00, 465.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452214_0IN0YNBKY', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (470.00, '', 2693.00, 'SYS_2452214_0IN0YNF9J', NULL, 0.00, 469.00, 464.00, 'SQUERY_LINK_BASE', 'SYS_2452214_0IN0YNF73', 'SYS_2452214_0IN0YKZXV', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (471.00, '', 2691.00, 'SYS_2452214_0IN0YNF9T', NULL, 0.00, 469.00, 464.00, 'SQUERY_LINK_SOURCE', 'SYS_2452214_0IN0YNF73', 'SYS_2452214_0IN0YKZXV', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (472.00, '', 2695.00, 'SYS_2452214_0IN0YNFA5', NULL, 0.00, 469.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452214_0IN0YNF73', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (994.00, 'Документ - кем выдан', 2686.00, 'SYS_2452244_0JH0JKLCT', NULL, 999.00, 62.00, 993.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452244_0JH0IPQP7', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1002.00, 'Язык 1 -степень знания', 2686.00, 'SYS_2452244_0JH0N7EZ8', NULL, 999.00, 62.00, 1000.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452244_0JH0N1C6C', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1006.00, 'Язык 1', 2686.00, 'SYS_2452244_0JH0N7KRV', NULL, 999.00, 62.00, 998.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452244_0JH0MZ29D', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1010.00, 'Язык 2 - степень знания', 2686.00, 'SYS_2452244_0JH0N7P0K', NULL, 999.00, 62.00, 1001.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452244_0JH0N228N', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1014.00, 'Язык 2', 2686.00, 'SYS_2452244_0JH0N7SBX', NULL, 999.00, 62.00, 999.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452244_0JH0N0ZEI', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1663.00, 'Приказ об увольнении', 2686.00, 'SYS_2452385_0NG0Q710R', NULL, 999.00, 62.00, 1662.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452385_0NG0Q2XUU', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5328.00, 'Специальный учет - документ', 2686.00, 'SYS_2452669_0VE0JXYFC', NULL, 999.00, 62.00, 5327.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452669_0VE0JUQUQ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5333.00, 'Отметка о снятии с воинского учета', 2686.00, 'SYS_2452669_0VE0KHHIJ', NULL, 999.00, 62.00, 5332.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452669_0VE0KF500', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5782.00, 'Ученая степень', 2686.00, 'SYS_2452716_0WP0SCPUR', NULL, 999.00, 62.00, 1156.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452278_0KH0LSCUN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5787.00, 'Ученая степень - код', 2686.00, 'SYS_2452716_0WP0SJK9U', NULL, 999.00, 62.00, 5786.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452716_0WP0SGIRK', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5792.00, '', 2693.00, 'SYS_2452716_0WP0SUNTJ', NULL, 0.00, 5791.00, 3423.00, 'SQUERY_LINK_BASE', 'SYS_2452716_0WP0SUNOB', '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 (5793.00, '', 2691.00, 'SYS_2452716_0WP0SUNUU', NULL, 0.00, 5791.00, 3423.00, 'SQUERY_LINK_SOURCE', 'SYS_2452716_0WP0SUNOB', '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 (5794.00, '', 2695.00, 'SYS_2452716_0WP0SUNW4', NULL, 0.00, 5791.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452716_0WP0SUNOB', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5795.00, 'Наименование', 2686.00, 'SYS_2452716_0WP0SUO0H', NULL, 999.00, 5791.00, 3425.00, 'SQUERY_FIELD', 'SYS_2452716_0WP0SUNOB', 'SYS_2452558_0S90YICU0', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5799.00, 'ОКПО', 2686.00, 'SYS_2452716_0WP0SURA4', NULL, 999.00, 5791.00, 3430.00, 'SQUERY_FIELD', 'SYS_2452716_0WP0SUNOB', 'SYS_2452558_0S90YJ1FR', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5803.00, '', 2694.00, 'SYS_2452716_0WP0SV70I', NULL, 0.00, 5791.00, 4000.00, 'SQUERY_LINK_STATE', 'SYS_2452716_0WP0SUNOB', 'SYS_2452565_0SG128RND', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5986.00, '', 2693.00, 'SYS_2452744_0XH0N9GBE', NULL, 0.00, 5985.00, 5983.00, 'SQUERY_LINK_BASE', 'SYS_2452744_0XH0N9G5B', 'SYS_2452744_0XH0N6EVQ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5987.00, '', 2691.00, 'SYS_2452744_0XH0N9GDK', NULL, 0.00, 5985.00, 5983.00, 'SQUERY_LINK_SOURCE', 'SYS_2452744_0XH0N9G5B', 'SYS_2452744_0XH0N6EVQ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5988.00, '', 2695.00, 'SYS_2452744_0XH0N9GEW', NULL, 0.00, 5985.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452744_0XH0N9G5B', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5990.00, '', 2693.00, 'SYS_2452744_0XH0N9IOH', NULL, 0.00, 5989.00, 5984.00, 'SQUERY_LINK_BASE', 'SYS_2452744_0XH0N9IL0', 'SYS_2452744_0XH0N6LMT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5991.00, '', 2691.00, 'SYS_2452744_0XH0N9IPR', NULL, 0.00, 5989.00, 5984.00, 'SQUERY_LINK_SOURCE', 'SYS_2452744_0XH0N9IL0', 'SYS_2452744_0XH0N6LMT', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5992.00, '', 2695.00, 'SYS_2452744_0XH0N9IR2', NULL, 0.00, 5989.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452744_0XH0N9IL0', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6120.00, 'Дата регистрации', 2686.00, 'SYS_2452819_0ZK0SLDB9', NULL, 999.00, 62.00, 6119.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452819_0ZK0S2CQP', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6897.00, 'Трудовой договор - дата', 2686.00, 'SYS_2452878_1170VWIDI', NULL, 999.00, 62.00, 6895.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452878_1170VRMK3', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6901.00, 'Трудовой договор - номер', 2686.00, 'SYS_2452878_1170VWKIB', NULL, 999.00, 62.00, 6896.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_2452878_1170VRRVI', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (9246.00, 'Основание увольнения', 2686.00, 'SYS_9D83AA4F-B9BE-4265-A427-29615EA664D5', NULL, 999.00, 62.00, 9245.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_F190D880-FE76-4E3A-87A0-E953F4B64336', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (9744.00, 'Стаж выслуги', 2686.00, 'SYS_B15C585A-AD14-438C-A792-6343ECDC0F27', NULL, 999.00, 62.00, 9743.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_44C6AAAA-E155-48CE-81F7-4B1897B0A0A4', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (9750.00, '', 2693.00, 'SYS_CF6D191C-8AE2-4184-BBF4-C3D8172BE916', NULL, 0.00, 9749.00, 9748.00, 'SQUERY_LINK_BASE', 'SYS_24BCA28F-D442-4C5A-B123-E14B5F73FD9E', 'SYS_BD490B9C-1A62-4B44-823E-A31AEDC52DD3', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (9751.00, '', 2691.00, 'SYS_58CA8725-90D1-48A6-AD40-8A82DC57C05F', NULL, 0.00, 9749.00, 9748.00, 'SQUERY_LINK_SOURCE', 'SYS_24BCA28F-D442-4C5A-B123-E14B5F73FD9E', 'SYS_BD490B9C-1A62-4B44-823E-A31AEDC52DD3', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (9752.00, '', 2695.00, 'SYS_73680932-F35F-4A90-89BD-9D00FD50A710', NULL, 0.00, 9749.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_24BCA28F-D442-4C5A-B123-E14B5F73FD9E', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (10468.00, 'Приказ об увольнении - дата', 2686.00, 'SYS_E4A34200-71DF-423A-9A3E-0199823056C3', NULL, 999.00, 62.00, 10467.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_F0E4F3CC-D9F7-4B34-954F-2E6778B1CE46', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (10960.00, '', 2693.00, 'SYS_2453114_17T0YPWJJ', NULL, 0.00, 11257.00, 11234.00, 'SQUERY_LINK_BASE', 'SYS_2453114_17T0YPW9F', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (10965.00, '', 2693.00, 'SYS_2453114_17T0Z1MUX', NULL, 0.00, 11263.00, 11234.00, 'SQUERY_LINK_BASE', 'SYS_2453114_17T0Z1MMF', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (10966.00, '', 2693.00, 'SYS_2453114_17T0YYAIN', NULL, 0.00, 11262.00, 11234.00, 'SQUERY_LINK_BASE', 'SYS_2453114_17T0YYAAN', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (10967.00, '', 2693.00, 'SYS_2453114_17T0YS2HY', NULL, 0.00, 11261.00, 11234.00, 'SQUERY_LINK_BASE', 'SYS_2453114_17T0YS28O', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (10968.00, '', 2693.00, 'SYS_2453114_17T0YRKRF', NULL, 0.00, 11260.00, 11234.00, 'SQUERY_LINK_BASE', 'SYS_2453114_17T0YRKJH', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (10969.00, '', 2693.00, 'SYS_2453114_17T0YR5G0', NULL, 0.00, 11259.00, 11234.00, 'SQUERY_LINK_BASE', 'SYS_2453114_17T0YR570', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (10970.00, '', 2693.00, 'SYS_2453114_17T0YQI9E', NULL, 0.00, 11258.00, 11234.00, 'SQUERY_LINK_BASE', 'SYS_2453114_17T0YQI0V', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11007.00, '', 2691.00, 'SYS_2453114_17T0YQIAS', NULL, 0.00, 11258.00, 11234.00, 'SQUERY_LINK_SOURCE', 'SYS_2453114_17T0YQI0V', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11008.00, '', 2691.00, 'SYS_2453114_17T0YR5HC', NULL, 0.00, 11259.00, 11234.00, 'SQUERY_LINK_SOURCE', 'SYS_2453114_17T0YR570', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11009.00, '', 2691.00, 'SYS_2453114_17T0YRKSR', NULL, 0.00, 11260.00, 11234.00, 'SQUERY_LINK_SOURCE', 'SYS_2453114_17T0YRKJH', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11010.00, '', 2691.00, 'SYS_2453114_17T0YS2JA', NULL, 0.00, 11261.00, 11234.00, 'SQUERY_LINK_SOURCE', 'SYS_2453114_17T0YS28O', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11011.00, '', 2691.00, 'SYS_2453114_17T0YYAK0', NULL, 0.00, 11262.00, 11234.00, 'SQUERY_LINK_SOURCE', 'SYS_2453114_17T0YYAAN', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11012.00, '', 2691.00, 'SYS_2453114_17T0Z1MWA', NULL, 0.00, 11263.00, 11234.00, 'SQUERY_LINK_SOURCE', 'SYS_2453114_17T0Z1MMF', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11020.00, '', 2691.00, 'SYS_2453114_17T0YPWKX', NULL, 0.00, 11257.00, 11234.00, 'SQUERY_LINK_SOURCE', 'SYS_2453114_17T0YPW9F', 'SYS_2452559_0SA0JCBYF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11153.00, '', 2695.00, 'SYS_2453114_17T0YPWMI', NULL, 0.00, 11257.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2453114_17T0YPW9F', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11159.00, '', 2695.00, 'SYS_2453114_17T0Z1MXU', NULL, 0.00, 11263.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2453114_17T0Z1MMF', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11160.00, '', 2695.00, 'SYS_2453114_17T0YYALM', NULL, 0.00, 11262.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2453114_17T0YYAAN', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11161.00, '', 2695.00, 'SYS_2453114_17T0YS2KV', NULL, 0.00, 11261.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2453114_17T0YS28O', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11162.00, '', 2695.00, 'SYS_2453114_17T0YRKUA', NULL, 0.00, 11260.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2453114_17T0YRKJH', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11163.00, '', 2695.00, 'SYS_2453114_17T0YR5IW', NULL, 0.00, 11259.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2453114_17T0YR570', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (11164.00, '', 2695.00, 'SYS_2453114_17T0YQICA', NULL, 0.00, 11258.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2453114_17T0YQI0V', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (15665.00, 'Статус', 2686.00, 'SYS_B8FFE4E2-96EA-49DB-A8C0-A905D873A682', NULL, 999.00, 62.00, 11314.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_65A292E8-3495-4537-9AA2-5BB93B53A0DD', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (15666.00, 'Тип док. об образ. 1', 2686.00, 'SYS_E6A76FE4-F013-4DE1-8AC1-58CCEC48B95C', NULL, 999.00, 62.00, 11343.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_5E932961-B16A-4DCE-ADBE-C3669D020C57', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (15671.00, 'Тип док. об образ. 2', 2686.00, 'SYS_3A595A76-2F0E-4682-BFB5-58E7FEAD9142', NULL, 999.00, 62.00, 11344.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_3BD8BFB6-C83A-41F3-A231-845777445FFF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (15672.00, 'Характер работы', 2686.00, 'SYS_44A449E2-29E2-49C2-947D-93478E146754', NULL, 999.00, 62.00, 11480.00, 'SQUERY_FIELD', 'SYS_2452199_0I80Z7IRM', 'SYS_0190270A-E492-4E63-B2FF-EE08DCD70C01', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (67.00, '', 2693.00, 'SYS_2452199_0I80Z7JVO', NULL, 0.00, 66.00, 27.00, 'SQUERY_LINK_BASE', 'SYS_2452199_0I80Z7JL6', 'SYS_2452192_0I10UFUAJ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (68.00, '', 2691.00, 'SYS_2452199_0I80Z7JWP', NULL, 0.00, 66.00, 27.00, 'SQUERY_LINK_SOURCE', 'SYS_2452199_0I80Z7JL6', 'SYS_2452192_0I10UFUAJ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (69.00, '', 2695.00, 'SYS_2452199_0I80Z7JX0', NULL, 0.00, 66.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452199_0I80Z7JL6', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (71.00, '', 2693.00, 'SYS_2452199_0I80Z7SMC', NULL, 0.00, 70.00, 28.00, 'SQUERY_LINK_BASE', 'SYS_2452199_0I80Z7SAC', 'SYS_2452192_0I10UGYIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (72.00, '', 2691.00, 'SYS_2452199_0I80Z7SNE', NULL, 0.00, 70.00, 28.00, 'SQUERY_LINK_SOURCE', 'SYS_2452199_0I80Z7SAC', 'SYS_2452192_0I10UGYIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (73.00, '', 2695.00, 'SYS_2452199_0I80Z7SO2', NULL, 0.00, 70.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452199_0I80Z7SAC', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (75.00, '', 2693.00, 'SYS_2452199_0I80Z7X9L', NULL, 0.00, 74.00, 29.00, 'SQUERY_LINK_BASE', 'SYS_2452199_0I80Z7WXW', 'SYS_2452192_0I10UHD76', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (76.00, '', 2691.00, 'SYS_2452199_0I80Z7XAI', NULL, 0.00, 74.00, 29.00, 'SQUERY_LINK_SOURCE', 'SYS_2452199_0I80Z7WXW', 'SYS_2452192_0I10UHD76', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (77.00, '', 2695.00, 'SYS_2452199_0I80Z7XAU', NULL, 0.00, 74.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452199_0I80Z7WXW', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (79.00, '', 2693.00, 'SYS_2452199_0I80Z9MMA', NULL, 0.00, 78.00, 31.00, 'SQUERY_LINK_BASE', 'SYS_2452199_0I80Z9M6T', 'SYS_2452192_0I10X289K', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (80.00, '', 2691.00, 'SYS_2452199_0I80Z9MND', NULL, 0.00, 78.00, 31.00, 'SQUERY_LINK_SOURCE', 'SYS_2452199_0I80Z9M6T', 'SYS_2452192_0I10X289K', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (81.00, '', 2695.00, 'SYS_2452199_0I80Z9MNQ', NULL, 0.00, 78.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452199_0I80Z9M6T', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (83.00, '', 2693.00, 'SYS_2452199_0I80ZD69K', NULL, 0.00, 82.00, 32.00, 'SQUERY_LINK_BASE', 'SYS_2452199_0I80ZD5TT', 'SYS_2452192_0I10X9UPG', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (84.00, '', 2691.00, 'SYS_2452199_0I80ZD6AF', NULL, 0.00, 82.00, 32.00, 'SQUERY_LINK_SOURCE', 'SYS_2452199_0I80ZD5TT', 'SYS_2452192_0I10X9UPG', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (85.00, '', 2695.00, 'SYS_2452199_0I80ZD6AP', NULL, 0.00, 82.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452199_0I80ZD5TT', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (88.00, '', 2693.00, 'SYS_2452199_0I810CBVO', NULL, 0.00, 87.00, 86.00, 'SQUERY_LINK_BASE', 'SYS_2452199_0I810CBQY', 'SYS_2452199_0I8109IND', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (89.00, '', 2691.00, 'SYS_2452199_0I810CBVW', NULL, 0.00, 87.00, 86.00, 'SQUERY_LINK_SOURCE', 'SYS_2452199_0I810CBQY', 'SYS_2452199_0I8109IND', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (90.00, '', 2695.00, 'SYS_2452199_0I810CBW6', NULL, 0.00, 87.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452199_0I810CBQY', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (93.00, '', 2693.00, 'SYS_2452199_0I810RQ4K', NULL, 0.00, 92.00, 91.00, 'SQUERY_LINK_BASE', 'SYS_2452199_0I810RPWN', 'SYS_2452199_0I810I5B6', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (94.00, '', 2691.00, 'SYS_2452199_0I810RQ51', NULL, 0.00, 92.00, 91.00, 'SQUERY_LINK_SOURCE', 'SYS_2452199_0I810RPWN', 'SYS_2452199_0I810I5B6', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (95.00, '', 2695.00, 'SYS_2452199_0I810RQ5U', NULL, 0.00, 92.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452199_0I810RPWN', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (99.00, '', 2693.00, 'SYS_2452200_0I90GW05M', NULL, 0.00, 98.00, 96.00, 'SQUERY_LINK_BASE', 'SYS_2452200_0I90GVZUP', 'SYS_2452200_0I90GNGTY', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (100.00, '', 2691.00, 'SYS_2452200_0I90GW09W', NULL, 0.00, 98.00, 96.00, 'SQUERY_LINK_SOURCE', 'SYS_2452200_0I90GVZUP', 'SYS_2452200_0I90GNGTY', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (101.00, '', 2695.00, 'SYS_2452200_0I90GW0MM', NULL, 0.00, 98.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452200_0I90GVZUP', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (104.00, '', 2693.00, 'SYS_2452200_0I90IRJH7', NULL, 0.00, 103.00, 102.00, 'SQUERY_LINK_BASE', 'SYS_2452200_0I90IRJ3W', 'SYS_2452200_0I90INCEK', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (105.00, '', 2691.00, 'SYS_2452200_0I90IRJHG', NULL, 0.00, 103.00, 102.00, 'SQUERY_LINK_SOURCE', 'SYS_2452200_0I90IRJ3W', 'SYS_2452200_0I90INCEK', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (106.00, '', 2695.00, 'SYS_2452200_0I90IRJHQ', NULL, 0.00, 103.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452200_0I90IRJ3W', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (109.00, '', 2693.00, 'SYS_2452201_0IA0LXM39', NULL, 0.00, 108.00, 107.00, 'SQUERY_LINK_BASE', 'SYS_2452201_0IA0LXM0C', 'SYS_2452200_0I90UF5AS', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (110.00, '', 2691.00, 'SYS_2452201_0IA0LXM3H', NULL, 0.00, 108.00, 107.00, 'SQUERY_LINK_SOURCE', 'SYS_2452201_0IA0LXM0C', 'SYS_2452200_0I90UF5AS', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (111.00, '', 2695.00, 'SYS_2452201_0IA0LXM3Q', NULL, 0.00, 108.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452201_0IA0LXM0C', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (117.00, '', 2693.00, 'SYS_2452201_0IA0MTHR2', NULL, 0.00, 116.00, 112.00, 'SQUERY_LINK_BASE', 'SYS_2452201_0IA0MTHO8', 'SYS_2452201_0IA0MD8LC', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (118.00, '', 2691.00, 'SYS_2452201_0IA0MTHRB', NULL, 0.00, 116.00, 112.00, 'SQUERY_LINK_SOURCE', 'SYS_2452201_0IA0MTHO8', 'SYS_2452201_0IA0MD8LC', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (119.00, '', 2695.00, 'SYS_2452201_0IA0MTHRL', NULL, 0.00, 116.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452201_0IA0MTHO8', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (121.00, '', 2693.00, 'SYS_2452201_0IA0MTQ3H', NULL, 0.00, 120.00, 113.00, 'SQUERY_LINK_BASE', 'SYS_2452201_0IA0MTQ0Q', 'SYS_2452201_0IA0MJZ6R', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (122.00, '', 2691.00, 'SYS_2452201_0IA0MTQ3Q', NULL, 0.00, 120.00, 113.00, 'SQUERY_LINK_SOURCE', 'SYS_2452201_0IA0MTQ0Q', 'SYS_2452201_0IA0MJZ6R', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (123.00, '', 2695.00, 'SYS_2452201_0IA0MTQ6F', NULL, 0.00, 120.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452201_0IA0MTQ0Q', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (125.00, '', 2693.00, 'SYS_2452201_0IA0MTSIA', NULL, 0.00, 124.00, 115.00, 'SQUERY_LINK_BASE', 'SYS_2452201_0IA0MTSDM', 'SYS_2452201_0IA0ML22C', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (126.00, '', 2691.00, 'SYS_2452201_0IA0MTSIZ', NULL, 0.00, 124.00, 115.00, 'SQUERY_LINK_SOURCE', 'SYS_2452201_0IA0MTSDM', 'SYS_2452201_0IA0ML22C', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (127.00, '', 2695.00, 'SYS_2452201_0IA0MTSK9', NULL, 0.00, 124.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452201_0IA0MTSDM', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (129.00, '', 2693.00, 'SYS_2452201_0IA0MUALB', NULL, 0.00, 128.00, 114.00, 'SQUERY_LINK_BASE', 'SYS_2452201_0IA0MUAIY', 'SYS_2452201_0IA0MKHKM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (130.00, '', 2691.00, 'SYS_2452201_0IA0MUALN', NULL, 0.00, 128.00, 114.00, 'SQUERY_LINK_SOURCE', 'SYS_2452201_0IA0MUAIY', 'SYS_2452201_0IA0MKHKM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (131.00, '', 2695.00, 'SYS_2452201_0IA0MUAMG', NULL, 0.00, 128.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452201_0IA0MUAIY', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (136.00, '', 2693.00, 'SYS_2452201_0IA0O7GA0', NULL, 0.00, 135.00, 38.00, 'SQUERY_LINK_BASE', 'SYS_2452201_0IA0O7G4P', 'SYS_2452193_0I20J1WP6', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (137.00, '', 2691.00, 'SYS_2452201_0IA0O7GAA', NULL, 0.00, 135.00, 38.00, 'SQUERY_LINK_SOURCE', 'SYS_2452201_0IA0O7G4P', 'SYS_2452193_0I20J1WP6', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (138.00, '', 2695.00, 'SYS_2452201_0IA0O7GAX', NULL, 0.00, 135.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452201_0IA0O7G4P', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (140.00, '', 2693.00, 'SYS_2452201_0IA0O7QR5', NULL, 0.00, 139.00, 132.00, 'SQUERY_LINK_BASE', 'SYS_2452201_0IA0O7QNK', 'SYS_2452201_0IA0NU9K4', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (141.00, '', 2691.00, 'SYS_2452201_0IA0O7QRE', NULL, 0.00, 139.00, 132.00, 'SQUERY_LINK_SOURCE', 'SYS_2452201_0IA0O7QNK', 'SYS_2452201_0IA0NU9K4', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (142.00, '', 2695.00, 'SYS_2452201_0IA0O7QS3', NULL, 0.00, 139.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452201_0IA0O7QNK', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (144.00, '', 2693.00, 'SYS_2452201_0IA0O9UH8', NULL, 0.00, 143.00, 134.00, 'SQUERY_LINK_BASE', 'SYS_2452201_0IA0O9U0G', 'SYS_2452201_0IA0O2KXN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (145.00, '', 2691.00, 'SYS_2452201_0IA0O9UHN', NULL, 0.00, 143.00, 134.00, 'SQUERY_LINK_SOURCE', 'SYS_2452201_0IA0O9U0G', 'SYS_2452201_0IA0O2KXN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (146.00, '', 2695.00, 'SYS_2452201_0IA0O9UJV', NULL, 0.00, 143.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452201_0IA0O9U0G', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (148.00, '', 2693.00, 'SYS_2452201_0IA0O9Z5T', NULL, 0.00, 147.00, 59.00, 'SQUERY_LINK_BASE', 'SYS_2452201_0IA0O9Z2A', 'SYS_2452198_0I70S6A2B', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (149.00, '', 2691.00, 'SYS_2452201_0IA0O9Z79', NULL, 0.00, 147.00, 59.00, 'SQUERY_LINK_SOURCE', 'SYS_2452201_0IA0O9Z2A', 'SYS_2452198_0I70S6A2B', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (150.00, '', 2695.00, 'SYS_2452201_0IA0O9Z7X', NULL, 0.00, 147.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452201_0IA0O9Z2A', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (152.00, '', 2693.00, 'SYS_2452201_0IA0OA4BU', NULL, 0.00, 151.00, 37.00, 'SQUERY_LINK_BASE', 'SYS_2452201_0IA0OA497', 'SYS_2452193_0I20IYZNL', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (153.00, '', 2691.00, 'SYS_2452201_0IA0OA4CA', NULL, 0.00, 151.00, 37.00, 'SQUERY_LINK_SOURCE', 'SYS_2452201_0IA0OA497', 'SYS_2452193_0I20IYZNL', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (154.00, '', 2695.00, 'SYS_2452201_0IA0OA4CT', NULL, 0.00, 151.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452201_0IA0OA497', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (156.00, '', 2693.00, 'SYS_2452201_0IA0OSUU0', NULL, 0.00, 155.00, 133.00, 'SQUERY_LINK_BASE', 'SYS_2452201_0IA0OSUPP', 'SYS_2452201_0IA0NUGXQ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (157.00, '', 2691.00, 'SYS_2452201_0IA0OSUUZ', NULL, 0.00, 155.00, 133.00, 'SQUERY_LINK_SOURCE', 'SYS_2452201_0IA0OSUPP', 'SYS_2452201_0IA0NUGXQ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (158.00, '', 2695.00, 'SYS_2452201_0IA0OSUVA', NULL, 0.00, 155.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452201_0IA0OSUPP', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (166.00, '', 2693.00, 'SYS_2452201_0IA0V6REV', NULL, 0.00, 165.00, 159.00, 'SQUERY_LINK_BASE', 'SYS_2452201_0IA0V6RBC', 'SYS_2452201_0IA0TZ59V', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (167.00, '', 2691.00, 'SYS_2452201_0IA0V6RFM', NULL, 0.00, 165.00, 159.00, 'SQUERY_LINK_SOURCE', 'SYS_2452201_0IA0V6RBC', 'SYS_2452201_0IA0TZ59V', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (168.00, '', 2695.00, 'SYS_2452201_0IA0V6RFX', NULL, 0.00, 165.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452201_0IA0V6RBC', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (170.00, '', 2693.00, 'SYS_2452201_0IA0V7CLQ', NULL, 0.00, 169.00, 160.00, 'SQUERY_LINK_BASE', 'SYS_2452201_0IA0V7CJH', 'SYS_2452201_0IA0U19UV', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (171.00, '', 2691.00, 'SYS_2452201_0IA0V7CLZ', NULL, 0.00, 169.00, 160.00, 'SQUERY_LINK_SOURCE', 'SYS_2452201_0IA0V7CJH', 'SYS_2452201_0IA0U19UV', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (172.00, '', 2695.00, 'SYS_2452201_0IA0V7CM9', NULL, 0.00, 169.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452201_0IA0V7CJH', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (174.00, '', 2693.00, 'SYS_2452201_0IA0V7V07', NULL, 0.00, 173.00, 161.00, 'SQUERY_LINK_BASE', 'SYS_2452201_0IA0V7UXZ', 'SYS_2452201_0IA0U1NVH', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (175.00, '', 2691.00, 'SYS_2452201_0IA0V7V0G', NULL, 0.00, 173.00, 161.00, 'SQUERY_LINK_SOURCE', 'SYS_2452201_0IA0V7UXZ', 'SYS_2452201_0IA0U1NVH', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (176.00, '', 2695.00, 'SYS_2452201_0IA0V7V0Q', NULL, 0.00, 173.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452201_0IA0V7UXZ', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (178.00, '', 2693.00, 'SYS_2452201_0IA0V840V', NULL, 0.00, 177.00, 162.00, 'SQUERY_LINK_BASE', 'SYS_2452201_0IA0V83YQ', 'SYS_2452201_0IA0U3G7V', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (179.00, '', 2691.00, 'SYS_2452201_0IA0V8415', NULL, 0.00, 177.00, 162.00, 'SQUERY_LINK_SOURCE', 'SYS_2452201_0IA0V83YQ', 'SYS_2452201_0IA0U3G7V', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (180.00, '', 2695.00, 'SYS_2452201_0IA0V841J', NULL, 0.00, 177.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452201_0IA0V83YQ', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (207.00, '', 2693.00, 'SYS_2452202_0IB0TMHRV', NULL, 0.00, 206.00, 163.00, 'SQUERY_LINK_BASE', 'SYS_2452202_0IB0TMHPA', 'SYS_2452201_0IA0U3QCC', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (208.00, '', 2691.00, 'SYS_2452202_0IB0TMHS3', NULL, 0.00, 206.00, 163.00, 'SQUERY_LINK_SOURCE', 'SYS_2452202_0IB0TMHPA', 'SYS_2452201_0IA0U3QCC', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (209.00, '', 2695.00, 'SYS_2452202_0IB0TMHSD', NULL, 0.00, 206.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452202_0IB0TMHPA', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (213.00, '', 2693.00, 'SYS_2452203_0IC0O01Y7', NULL, 0.00, 212.00, 210.00, 'SQUERY_LINK_BASE', 'SYS_2452203_0IC0O01TS', 'SYS_2452202_0IB0WNPH6', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (214.00, '', 2691.00, 'SYS_2452203_0IC0O01YR', NULL, 0.00, 212.00, 210.00, 'SQUERY_LINK_SOURCE', 'SYS_2452203_0IC0O01TS', 'SYS_2452202_0IB0WNPH6', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (215.00, '', 2695.00, 'SYS_2452203_0IC0O01ZJ', NULL, 0.00, 212.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452203_0IC0O01TS', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (217.00, '', 2693.00, 'SYS_2452203_0IC0O0ALZ', NULL, 0.00, 216.00, 211.00, 'SQUERY_LINK_BASE', 'SYS_2452203_0IC0O0AJT', 'SYS_2452203_0IC0NY0TB', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (218.00, '', 2691.00, 'SYS_2452203_0IC0O0AM7', NULL, 0.00, 216.00, 211.00, 'SQUERY_LINK_SOURCE', 'SYS_2452203_0IC0O0AJT', 'SYS_2452203_0IC0NY0TB', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (219.00, '', 2695.00, 'SYS_2452203_0IC0O0AMG', NULL, 0.00, 216.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452203_0IC0O0AJT', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (222.00, '', 2693.00, 'SYS_2452203_0IC0ONKXL', NULL, 0.00, 221.00, 220.00, 'SQUERY_LINK_BASE', 'SYS_2452203_0IC0ONKUH', 'SYS_2452203_0IC0OI4K0', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (223.00, '', 2691.00, 'SYS_2452203_0IC0ONKXS', NULL, 0.00, 221.00, 220.00, 'SQUERY_LINK_SOURCE', 'SYS_2452203_0IC0ONKUH', 'SYS_2452203_0IC0OI4K0', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (224.00, '', 2695.00, 'SYS_2452203_0IC0ONKY1', NULL, 0.00, 221.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452203_0IC0ONKUH', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (231.00, '', 2693.00, 'SYS_2452205_0IE0KK32K', NULL, 0.00, 230.00, 225.00, 'SQUERY_LINK_BASE', 'SYS_2452205_0IE0KK2U6', 'SYS_2452205_0IE0KF7UY', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (232.00, '', 2691.00, 'SYS_2452205_0IE0KK33Y', NULL, 0.00, 230.00, 225.00, 'SQUERY_LINK_SOURCE', 'SYS_2452205_0IE0KK2U6', 'SYS_2452205_0IE0KF7UY', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (233.00, '', 2695.00, 'SYS_2452205_0IE0KK35E', NULL, 0.00, 230.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452205_0IE0KK2U6', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (235.00, '', 2693.00, 'SYS_2452205_0IE0KK7C0', NULL, 0.00, 234.00, 226.00, 'SQUERY_LINK_BASE', 'SYS_2452205_0IE0KK79I', 'SYS_2452205_0IE0KFGIY', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (236.00, '', 2691.00, 'SYS_2452205_0IE0KK7C8', NULL, 0.00, 234.00, 226.00, 'SQUERY_LINK_SOURCE', 'SYS_2452205_0IE0KK79I', 'SYS_2452205_0IE0KFGIY', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (237.00, '', 2695.00, 'SYS_2452205_0IE0KK7CP', NULL, 0.00, 234.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452205_0IE0KK79I', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (239.00, '', 2693.00, 'SYS_2452205_0IE0KKB38', NULL, 0.00, 238.00, 227.00, 'SQUERY_LINK_BASE', 'SYS_2452205_0IE0KKB12', 'SYS_2452205_0IE0KFK05', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (240.00, '', 2691.00, 'SYS_2452205_0IE0KKB3W', NULL, 0.00, 238.00, 227.00, 'SQUERY_LINK_SOURCE', 'SYS_2452205_0IE0KKB12', 'SYS_2452205_0IE0KFK05', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (241.00, '', 2695.00, 'SYS_2452205_0IE0KKB4D', NULL, 0.00, 238.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452205_0IE0KKB12', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (243.00, '', 2693.00, 'SYS_2452205_0IE0KKELB', NULL, 0.00, 242.00, 228.00, 'SQUERY_LINK_BASE', 'SYS_2452205_0IE0KKEJ2', 'SYS_2452205_0IE0KFTKJ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (244.00, '', 2691.00, 'SYS_2452205_0IE0KKEM0', NULL, 0.00, 242.00, 228.00, 'SQUERY_LINK_SOURCE', 'SYS_2452205_0IE0KKEJ2', 'SYS_2452205_0IE0KFTKJ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (245.00, '', 2695.00, 'SYS_2452205_0IE0KKEMO', NULL, 0.00, 242.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452205_0IE0KKEJ2', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (247.00, '', 2693.00, 'SYS_2452205_0IE0KKGUG', NULL, 0.00, 246.00, 229.00, 'SQUERY_LINK_BASE', 'SYS_2452205_0IE0KKGS6', 'SYS_2452205_0IE0KFWWM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (248.00, '', 2691.00, 'SYS_2452205_0IE0KKGUO', NULL, 0.00, 246.00, 229.00, 'SQUERY_LINK_SOURCE', 'SYS_2452205_0IE0KKGS6', 'SYS_2452205_0IE0KFWWM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (249.00, '', 2695.00, 'SYS_2452205_0IE0KKGVE', NULL, 0.00, 246.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452205_0IE0KKGS6', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (269.00, '', 2693.00, 'SYS_2452207_0IG0GM1P4', NULL, 0.00, 268.00, 97.00, 'SQUERY_LINK_BASE', 'SYS_2452207_0IG0GM1JJ', 'SYS_2452200_0I90GS8J9', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (270.00, '', 2691.00, 'SYS_2452207_0IG0GM1PO', NULL, 0.00, 268.00, 97.00, 'SQUERY_LINK_SOURCE', 'SYS_2452207_0IG0GM1JJ', 'SYS_2452200_0I90GS8J9', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (271.00, '', 2695.00, 'SYS_2452207_0IG0GM1Q5', NULL, 0.00, 268.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452207_0IG0GM1JJ', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (273.00, '', 2693.00, 'SYS_2452207_0IG0HM67B', NULL, 0.00, 272.00, 42.00, 'SQUERY_LINK_BASE', 'SYS_2452207_0IG0HM647', 'SYS_2452194_0I30N3BF2', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (274.00, '', 2691.00, 'SYS_2452207_0IG0HM67N', NULL, 0.00, 272.00, 42.00, 'SQUERY_LINK_SOURCE', 'SYS_2452207_0IG0HM647', 'SYS_2452194_0I30N3BF2', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (275.00, '', 2695.00, 'SYS_2452207_0IG0HM684', NULL, 0.00, 272.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452207_0IG0HM647', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (285.00, '', 2693.00, 'SYS_2452207_0IG0LXRLN', NULL, 0.00, 284.00, 278.00, 'SQUERY_LINK_BASE', 'SYS_2452207_0IG0LXRI8', 'SYS_2452207_0IG0LPXK0', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (286.00, '', 2691.00, 'SYS_2452207_0IG0LXRLY', NULL, 0.00, 284.00, 278.00, 'SQUERY_LINK_SOURCE', 'SYS_2452207_0IG0LXRI8', 'SYS_2452207_0IG0LPXK0', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (287.00, '', 2695.00, 'SYS_2452207_0IG0LXRME', NULL, 0.00, 284.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452207_0IG0LXRI8', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (289.00, '', 2693.00, 'SYS_2452207_0IG0LXUYS', NULL, 0.00, 288.00, 282.00, 'SQUERY_LINK_BASE', 'SYS_2452207_0IG0LXUWD', 'SYS_2452207_0IG0LQP5O', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (290.00, '', 2691.00, 'SYS_2452207_0IG0LXUZ3', NULL, 0.00, 288.00, 282.00, 'SQUERY_LINK_SOURCE', 'SYS_2452207_0IG0LXUWD', 'SYS_2452207_0IG0LQP5O', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (291.00, '', 2695.00, 'SYS_2452207_0IG0LXUZL', NULL, 0.00, 288.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452207_0IG0LXUWD', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (293.00, '', 2693.00, 'SYS_2452207_0IG0LXYZP', NULL, 0.00, 292.00, 279.00, 'SQUERY_LINK_BASE', 'SYS_2452207_0IG0LXYXA', 'SYS_2452207_0IG0LQ1NN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (294.00, '', 2691.00, 'SYS_2452207_0IG0LXZ01', NULL, 0.00, 292.00, 279.00, 'SQUERY_LINK_SOURCE', 'SYS_2452207_0IG0LXYXA', 'SYS_2452207_0IG0LQ1NN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (295.00, '', 2695.00, 'SYS_2452207_0IG0LXZ0J', NULL, 0.00, 292.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452207_0IG0LXYXA', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (297.00, '', 2693.00, 'SYS_2452207_0IG0LY19I', NULL, 0.00, 296.00, 283.00, 'SQUERY_LINK_BASE', 'SYS_2452207_0IG0LY172', 'SYS_2452207_0IG0LQTXE', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (298.00, '', 2691.00, 'SYS_2452207_0IG0LY19U', NULL, 0.00, 296.00, 283.00, 'SQUERY_LINK_SOURCE', 'SYS_2452207_0IG0LY172', 'SYS_2452207_0IG0LQTXE', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (299.00, '', 2695.00, 'SYS_2452207_0IG0LY1AQ', NULL, 0.00, 296.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452207_0IG0LY172', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (301.00, '', 2693.00, 'SYS_2452207_0IG0LY7LO', NULL, 0.00, 300.00, 276.00, 'SQUERY_LINK_BASE', 'SYS_2452207_0IG0LY7I6', 'SYS_2452207_0IG0LPNJ6', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (302.00, '', 2691.00, 'SYS_2452207_0IG0LY7MN', NULL, 0.00, 300.00, 276.00, 'SQUERY_LINK_SOURCE', 'SYS_2452207_0IG0LY7I6', 'SYS_2452207_0IG0LPNJ6', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (303.00, '', 2695.00, 'SYS_2452207_0IG0LY7OO', NULL, 0.00, 300.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452207_0IG0LY7I6', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (305.00, '', 2693.00, 'SYS_2452207_0IG0LY9ID', NULL, 0.00, 304.00, 277.00, 'SQUERY_LINK_BASE', 'SYS_2452207_0IG0LY9FS', 'SYS_2452207_0IG0LPRPO', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (306.00, '', 2691.00, 'SYS_2452207_0IG0LY9IO', NULL, 0.00, 304.00, 277.00, 'SQUERY_LINK_SOURCE', 'SYS_2452207_0IG0LY9FS', 'SYS_2452207_0IG0LPRPO', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (307.00, '', 2695.00, 'SYS_2452207_0IG0LY9J4', NULL, 0.00, 304.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452207_0IG0LY9FS', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (309.00, '', 2693.00, 'SYS_2452207_0IG0LYDJV', NULL, 0.00, 308.00, 280.00, 'SQUERY_LINK_BASE', 'SYS_2452207_0IG0LYDHF', 'SYS_2452207_0IG0LQ50O', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (310.00, '', 2691.00, 'SYS_2452207_0IG0LYDK8', NULL, 0.00, 308.00, 280.00, 'SQUERY_LINK_SOURCE', 'SYS_2452207_0IG0LYDHF', 'SYS_2452207_0IG0LQ50O', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (311.00, '', 2695.00, 'SYS_2452207_0IG0LYDKQ', NULL, 0.00, 308.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452207_0IG0LYDHF', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (313.00, '', 2693.00, 'SYS_2452207_0IG0LYGCU', NULL, 0.00, 312.00, 281.00, 'SQUERY_LINK_BASE', 'SYS_2452207_0IG0LYG8O', 'SYS_2452207_0IG0LQ7XP', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (314.00, '', 2691.00, 'SYS_2452207_0IG0LYGG0', NULL, 0.00, 312.00, 281.00, 'SQUERY_LINK_SOURCE', 'SYS_2452207_0IG0LYG8O', 'SYS_2452207_0IG0LQ7XP', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (315.00, '', 2695.00, 'SYS_2452207_0IG0LYGGN', NULL, 0.00, 312.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452207_0IG0LYG8O', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (326.00, '', 2693.00, 'SYS_2452207_0IG0SJ0VT', NULL, 0.00, 325.00, 324.00, 'SQUERY_LINK_BASE', 'SYS_2452207_0IG0SJ0SM', 'SYS_2452207_0IG0PBD72', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (327.00, '', 2691.00, 'SYS_2452207_0IG0SJ0W5', NULL, 0.00, 325.00, 324.00, 'SQUERY_LINK_SOURCE', 'SYS_2452207_0IG0SJ0SM', 'SYS_2452207_0IG0PBD72', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (328.00, '', 2695.00, 'SYS_2452207_0IG0SJ0WN', NULL, 0.00, 325.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452207_0IG0SJ0SM', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (330.00, '', 2693.00, 'SYS_2452207_0IG0SJ764', NULL, 0.00, 329.00, 35.00, 'SQUERY_LINK_BASE', 'SYS_2452207_0IG0SJ73O', 'SYS_2452193_0I20IQTIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (331.00, '', 2691.00, 'SYS_2452207_0IG0SJ76G', NULL, 0.00, 329.00, 35.00, 'SQUERY_LINK_SOURCE', 'SYS_2452207_0IG0SJ73O', 'SYS_2452193_0I20IQTIF', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (332.00, '', 2695.00, 'SYS_2452207_0IG0SJ76X', NULL, 0.00, 329.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452207_0IG0SJ73O', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (338.00, '', 2693.00, 'SYS_2452207_0IG0TIJWZ', NULL, 0.00, 337.00, 335.00, 'SQUERY_LINK_BASE', 'SYS_2452207_0IG0TIJUB', 'SYS_2452207_0IG0TC1P4', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (339.00, '', 2691.00, 'SYS_2452207_0IG0TIJXD', NULL, 0.00, 337.00, 335.00, 'SQUERY_LINK_SOURCE', 'SYS_2452207_0IG0TIJUB', 'SYS_2452207_0IG0TC1P4', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (340.00, '', 2695.00, 'SYS_2452207_0IG0TIJY2', NULL, 0.00, 337.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452207_0IG0TIJUB', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (342.00, '', 2693.00, 'SYS_2452207_0IG0TIR5P', NULL, 0.00, 341.00, 336.00, 'SQUERY_LINK_BASE', 'SYS_2452207_0IG0TIR37', 'SYS_2452207_0IG0TF7WU', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (343.00, '', 2691.00, 'SYS_2452207_0IG0TIR61', NULL, 0.00, 341.00, 336.00, 'SQUERY_LINK_SOURCE', 'SYS_2452207_0IG0TIR37', 'SYS_2452207_0IG0TF7WU', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (344.00, '', 2695.00, 'SYS_2452207_0IG0TIR6J', NULL, 0.00, 341.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452207_0IG0TIR37', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (427.00, '', 2693.00, 'SYS_2452214_0IN0UBYMS', NULL, 0.00, 426.00, 425.00, 'SQUERY_LINK_BASE', 'SYS_2452214_0IN0UBYHW', 'SYS_2452214_0IN0TRHT2', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (428.00, '', 2691.00, 'SYS_2452214_0IN0UBYNE', NULL, 0.00, 426.00, 425.00, 'SQUERY_LINK_SOURCE', 'SYS_2452214_0IN0UBYHW', 'SYS_2452214_0IN0TRHT2', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (429.00, '', 2695.00, 'SYS_2452214_0IN0UBYNW', NULL, 0.00, 426.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452214_0IN0UBYHW', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (995.00, '', 2693.00, 'SYS_2452244_0JH0JKM75', NULL, 0.00, 994.00, 993.00, 'SQUERY_LINK_BASE', 'SYS_2452244_0JH0JKLCT', 'SYS_2452244_0JH0IPQP7', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (996.00, '', 2691.00, 'SYS_2452244_0JH0JKM7Z', NULL, 0.00, 994.00, 993.00, 'SQUERY_LINK_SOURCE', 'SYS_2452244_0JH0JKLCT', 'SYS_2452244_0JH0IPQP7', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (997.00, '', 2695.00, 'SYS_2452244_0JH0JKM9M', NULL, 0.00, 994.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452244_0JH0JKLCT', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1003.00, '', 2693.00, 'SYS_2452244_0JH0N7F5C', NULL, 0.00, 1002.00, 1000.00, 'SQUERY_LINK_BASE', 'SYS_2452244_0JH0N7EZ8', 'SYS_2452244_0JH0N1C6C', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1004.00, '', 2691.00, 'SYS_2452244_0JH0N7F5M', NULL, 0.00, 1002.00, 1000.00, 'SQUERY_LINK_SOURCE', 'SYS_2452244_0JH0N7EZ8', 'SYS_2452244_0JH0N1C6C', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1005.00, '', 2695.00, 'SYS_2452244_0JH0N7F66', NULL, 0.00, 1002.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452244_0JH0N7EZ8', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1007.00, '', 2693.00, 'SYS_2452244_0JH0N7KV7', NULL, 0.00, 1006.00, 998.00, 'SQUERY_LINK_BASE', 'SYS_2452244_0JH0N7KRV', 'SYS_2452244_0JH0MZ29D', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1008.00, '', 2691.00, 'SYS_2452244_0JH0N7KVH', NULL, 0.00, 1006.00, 998.00, 'SQUERY_LINK_SOURCE', 'SYS_2452244_0JH0N7KRV', 'SYS_2452244_0JH0MZ29D', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1009.00, '', 2695.00, 'SYS_2452244_0JH0N7KW1', NULL, 0.00, 1006.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452244_0JH0N7KRV', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1011.00, '', 2693.00, 'SYS_2452244_0JH0N7P3X', NULL, 0.00, 1010.00, 1001.00, 'SQUERY_LINK_BASE', 'SYS_2452244_0JH0N7P0K', 'SYS_2452244_0JH0N228N', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1012.00, '', 2691.00, 'SYS_2452244_0JH0N7P4R', NULL, 0.00, 1010.00, 1001.00, 'SQUERY_LINK_SOURCE', 'SYS_2452244_0JH0N7P0K', 'SYS_2452244_0JH0N228N', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1013.00, '', 2695.00, 'SYS_2452244_0JH0N7P5B', NULL, 0.00, 1010.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452244_0JH0N7P0K', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1015.00, '', 2693.00, 'SYS_2452244_0JH0N7SF9', NULL, 0.00, 1014.00, 999.00, 'SQUERY_LINK_BASE', 'SYS_2452244_0JH0N7SBX', 'SYS_2452244_0JH0N0ZEI', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1016.00, '', 2691.00, 'SYS_2452244_0JH0N7SFT', NULL, 0.00, 1014.00, 999.00, 'SQUERY_LINK_SOURCE', 'SYS_2452244_0JH0N7SBX', 'SYS_2452244_0JH0N0ZEI', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1017.00, '', 2695.00, 'SYS_2452244_0JH0N7SGN', NULL, 0.00, 1014.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452244_0JH0N7SBX', 'SYS_T2_FORM', 1)

GO

		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1664.00, '', 2693.00, 'SYS_2452385_0NG0Q714D', NULL, 0.00, 1663.00, 1662.00, 'SQUERY_LINK_BASE', 'SYS_2452385_0NG0Q710R', 'SYS_2452385_0NG0Q2XUU', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1665.00, '', 2691.00, 'SYS_2452385_0NG0Q714X', NULL, 0.00, 1663.00, 1662.00, 'SQUERY_LINK_SOURCE', 'SYS_2452385_0NG0Q710R', 'SYS_2452385_0NG0Q2XUU', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (1666.00, '', 2695.00, 'SYS_2452385_0NG0Q715R', NULL, 0.00, 1663.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452385_0NG0Q710R', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5329.00, '', 2693.00, 'SYS_2452669_0VE0JXYLE', NULL, 0.00, 5328.00, 5327.00, 'SQUERY_LINK_BASE', 'SYS_2452669_0VE0JXYFC', 'SYS_2452669_0VE0JUQUQ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5330.00, '', 2691.00, 'SYS_2452669_0VE0JXYN5', NULL, 0.00, 5328.00, 5327.00, 'SQUERY_LINK_SOURCE', 'SYS_2452669_0VE0JXYFC', 'SYS_2452669_0VE0JUQUQ', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5331.00, '', 2695.00, 'SYS_2452669_0VE0JXYOH', NULL, 0.00, 5328.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452669_0VE0JXYFC', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5334.00, '', 2693.00, 'SYS_2452669_0VE0KHHNB', NULL, 0.00, 5333.00, 5332.00, 'SQUERY_LINK_BASE', 'SYS_2452669_0VE0KHHIJ', 'SYS_2452669_0VE0KF500', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5335.00, '', 2691.00, 'SYS_2452669_0VE0KHHOM', NULL, 0.00, 5333.00, 5332.00, 'SQUERY_LINK_SOURCE', 'SYS_2452669_0VE0KHHIJ', 'SYS_2452669_0VE0KF500', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5336.00, '', 2695.00, 'SYS_2452669_0VE0KHHPX', NULL, 0.00, 5333.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452669_0VE0KHHIJ', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5783.00, '', 2693.00, 'SYS_2452716_0WP0SCPZJ', NULL, 0.00, 5782.00, 1156.00, 'SQUERY_LINK_BASE', 'SYS_2452716_0WP0SCPUR', 'SYS_2452278_0KH0LSCUN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5784.00, '', 2691.00, 'SYS_2452716_0WP0SCQ0U', NULL, 0.00, 5782.00, 1156.00, 'SQUERY_LINK_SOURCE', 'SYS_2452716_0WP0SCPUR', 'SYS_2452278_0KH0LSCUN', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5785.00, '', 2695.00, 'SYS_2452716_0WP0SCQ25', NULL, 0.00, 5782.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452716_0WP0SCPUR', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5788.00, '', 2693.00, 'SYS_2452716_0WP0SJKDS', NULL, 0.00, 5787.00, 5786.00, 'SQUERY_LINK_BASE', 'SYS_2452716_0WP0SJK9U', 'SYS_2452716_0WP0SGIRK', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5789.00, '', 2691.00, 'SYS_2452716_0WP0SJKEO', NULL, 0.00, 5787.00, 5786.00, 'SQUERY_LINK_SOURCE', 'SYS_2452716_0WP0SJK9U', 'SYS_2452716_0WP0SGIRK', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5790.00, '', 2695.00, 'SYS_2452716_0WP0SJKGD', NULL, 0.00, 5787.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452716_0WP0SJK9U', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5796.00, '', 2693.00, 'SYS_2452716_0WP0SUO3Y', NULL, 0.00, 5795.00, 3425.00, 'SQUERY_LINK_BASE', 'SYS_2452716_0WP0SUO0H', 'SYS_2452558_0S90YICU0', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5797.00, '', 2691.00, 'SYS_2452716_0WP0SUO4U', NULL, 0.00, 5795.00, 3425.00, 'SQUERY_LINK_SOURCE', 'SYS_2452716_0WP0SUO0H', 'SYS_2452558_0S90YICU0', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5798.00, '', 2695.00, 'SYS_2452716_0WP0SUO66', NULL, 0.00, 5795.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452716_0WP0SUO0H', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5800.00, '', 2693.00, 'SYS_2452716_0WP0SURDL', NULL, 0.00, 5799.00, 3430.00, 'SQUERY_LINK_BASE', 'SYS_2452716_0WP0SURA4', 'SYS_2452558_0S90YJ1FR', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5801.00, '', 2691.00, 'SYS_2452716_0WP0SUREV', NULL, 0.00, 5799.00, 3430.00, 'SQUERY_LINK_SOURCE', 'SYS_2452716_0WP0SURA4', 'SYS_2452558_0S90YJ1FR', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (5802.00, '', 2695.00, 'SYS_2452716_0WP0SURG6', NULL, 0.00, 5799.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452716_0WP0SURA4', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6121.00, '', 2693.00, 'SYS_2452819_0ZK0SLDG0', NULL, 0.00, 6120.00, 6119.00, 'SQUERY_LINK_BASE', 'SYS_2452819_0ZK0SLDB9', 'SYS_2452819_0ZK0S2CQP', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6122.00, '', 2691.00, 'SYS_2452819_0ZK0SLDGX', NULL, 0.00, 6120.00, 6119.00, 'SQUERY_LINK_SOURCE', 'SYS_2452819_0ZK0SLDB9', 'SYS_2452819_0ZK0S2CQP', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6123.00, '', 2695.00, 'SYS_2452819_0ZK0SLDHT', NULL, 0.00, 6120.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452819_0ZK0SLDB9', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6898.00, '', 2693.00, 'SYS_2452878_1170VWIK0', NULL, 0.00, 6897.00, 6895.00, 'SQUERY_LINK_BASE', 'SYS_2452878_1170VWIDI', 'SYS_2452878_1170VRMK3', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6899.00, '', 2691.00, 'SYS_2452878_1170VWILR', NULL, 0.00, 6897.00, 6895.00, 'SQUERY_LINK_SOURCE', 'SYS_2452878_1170VWIDI', 'SYS_2452878_1170VRMK3', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6900.00, '', 2695.00, 'SYS_2452878_1170VWIN4', NULL, 0.00, 6897.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452878_1170VWIDI', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6902.00, '', 2693.00, 'SYS_2452878_1170VWKMQ', NULL, 0.00, 6901.00, 6896.00, 'SQUERY_LINK_BASE', 'SYS_2452878_1170VWKIB', 'SYS_2452878_1170VRRVI', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6903.00, '', 2691.00, 'SYS_2452878_1170VWKNZ', NULL, 0.00, 6901.00, 6896.00, 'SQUERY_LINK_SOURCE', 'SYS_2452878_1170VWKIB', 'SYS_2452878_1170VRRVI', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (6904.00, '', 2695.00, 'SYS_2452878_1170VWKOW', NULL, 0.00, 6901.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_2452878_1170VWKIB', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (9247.00, '', 2693.00, 'SYS_7A2D2F8D-2A64-4575-A3B0-D9679E89F0D6', NULL, 0.00, 9246.00, 9245.00, 'SQUERY_LINK_BASE', 'SYS_9D83AA4F-B9BE-4265-A427-29615EA664D5', 'SYS_F190D880-FE76-4E3A-87A0-E953F4B64336', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (9248.00, '', 2691.00, 'SYS_4187A9EB-46A2-4341-A073-82CA3F5D92EF', NULL, 0.00, 9246.00, 9245.00, 'SQUERY_LINK_SOURCE', 'SYS_9D83AA4F-B9BE-4265-A427-29615EA664D5', 'SYS_F190D880-FE76-4E3A-87A0-E953F4B64336', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (9249.00, '', 2695.00, 'SYS_5BC3E815-E9BB-4C38-A8D3-836AE4C69D91', NULL, 0.00, 9246.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_9D83AA4F-B9BE-4265-A427-29615EA664D5', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (9745.00, '', 2693.00, 'SYS_85510AD7-8EE4-4E79-ADA4-DF4ADC115D06', NULL, 0.00, 9744.00, 9743.00, 'SQUERY_LINK_BASE', 'SYS_B15C585A-AD14-438C-A792-6343ECDC0F27', 'SYS_44C6AAAA-E155-48CE-81F7-4B1897B0A0A4', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (9746.00, '', 2691.00, 'SYS_DD3F6E18-1BA4-4381-AAF2-4AB99EC3A967', NULL, 0.00, 9744.00, 9743.00, 'SQUERY_LINK_SOURCE', 'SYS_B15C585A-AD14-438C-A792-6343ECDC0F27', 'SYS_44C6AAAA-E155-48CE-81F7-4B1897B0A0A4', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (9747.00, '', 2695.00, 'SYS_B7FC6259-F9D7-47AC-8957-6AA5FD3B63C6', NULL, 0.00, 9744.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_B15C585A-AD14-438C-A792-6343ECDC0F27', 'SYS_T2_FORM', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (10469.00, '', 2693.00, 'SYS_1D3BE26C-A60C-4D9C-BE39-3AB22387D49C', NULL, 0.00, 10468.00, 10467.00, 'SQUERY_LINK_BASE', 'SYS_E4A34200-71DF-423A-9A3E-0199823056C3', 'SYS_F0E4F3CC-D9F7-4B34-954F-2E6778B1CE46', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (10470.00, '', 2691.00, 'SYS_B1FA5E95-4FAA-4F4F-AD58-1CD8AC10659C', NULL, 0.00, 10468.00, 10467.00, 'SQUERY_LINK_SOURCE', 'SYS_E4A34200-71DF-423A-9A3E-0199823056C3', 'SYS_F0E4F3CC-D9F7-4B34-954F-2E6778B1CE46', 1)
		INSERT INTO #T_OV(LINK,  NAME,  OBJECT,  CODE,  USERS,  ORDERS,  LINK_SELF,  LINK_STATE,  CODE_OBJ,  CODE_SELF,  CODE_STATE,  SYS) VALUES (10471.00, '', 2695.00, 'SYS_44A106B9-1E9F-4707-99E5-38D89E56C1E1', NULL, 0.00, 10468.00, 61.00, 'SQUERY_LINK_SQUERY', 'SYS_E4A34200-71DF-423A-9A3E-0199823056C3', 'SYS_T2_FORM', 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 (61.00, 137.00, NULL, NULL, '', 'SYS_T2_FORM', 'SQUERY_CHANGED')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 157.00, NULL, NULL, '', 'SYS_T2_FORM', 'SQUERY_FOOTER')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 159.00, NULL, NULL, 'KIRREPMAKER.XLS', 'SYS_T2_FORM', 'SQUERY_GENERATOR')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 160.00, NULL, NULL, '', 'SYS_T2_FORM', 'SQUERY_HEADER')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 173.00, NULL, NULL, '', 'SYS_T2_FORM', 'SQUERY_PATH')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 174.00, NULL, NULL, 'IIF((@nOption_3=1) and (@nOption_4=1) and mk_t2_hist_data(),"FORM-T2.XLT",IIF((@nOption_3=1) and (@nOption_4=2) and mk_t2_hist_data(),"FORM-T2_GS.XLT",IIF((@nOption_3=2) AND (@nOption_4=1) AND mk_t2_hist_data(),"FORM-T2_BOOK.XLT",IIF((@nOption_3=2) AND (@nOption_4=2) AND mk_t2_hist_data(),"FORM-T2GS_BOOK.XLT",""))))', 'SYS_T2_FORM', 'SQUERY_REPORT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 175.00, NULL, NULL, '(1>0)

EXEC MK_MAKE_T2_DATA @nNumber001

EXEC KIR_GET_OTV_FACES', 'SYS_T2_FORM', 'SQUERY_RES_WHERE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 27.00, '
	UPDATE #T_RES
	SET	OBR_END1 = (SELECT ENDYEAR FROM #OBR_LK WHERE REAL_NUM=1) /*Год окончания - 1*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 16.00, '
	UPDATE #T_RES
	SET	KONTR_NUM = (select top 1 kontr_num
from item_move im inner join empl em on im.empl_link=em.link 
where (@dDate001 between date_begin 
	and date_end 
	and em.link = @FACE_LK and active =1 
	and kontr_date is not null)
order by im.kontr_date) /*Трудовой договор - номер*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 11.00, '
	UPDATE #T_RES
	SET	SH_YEAR = (SELECT convert(varchar(4),year(PE.DATE_END)) FROM PERS_EDUCATION PE INNER JOIN EDUCTYPE ED ON PE.EDUC_LINK=ED.LINK
WHERE PE.PERS_LINK = (SELECT PERS_LINK FROM EMPL WHERE LINK=@FACE_LK)  AND ED.CODE=''19'') /*Послевуз. обр. - год оконч*/ FROM #T_RES T  WHERE SQUERY=45311
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 12.00, '
	UPDATE #T_RES
	SET	S_2511 = (SELECT FULL_NAME FROM DICTIONARY_DEPARTMENT WHERE LINK=S_26265) /*Наименование*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 13.00, '
	UPDATE #T_RES
	SET	OKPO = (SELECT OKPO FROM DICTIONARY_DEPARTMENT WHERE LINK=S_26265) /*ОКПО*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 14.00, '
	UPDATE #T_RES
	SET	DATE_REG = ISNULL((SELECT REGDATE_OFIC FROM PERSON WHERE LINK=S_2158),'''') /*Дата регистрации*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 15.00, '
	UPDATE #T_RES
	SET	KONTR_DATE = (select top 1 kontr_date
from item_move im inner join empl em on im.empl_link=em.link 
where (@dDate001 between date_begin 
	and date_end 
	and em.link = @FACE_LK and active =1 
	and kontr_date is not null)
order by im.kontr_date) /*Трудовой договор - дата*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 69.00, '
	UPDATE #T_RES
	SET	S_2600 = (SELECT NAME FROM #DOP WHERE NUM=2) /*Доп - 2*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 70.00, '
	UPDATE #T_RES
	SET	S_2604 = (SELECT NAME FROM #DOP WHERE NUM=3) /*Доп - 3*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 71.00, '
	UPDATE #T_RES
	SET	S_2608 = (SELECT NAME FROM #DOP WHERE NUM=4) /*Доп - 4*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 72.00, '
	UPDATE #T_RES
	SET	S_5984 = ISNULL((SELECT DOC_WHOM FROM PERSON WHERE LINK=S_2158), '''') /*Документ - кем выдан*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 52.00, '
	UPDATE #T_RES
	SET	S_2368 = ISNULL((SELECT CONVERT(VARCHAR(10),DOC_DATE,104) FROM PERSON WHERE LINK=S_2158), '''') /*Документ - дата*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 53.00, '
	UPDATE #T_RES
	SET	S_2380 = ISNULL((SELECT DOC_NUM FROM PERSON P WHERE P.LINK=S_2158), '''') /*Документ - номер*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 82.00, '
	SELECT S_2158 AS S_2158 /*Лицо*/,
		S_2162 AS S_2162 /*Фамилия*/,
		S_2166 AS S_2166 /*Имя*/,
		S_2170 AS S_2170 /*Отчество*/,
		S_2178 AS S_2178 /*Дата рождения*/,
		S_2182 AS S_2182 /*Табельный номер*/,
		S_2191 AS S_2191 /*Пол*/,
		S_2214 AS S_2214 /*Дата составления*/,
		S_2220 AS S_2220 /*Гражданство*/,
		S_2237 AS S_2237 /*Место рождения*/,
		S_2352 AS S_2352 /*Профессия*/,
		S_2360 AS S_2360 /*Семейное положение*/,
		S_2364 AS S_2364 /*Документ - вид*/,
		S_2368 AS S_2368 /*Документ - дата*/,
		S_2380 AS S_2380 /*Документ - номер*/,
		S_2387 AS S_2387 /*ВУС*/,
		S_2391 AS S_2391 /*Звание*/,
		S_2395 AS S_2395 /*Годность к военной службе*/,
		S_2399 AS S_2399 /*РВК*/,
		S_2403 AS S_2403 /*Специальный учет*/,
		S_2407 AS S_2407 /*Звание - код*/,
		S_2428 AS S_2428 /*Стаж а-1*/,
		EXP_NEPR AS EXP_NEPR /*Стаж непрерывный*/,
		EXP_GEN AS EXP_GEN /*Стаж общий*/,
		S_2472 AS S_2472 /*Стаж г-1*/,
		S_2515 AS S_2515 /*Семейное положение - код*/,
		S_2523 AS S_2523 /*Адрес по паспорту*/,
		S_2527 AS S_2527 /*Адрес фактический*/,
		S_2532 AS S_2532 /*Домашний телефон*/,
		S_2596 AS S_2596 /*Доп - 1*/,
		S_2600 AS S_2600 /*Доп - 2*/,
		S_2604 AS S_2604 /*Доп - 3*/,
		S_2608 AS S_2608 /*Доп - 4*/,
		S_2612 AS S_2612 /*Доп - 5*/,
		S_2224 AS S_2224 /*Гражданство (код)*/,
		S_2881 AS S_2881 /*Образование*/,
		DIPLOM1 AS DIPLOM1 /*Диплом - 1*/,
		DIPLOM2 AS DIPLOM2 /*Диплом - 2*/,
		OBR_END1 AS OBR_END1 /*Год окончания - 1*/,
		OBR_END2 AS OBR_END2 /*Год окончания - 2*/,
		OBR1_1 AS OBR1_1 /*Учебное заведение 1 - 1*/,
		OBR1_2 AS OBR1_2 /*Учебное заведение 1 - 2*/,
		OBR2_1 AS OBR2_1 /*Учебное заведение 2 - 1*/,
		OBR2_2 AS OBR2_2 /*Учебное заведение 2 - 2*/,
		S_2960 AS S_2960 /*Категория запаса*/,
		S_2964 AS S_2964 /*Состав воинского учета*/,
		S_2978 AS S_2978 /*ИНН*/,
		S_2982 AS S_2982 /*Номер СПУ*/,
		S_2972 AS S_2972 /*Дата увольнения*/,
		SPEC1 AS SPEC1 /*Специальность 1*/,
		SPEC2 AS SPEC2 /*Специальность 2*/,
		OKSO1 AS OKSO1 /*ОКСО - 1*/,
		OKSO2 AS OKSO2 /*ОКСО - 2*/,
		S_5984 AS S_5984 /*Документ - кем выдан*/,
		S_5992 AS S_5992 /*Язык 1 -степень знания*/,
		S_5996 AS S_5996 /*Язык 1*/,
		S_6000 AS S_6000 /*Язык 2 - степень знания*/,
		S_6004 AS S_6004 /*Язык 2*/,
		dis_ord AS dis_ord /*Приказ об увольнении*/,
		S_24409 AS S_24409 /*Специальный учет - документ*/,
		S_24414 AS S_24414 /*Отметка о снятии с воинского учета*/,
		uch_st AS uch_st /*Ученая степень*/,
		UCH_S_C AS UCH_S_C /*Ученая степень - код*/,
		S_26265 AS S_26265 /*Организация - ключ*/,
		S_2511 AS S_2511 /*Наименование*/,
		OKPO AS OKPO /*ОКПО*/,
		KVAL1 AS KVAL1 /*Квалификация 1*/,
		KVAL2 AS KVAL2 /*Квалификация 2*/,
		DATE_REG AS DATE_REG /*Дата регистрации*/,
		KONTR_DATE AS KONTR_DATE /*Трудовой договор - дата*/,
		KONTR_NUM AS KONTR_NUM /*Трудовой договор - номер*/,
		SH_TYPE AS SH_TYPE /*Послевуз. обр. - тип*/,
		SH_DOC AS SH_DOC /*Послевуз. обр. - № док.*/,
		SH_DEP AS SH_DEP /*Послевуз. обр. - наим. уч. зав*/,
		SH_SPEC AS SH_SPEC /*Послевуз. обр. - специальность*/,
		sh_spec2 AS sh_spec2 /*Послевуз. обр. - спец2*/,
		SH_DATE AS SH_DATE /*Послевуз. обр. - дата док.*/,
		SH_YEAR AS SH_YEAR /*Послевуз. обр. - год оконч*/,
		DATE_BEGIN AS DATE_BEGIN /*Дата приема*/,
		DIS_REASON AS DIS_REASON /*Основание увольнения*/,
		EXP_VYS AS EXP_VYS /*Стаж выслуги*/,
		DIS_OD AS DIS_OD /*Приказ об увольнении - дата*/,
		OBR_DOC2 AS OBR_DOC2 /*Тип док. об образ. 2*/,
		CHARACT2 AS CHARACT2 /*Характер работы*/,
		STAT AS STAT /*Статус*/,
		OBR_DOC1 AS OBR_DOC1 /*Тип док. об образ. 1*/
	INTO #T_RES2
	FROM #T_RES T
	GROUP BY S_2158, S_2162, S_2166, S_2170, S_2178, S_2182, S_2191, S_2214, S_2220, S_2237, S_2352, S_2360, S_2364, S_2368, S_2380, S_2387, S_2391, S_2395, S_2399, S_2403, S_2407, S_2428, EXP_NEPR, EXP_GEN, S_2472, S_2515, S_2523, S_2527, S_2532, S_2596, S_2600, S_2604, S_2608, S_2612, S_2224, S_2881, DIPLOM1, DIPLOM2, OBR_END1, OBR_END2, OBR1_1, OBR1_2, OBR2_1, OBR2_2, S_2960, S_2964, S_2978, S_2982, S_2972, SPEC1, SPEC2, OKSO1, OKSO2, S_5984, S_5992, S_5996, S_6000, S_6004, dis_ord, S_24409, S_24414, uch_st, UCH_S_C, S_26265, S_2511, OKPO, KVAL1, KVAL2, DATE_REG, KONTR_DATE, KONTR_NUM, SH_TYPE, SH_DOC, SH_DEP, SH_SPEC, sh_spec2, SH_DATE, SH_YEAR, DATE_BEGIN, DIS_REASON, EXP_VYS, DIS_OD, OBR_DOC2, CHARACT2, STAT, OBR_DOC1


', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 4.00, '
	INSERT #T_RES (S_2158, SPEC1, SPEC2, OKSO1, OKSO2, S_26265, KVAL1, KVAL2, DATE_BEGIN, SQUERY) /*Дата приема*/
	SELECT FM2.LINK, (SELECT SPEC FROM #OBR_LK WHERE REAL_NUM=1), (SELECT SPEC FROM #OBR_LK WHERE REAL_NUM=2), (SELECT OKSO FROM #OBR_LK WHERE REAL_NUM=1), (SELECT OKSO FROM #OBR_LK WHERE REAL_NUM=2), DEP.LINK, (SELECT KVALIF1 FROM #OBR_LK WHERE REAL_NUM=1), (SELECT KVALIF1 FROM #OBR_LK WHERE REAL_NUM=2), dbo.kd_DateBeginWork(@FACE_LK, @dDate001), 45311
	FROM PERSON FM2, #TMP_LK, DICTIONARY_DEPARTMENT DEP
	WHERE DEP.LINK=isnull(dbo.BK_getDepZB(), dbo.getowndeplink())
		AND FM2.LINK=(select pers_link from empl where link = @nNumber001)
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 9.00, '
	UPDATE #T_RES
	SET	sh_spec2 = (SELECT substring(SP.NAME,41,254) FROM PERS_EDUCATION PE INNER JOIN SPECIALITY SP ON PE.SPEC_LINK=SP.LINK INNER JOIN EDUCTYPE ED ON PE.EDUC_LINK=ED.LINK 
WHERE PE.PERS_LINK = (SELECT PERS_LINK FROM EMPL WHERE LINK=@FACE_LK)  AND ED.CODE=''19'') /*Послевуз. обр. - спец2*/ FROM #T_RES T  WHERE SQUERY=45311
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 57.00, '
	UPDATE #T_RES
	SET	S_2399 = ISNULL((SELECT NAME FROM PERSON P INNER JOIN VOINVK VK ON P.VOINVK_LINK = VK.LINK WHERE P.LINK=S_2158), '''') /*РВК*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 58.00, '
	UPDATE #T_RES
	SET	S_2403 = ( SELECT CASE 
	WHEN ISNULL(VOINBRON,0) = 1 THEN ''Удостоверение бронирования''
	WHEN ISNULL(VOINMOB,0) = 1 THEN ''Мобилизационное предписание''
	else ''''
end 
from PERSON
where link = S_2158
)

 /*Специальный учет*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 76.00, '
	UPDATE #T_RES
	SET	S_6004 = (SELECT NAME1 FROM #LANG_LK WHERE REAL_NUM=2) /*Язык 2*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 77.00, '
	UPDATE #T_RES
	SET	dis_ord = (
SELECT	top 1 IDF.number
FROM	DIS_FACE IDF
WHERE idf.active = 1
                and idf.DIS_DATE <= @dDate001
                and idf.empl_link  =	@FACE_LK
) /*Приказ об увольнении*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 78.00, '
	UPDATE #T_RES
	SET	S_24409 = ( SELECT CASE 
	WHEN ISNULL(VOINBRON,0) = 1 THEN VOINBRONNUM
	WHEN ISNULL(VOINMOB,0) = 1 THEN ''''
	else ''''
end 
from PERSON
where link = S_2158
)
 /*Специальный учет - документ*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 79.00, '
	UPDATE #T_RES
	SET	S_24414 = (SELECT VOINSPUCHET FROM PERSON WHERE LINK=S_2158) /*Отметка о снятии с воинского учета*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 34.00, '
	UPDATE #T_RES
	SET	S_2964 = ISNULL((SELECT VS.NAME FROM PERSON P INNER JOIN VOINSOST VS ON P.VOINSOST_LINK=VS.LINK WHERE P.LINK=S_2158), '''') /*Состав воинского учета*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 35.00, '
	UPDATE #T_RES
	SET	S_2978 = ISNULL( (select ''#''+INN  FROM PERSON WHERE LINK=S_2158 ), ''#''+SPACE(12) ) /*ИНН*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 36.00, '
	UPDATE #T_RES
	SET	S_2982 = ISNULL((SELECT INSUR_NUM FROM PERSON WHERE LINK=S_2158), SPACE(14)) /*Номер СПУ*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 37.00, '
	UPDATE #T_RES
	SET	S_2972 = (
SELECT IDF.DIS_DATE
FROM	DIS_FACE IDF
WHERE idf.active = 1
                and idf.DIS_DATE <= @dDate001
                and idf.empl_link  =	@FACE_LK
) /*Дата увольнения*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 38.00, '
	UPDATE #T_RES
	SET	DIS_REASON = (
SELECT IDF.reason_name
FROM	DIS_FACE IDF
WHERE idf.active = 1
                and idf.DIS_DATE <= @dDate001
                and idf.empl_link  =	@FACE_LK
) /*Основание увольнения*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 73.00, '
	UPDATE #T_RES
	SET	S_5992 = (SELECT SKILL FROM #LANG_LK WHERE REAL_NUM=1) /*Язык 1 -степень знания*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 28.00, '
	UPDATE #T_RES
	SET	OBR_END2 = (SELECT ENDYEAR FROM #OBR_LK WHERE REAL_NUM=2) /*Год окончания - 2*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 29.00, '
	UPDATE #T_RES
	SET	OBR1_1 = (SELECT NAME1 FROM #OBR_LK WHERE REAL_NUM=1) /*Учебное заведение 1 - 1*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 30.00, '
	UPDATE #T_RES
	SET	OBR1_2 = (SELECT NAME2 FROM #OBR_LK WHERE REAL_NUM=1) /*Учебное заведение 1 - 2*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 31.00, '
	UPDATE #T_RES
	SET	OBR2_1 = (SELECT NAME1 FROM #OBR_LK WHERE REAL_NUM=2) /*Учебное заведение 2 - 1*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 10.00, '
	UPDATE #T_RES
	SET	SH_DATE = (SELECT PE.DOC_DATE FROM PERS_EDUCATION PE INNER JOIN EDUCTYPE ED ON PE.EDUC_LINK=ED.LINK WHERE PE.PERS_LINK = (SELECT PERS_LINK FROM EMPL WHERE LINK=@FACE_LK)  AND ED.CODE=''19'') /*Послевуз. обр. - дата док.*/ FROM #T_RES T  WHERE SQUERY=45311
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 2.00, '
	/*СОЗДАЕМ ТРЕБУЕМЫЕ ТАБЛИЦЫ*/
CREATE TABLE #TMP_LK 
(FIELD1 INT)
INSERT INTO #TMP_LK (FIELD1) VALUES (1)

/*ПЕРВИЧНЫЙ КЛЮЧ ЛИЦА */
DECLARE @FACE_LK INT
SET @FACE_LK=@nNumber001

/*СТРОКИ АДРЕСА*/
CREATE TABLE #ADDR (FACT INT 		/* 0 - ПО ПРОПИСКЕ, 1 - ФАКТИЧЕСКИЙ*/,
	ADDR_STR VARCHAR(200) 	/*СТРОКА АДРЕСА*/ )
EXEC K_FILL_TLK_ADDR @FACE_LK

/*Образование - раздел 6 личной карточки*/
CREATE TABLE #OBR_LK
(
	NAME1 VARCHAR(50),  /*название учебного заведения - строка 1 */
	NAME2 VARCHAR(254),  /*название учебного заведения - строка 2 */
	NAME VARCHAR(254),  /*название учебного заведения */
	DIPLOM VARCHAR(40), /*серия и номер диплома*/
	ENDYEAR CHAR(4),    /*год окончания*/
	KVALIF1 VARCHAR(50),    /*квалификация по диплому  - строка 1 */
	KVALIF2 VARCHAR(50),    /*квалификация по диплому  - строка 1 */
	SPEC  VARCHAR(254),      /*специальность по диплому  */
	OKSO  VARCHAR(10),       /*специальность по диплому  - код ОКСО */
	NUM_O INT, REAL_NUM INT,
OBR_DOC VARCHAR(50)  /*тип  документа об образовании*/
)
EXEC K_FILL_TLK_OBR_LK @FACE_LK

/*Стажи*/
SELECT ee.years,ee.months,ee.days,e.code
INTO #EXPIR
FROM empl el LEFT JOIN 
empl_expir ee ON el.link=ee.empl_link INNER JOIN
expir e ON ee.expir_link=e.link
WHERE el.link =  @FACE_LK

/*Дополнительные сведения*/
CREATE TABLE #DOP (NAME VARCHAR(100), NUM INT)
EXEC K_FILL_TLK_DOP @FACE_LK

/*члены семьи*/
/*
CREATE TABLE #REL (ROD CHAR(35), FM VARCHAR(100),IM VARCHAR(100), OT VARCHAR(100), 
BIRTH CHAR(4), 	BIRTH_DATE CHAR(10), 
NUM_REL INT, REAL_NUM INT, RESULT VARCHAR(120) )
EXEC K_FILL_TLK_REL @FACE_LK
*/
/*Владение языками*/
CREATE TABLE #LANG_LK
(
	NAME1 VARCHAR(120),  	SKILL VARCHAR(50),
	NUM_LANG INT, 	REAL_NUM INT
)
EXEC K_FILL_TLK_LANG @FACE_LK




', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 54.00, '
	UPDATE #T_RES
	SET	S_2387 = ISNULL((SELECT top 1 VOINVUS FROM PERSON WHERE LINK=S_2158),'''') /*ВУС*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 55.00, '
	UPDATE #T_RES
	SET	S_2391 = ISNULL((SELECT VZ.NAME FROM PERSON P INNER JOIN VOINZV VZ ON P.VOINZV_LINK=VZ.LINK WHERE P.LINK=S_2158), '''') /*Звание*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 56.00, '
	UPDATE #T_RES
	SET	S_2395 = ISNULL((SELECT VG.NAME FROM PERSON P INNER JOIN VOINGODN VG ON P.VOINGODN_LINK=VG.LINK WHERE P.LINK=S_2158), '''') /*Годность к военной службе*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 80.00, '
	UPDATE #T_RES
	SET	uch_st = ISNULL((SELECT AD.NAME FROM PERSON P INNER JOIN ACAD_DEGREE AD ON P.ACAD_DEGREE_LINK=AD.LINK WHERE P.LINK=S_2158),'''') /*Ученая степень*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 81.00, '
	UPDATE #T_RES
	SET	UCH_S_C = ISNULL((SELECT ACAD_DEGREE_LINK FROM PERSON WHERE LINK=S_2158),'''') /*Ученая степень - код*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 83.00, '	
SELECT * FROM #T_RES2 
	WHERE (1>0)

EXEC MK_MAKE_T2_DATA @nNumber001

EXEC KIR_GET_OTV_FACES

', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 84.00, '
	DROP TABLE #T_RES
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 85.00, '
	DROP TABLE #TMP_LK

	SET TRANSACTION ISOLATION LEVEL READ COMMITTED

END', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 1.00, 'CREATE PROCEDURE #P_SQUERY
		@dDate001 DATETIME /*Дата формирования*/,
		@nCheck_5 INT /*Показать оклад*/,
		@nNumber001 INT /*Ссылка на лицо*/,
		@nOption_3 INT /*Размер листа*/,
		@nOption_4 INT /*Форма личной карточки*/,
		@varKScTableInto varchar(20) = ''''
AS
BEGIN

	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 17.00, '
	UPDATE #T_RES
	SET	DIS_OD = (
SELECT	top 1 IDF.date
FROM	DIS_FACE IDF
WHERE idf.active = 1
                and idf.DIS_DATE <= @dDate001
                and idf.empl_link  =	@FACE_LK
) /*Приказ об увольнении - дата*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 18.00, '
	UPDATE #T_RES
	SET	OBR_DOC2 = (SELECT OBR_DOC FROM #OBR_LK WHERE REAL_NUM=2) /*Тип док. об образ. 2*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 19.00, '
	UPDATE #T_RES
	SET	CHARACT2 = (select top 1 case when date_end2 is null then ''Постоянный'' else ''Временный'' end
from item_move im inner join empl em on im.empl_link=em.link 
where @dDate001 between date_begin 
	and date_end 
	and em.link = @FACE_LK and active =1) /*Характер работы*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 3.00, '
	CREATE TABLE #T_RES (CHARACT2 varchar(20) /*Характер работы*/,
		DATE_BEGIN DATETIME /*Дата приема*/,
		DATE_REG VARCHAR(254) /*Дата регистрации*/,
		DIPLOM1 VARCHAR(40) /*Диплом - 1*/,
		DIPLOM2 VARCHAR(40) /*Диплом - 2*/,
		DIS_OD DATETIME /*Приказ об увольнении - дата*/,
		dis_ord VARCHAR(254) /*Приказ об увольнении*/,
		DIS_REASON VARCHAR(254) /*Основание увольнения*/,
		EXP_GEN char(8) /*Стаж общий*/,
		EXP_NEPR char(8) /*Стаж непрерывный*/,
		EXP_VYS CHAR(8) /*Стаж выслуги*/,
		KONTR_DATE VARCHAR(11) /*Трудовой договор - дата*/,
		KONTR_NUM VARCHAR(30) /*Трудовой договор - номер*/,
		KVAL1 VARCHAR(120) /*Квалификация 1*/,
		KVAL2 VARCHAR(120) /*Квалификация 2*/,
		OBR_DOC1 VARCHAR(50) /*Тип док. об образ. 1*/,
		OBR_DOC2 VARCHAR(50) /*Тип док. об образ. 2*/,
		OBR_END1 CHAR(4) /*Год окончания - 1*/,
		OBR_END2 CHAR(4) /*Год окончания - 2*/,
		OBR1_1 VARCHAR(50) /*Учебное заведение 1 - 1*/,
		OBR1_2 VARCHAR(254) /*Учебное заведение 1 - 2*/,
		OBR2_1 VARCHAR(50) /*Учебное заведение 2 - 1*/,
		OBR2_2 VARCHAR(254) /*Учебное заведение 2 - 2*/,
		OKPO VARCHAR(20) /*ОКПО*/,
		OKSO1 VARCHAR(10) /*ОКСО - 1*/,
		OKSO2 VARCHAR(10) /*ОКСО - 2*/,
		S_2158 INT /*Лицо*/,
		S_2162 varchar(50) /*Фамилия*/,
		S_2166 VARCHAR(25) /*Имя*/,
		S_2170 VARCHAR(25) /*Отчество*/,
		S_2178 VARCHAR(10) /*Дата рождения*/,
		S_2182 VARCHAR(10) /*Табельный номер*/,
		S_2191 CHAR(7) /*Пол*/,
		S_2214 datetime /*Дата составления*/,
		S_2220 VARCHAR(65) /*Гражданство*/,
		S_2224 varchar(4) /*Гражданство (код)*/,
		S_2237 varchar(80) /*Место рождения*/,
		S_2352 VARCHAR(254) /*Профессия*/,
		S_2360 VARCHAR(60) /*Семейное положение*/,
		S_2364 VARCHAR(50) /*Документ - вид*/,
		S_2368 VARCHAR(10) /*Документ - дата*/,
		S_2380 VARCHAR(20) /*Документ - номер*/,
		S_2387 CHAR(40) /*ВУС*/,
		S_2391 VARCHAR(45) /*Звание*/,
		S_2395 varchar(60) /*Годность к военной службе*/,
		S_2399 VARCHAR(150) /*РВК*/,
		S_2403 VARCHAR(40) /*Специальный учет*/,
		S_2407 VARCHAR(4) /*Звание - код*/,
		S_2428 CHAR(8) /*Стаж а-1*/,
		S_24409 VARCHAR(30) /*Специальный учет - документ*/,
		S_24414 varchar(30) /*Отметка о снятии с воинского учета*/,
		S_2472 CHAR(8) /*Стаж г-1*/,
		S_2511 VARCHAR(254) /*Наименование*/,
		S_2515 VARCHAR(2) /*Семейное положение - код*/,
		S_2523 VARCHAR(200) /*Адрес по паспорту*/,
		S_2527 varchar(200) /*Адрес фактический*/,
		S_2532 VARCHAR(60) /*Домашний телефон*/,
		S_2596 VARCHAR(100) /*Доп - 1*/,
		S_2600 VARCHAR(100) /*Доп - 2*/,
		S_2604 VARCHAR(100) /*Доп - 3*/,
		S_2608 VARCHAR(100) /*Доп - 4*/,
		S_2612 VARCHAR(100) /*Доп - 5*/,
		S_26265 INT /*Организация - ключ*/,
		S_2881 VARCHAR(60) /*Образование*/,
		S_2960 VARCHAR(20) /*Категория запаса*/,
		S_2964 VARCHAR(25) /*Состав воинского учета*/,
		S_2972 DATETIME /*Дата увольнения*/,
		S_2978 char(13) /*ИНН*/,
		S_2982 varchar(14) /*Номер СПУ*/,
		S_5984 VARCHAR(120) /*Документ - кем выдан*/,
		S_5992 VARCHAR(50) /*Язык 1 -степень знания*/,
		S_5996 VARCHAR(254) /*Язык 1*/,
		S_6000 VARCHAR(50) /*Язык 2 - степень знания*/,
		S_6004 VARCHAR(254) /*Язык 2*/,
		SH_DATE DATETIME /*Послевуз. обр. - дата док.*/,
		SH_DEP VARCHAR(254) /*Послевуз. обр. - наим. уч. зав*/,
		SH_DOC VARCHAR(20) /*Послевуз. обр. - № док.*/,
		SH_SPEC VARCHAR(40) /*Послевуз. обр. - специальность*/,
		sh_spec2 VARCHAR(254) /*Послевуз. обр. - спец2*/,
		SH_TYPE VARCHAR(20) /*Послевуз. обр. - тип*/,
		SH_YEAR VARCHAR(4) /*Послевуз. обр. - год оконч*/,
		SPEC1 VARCHAR(254) /*Специальность 1*/,
		SPEC2 VARCHAR(254) /*Специальность 2*/,
		STAT VARCHAR(40) /*Статус*/,
		UCH_S_C CHAR(2) /*Ученая степень - код*/,
		uch_st varchar(120) /*Ученая степень*/, SQUERY int)
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 5.00, '
	UPDATE #T_RES
	SET	SH_TYPE = (SELECT  '' '' as blank FROM PERSON WHERE LINK=(SELECT PERS_LINK FROM EMPL WHERE LINK=@FACE_LK) ) /*Послевуз. обр. - тип*/ FROM #T_RES T  WHERE SQUERY=45311
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 6.00, '
	UPDATE #T_RES
	SET	SH_DOC = (SELECT PE.DOC_NUM FROM PERS_EDUCATION PE INNER JOIN EDUCTYPE ED ON PE.EDUC_LINK=ED.LINK
WHERE PE.PERS_LINK = (SELECT PERS_LINK FROM EMPL WHERE LINK=@FACE_LK)  AND ED.CODE=''19'') /*Послевуз. обр. - № док.*/ FROM #T_RES T  WHERE SQUERY=45311
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 7.00, '
	UPDATE #T_RES
	SET	SH_DEP = (SELECT SC.NAME FROM PERS_EDUCATION PE INNER JOIN SCHOOL SC ON PE.SCHOOL_LINK=SC.LINK INNER JOIN EDUCTYPE ED ON PE.EDUC_LINK=ED.LINK WHERE PE.PERS_LINK = (SELECT PERS_LINK FROM EMPL WHERE LINK=@FACE_LK)  AND ED.CODE=''19'') /*Послевуз. обр. - наим. уч. зав*/ FROM #T_RES T  WHERE SQUERY=45311
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 8.00, '
	UPDATE #T_RES
	SET	SH_SPEC = (SELECT substring(SP.NAME,41,254) FROM PERS_EDUCATION PE INNER JOIN SPECIALITY SP ON PE.SPEC_LINK=SP.LINK INNER JOIN EDUCTYPE ED ON PE.EDUC_LINK=ED.LINK
WHERE PE.PERS_LINK = (SELECT PERS_LINK FROM EMPL WHERE LINK=@FACE_LK)  AND ED.CODE=''19'') /*Послевуз. обр. - специальность*/ FROM #T_RES T  WHERE SQUERY=45311
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 68.00, '
	UPDATE #T_RES
	SET	S_2596 = (SELECT NAME FROM #DOP WHERE NUM=1) /*Доп - 1*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 51.00, '
	UPDATE #T_RES
	SET	S_2364 = ISNULL((SELECT FD.NAME FROM PERSON P INNER JOIN FACE_DOCUMENT FD ON P.DOC_LINK=FD.LINK WHERE P.LINK=S_2158),'''') /*Документ - вид*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 45.00, '
	UPDATE #T_RES
	SET	S_2191 = CASE (SELECT SEX FROM PERSON WHERE LINK=S_2158)
WHEN 1 THEN ''Мужской''
ELSE ''Женский''
END /*Пол*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 46.00, '
	UPDATE #T_RES
	SET	S_2214 = @dDate001 /*Дата составления*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 47.00, '
	UPDATE #T_RES
	SET	S_2220 = ISNULL((SELECT CT.NAME FROM PERSON P INNER JOIN CITIZENSHIP CT ON P.CITIZ_LINK=CT.LINK WHERE P.LINK=S_2158),'''') /*Гражданство*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 48.00, '
	UPDATE #T_RES
	SET	S_2237 = (SELECT BIRTHPLACE FROM PERSON WHERE LINK=S_2158) /*Место рождения*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 49.00, '
	UPDATE #T_RES
	SET	S_2352 = ISNULL((SELECT PROFESSION FROM PERSON WHERE LINK=S_2158),'''') /*Профессия*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 50.00, '
	UPDATE #T_RES
	SET	S_2360 = ISNULL((SELECT M.NAME FROM PERSON P INNER JOIN MARRIAGE M ON P.MAR_LINK=M.LINK WHERE P.LINK=S_2158),'''') /*Семейное положение*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 39.00, '
	UPDATE #T_RES
	SET	EXP_VYS = (select  cast (ISNULL(days, 0) as char(2) ) + ''#'' + cast( isnull(months, 0) as char(2))+''#'' + cast(ISNULL(years, 0) as char(2)) from #expir where code = ''GOS_NADB'') /*Стаж выслуги*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 40.00, '
	UPDATE #T_RES
	SET	S_2162 = (SELECT FM FROM PERSON WHERE LINK = S_2158) /*Фамилия*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 41.00, '
	UPDATE #T_RES
	SET	S_2166 = (SELECT IM FROM PERSON WHERE LINK = S_2158) /*Имя*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 42.00, '
	UPDATE #T_RES
	SET	S_2170 = (SELECT OT FROM PERSON WHERE LINK = S_2158) /*Отчество*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 43.00, '
	UPDATE #T_RES
	SET	S_2178 = ISNULL((SELECT CONVERT(VARCHAR(10),BIRTHDATE,104) AS VALUE FROM PERSON WHERE LINK=S_2158),'''') /*Дата рождения*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 44.00, '
	UPDATE #T_RES
	SET	S_2182 = (SELECT TAB FROM EMPL WHERE LINK=@FACE_LK) /*Табельный номер*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 63.00, '
	UPDATE #T_RES
	SET	S_2472 = (select  cast (ISNULL(days, 0) as char(2) ) + ''#'' + cast( isnull(months, 0) as char(2))+''#'' + cast(ISNULL(years, 0) as char(2)) from #expir where code = ''GOS_PENS'') /*Стаж г-1*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 64.00, '
	UPDATE #T_RES
	SET	S_2515 = ISNULL((SELECT M.CODE FROM PERSON P INNER JOIN MARRIAGE M ON P.MAR_LINK=M.LINK WHERE P.LINK=S_2158),'''') /*Семейное положение - код*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 65.00, '
	UPDATE #T_RES
	SET	S_2523 = (SELECT ADDR_STR FROM #ADDR WHERE  FACT=0) /*Адрес по паспорту*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 32.00, '
	UPDATE #T_RES
	SET	OBR2_2 = (SELECT NAME2 FROM #OBR_LK WHERE REAL_NUM=2) /*Учебное заведение 2 - 2*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 33.00, '
	UPDATE #T_RES
	SET	S_2960 = ISNULL((SELECT VK.NAME FROM PERSON P INNER JOIN VOINKAT VK ON P.VOINKAT_LINK=VK.LINK WHERE P.LINK=S_2158),'''') /*Категория запаса*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 22.00, '
	UPDATE #T_RES
	SET	S_2612 = (SELECT NAME FROM #DOP WHERE NUM=5) /*Доп - 5*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 23.00, '
	UPDATE #T_RES
	SET	S_2224 = ISNULL((SELECT CT.CODE FROM PERSON P INNER JOIN CITIZENSHIP CT ON P.CITIZ_LINK=CT.LINK WHERE P.LINK=S_2158),'''') /*Гражданство (код)*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 59.00, '
	UPDATE #T_RES
	SET	S_2407 = ISNULL((SELECT VZ.CODE FROM PERSON P INNER JOIN VOINZV VZ ON P.VOINZV_LINK=VZ.LINK WHERE P.LINK=S_2158), '''') /*Звание - код*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 60.00, '
	UPDATE #T_RES
	SET	S_2428 = (select CAST (0 AS CHAR(2) )   + ''#''+ CAST (0 AS CHAR(2) )   + ''#''+CAST(0 AS CHAR(2))  ) /*Стаж а-1*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 61.00, '
	UPDATE #T_RES
	SET	EXP_NEPR = (select  cast (ISNULL(days, 0) as char(2) ) + ''#'' + cast( isnull(months, 0) as char(2))+''#'' + cast(ISNULL(years, 0) as char(2)) from #expir where code = ''NEPR'') /*Стаж непрерывный*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 62.00, '
	UPDATE #T_RES
	SET	EXP_GEN = (select  cast (ISNULL(days, 0) as char(2) ) + ''#'' + cast( isnull(months, 0) as char(2))+''#'' + cast(ISNULL(years, 0) as char(2)) from #expir where code = ''GEN'') /*Стаж общий*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 66.00, '
	UPDATE #T_RES
	SET	S_2527 = (SELECT top 1 ADDR_STR FROM #ADDR WHERE  FACT=1) /*Адрес фактический*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 67.00, '
	UPDATE #T_RES
	SET	S_2532 = (SELECT PHONE_REAL FROM PERSON WHERE LINK=S_2158) /*Домашний телефон*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 20.00, '
	UPDATE #T_RES
	SET	STAT = isnull((select top 1 CASE
		WHEN STATUS = 1 THEN ''Основной''
		WHEN STATUS = 2 THEN ''Совместитель''
		WHEN STATUS = 3 THEN ''Совместитель'' END
from dbo.empl_status(default) es inner join empl em on es.empl_link = em.link inner join user_dep d on em.dep_link=d.dep_link where em.link=@FACE_LK),'''') /*Статус*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 21.00, '
	UPDATE #T_RES
	SET	OBR_DOC1 = (SELECT OBR_DOC FROM #OBR_LK WHERE REAL_NUM=1) /*Тип док. об образ. 1*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 74.00, '
	UPDATE #T_RES
	SET	S_5996 = (SELECT NAME1 FROM #LANG_LK WHERE REAL_NUM=1) /*Язык 1*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 75.00, '
	UPDATE #T_RES
	SET	S_6000 = (SELECT SKILL FROM #LANG_LK WHERE REAL_NUM=2) /*Язык 2 - степень знания*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 24.00, '
	UPDATE #T_RES
	SET	S_2881 = ISNULL((SELECT TOP 1 ET.NAME FROM PERS_EDUCATION PD INNER JOIN EDUCTYPE ET ON PD.EDUC_LINK=ET.LINK WHERE PD.PERS_LINK=S_2158  AND ET.CODE<>''19'' ORDER BY ET.CODE DESC),'''') /*Образование*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 25.00, '
	UPDATE #T_RES
	SET	DIPLOM1 = (SELECT DIPLOM FROM #OBR_LK WHERE REAL_NUM=1) /*Диплом - 1*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 176.00, NULL, 26.00, '
	UPDATE #T_RES
	SET	DIPLOM2 = (SELECT DIPLOM FROM #OBR_LK WHERE REAL_NUM=2) /*Диплом - 2*/ FROM #T_RES T 
', 'SYS_T2_FORM', 'SQUERY_SQL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (61.00, 347.00, NULL, NULL, 'KirRepT2.bas', 'SYS_T2_FORM', 'QUERY_ADD_MODULE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (62.00, 139.00, NULL, NULL, 'S_2158', 'SYS_2452199_0I80Z7IRM', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (62.00, 147.00, NULL, NULL, '', 'SYS_2452199_0I80Z7IRM', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (62.00, 148.00, NULL, NULL, '0', 'SYS_2452199_0I80Z7IRM', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (62.00, 155.00, NULL, NULL, '1', 'SYS_2452199_0I80Z7IRM', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (62.00, 158.00, NULL, NULL, '', 'SYS_2452199_0I80Z7IRM', 'SQUERY_FORMULA')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (66.00, 139.00, NULL, NULL, 'S_2162', 'SYS_2452199_0I80Z7JL6', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (66.00, 140.00, NULL, NULL, '3', 'SYS_2452199_0I80Z7JL6', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (66.00, 148.00, NULL, NULL, '12', 'SYS_2452199_0I80Z7JL6', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (66.00, 155.00, NULL, NULL, '3', 'SYS_2452199_0I80Z7JL6', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (70.00, 139.00, NULL, NULL, 'S_2166', 'SYS_2452199_0I80Z7SAC', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (70.00, 140.00, NULL, NULL, '3', 'SYS_2452199_0I80Z7SAC', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (70.00, 148.00, NULL, NULL, '14', 'SYS_2452199_0I80Z7SAC', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (70.00, 155.00, NULL, NULL, '3', 'SYS_2452199_0I80Z7SAC', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (74.00, 139.00, NULL, NULL, 'S_2170', 'SYS_2452199_0I80Z7WXW', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (74.00, 140.00, NULL, NULL, '3', 'SYS_2452199_0I80Z7WXW', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (74.00, 148.00, NULL, NULL, '22', 'SYS_2452199_0I80Z7WXW', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (74.00, 155.00, NULL, NULL, '3', 'SYS_2452199_0I80Z7WXW', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (78.00, 139.00, NULL, NULL, 'S_2178', 'SYS_2452199_0I80Z9M6T', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (78.00, 140.00, NULL, NULL, '3', 'SYS_2452199_0I80Z9M6T', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (78.00, 148.00, NULL, NULL, '24', 'SYS_2452199_0I80Z9M6T', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (78.00, 155.00, NULL, NULL, '3', 'SYS_2452199_0I80Z9M6T', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (82.00, 139.00, NULL, NULL, 'S_2182', 'SYS_2452199_0I80ZD5TT', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (82.00, 140.00, NULL, NULL, '3', 'SYS_2452199_0I80ZD5TT', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (82.00, 148.00, NULL, NULL, '1', 'SYS_2452199_0I80ZD5TT', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (82.00, 155.00, NULL, NULL, '3', 'SYS_2452199_0I80ZD5TT', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (87.00, 139.00, NULL, NULL, 'S_2191', 'SYS_2452199_0I810CBQY', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (87.00, 140.00, NULL, NULL, '3', 'SYS_2452199_0I810CBQY', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (87.00, 148.00, NULL, NULL, '25', 'SYS_2452199_0I810CBQY', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (87.00, 155.00, NULL, NULL, '3', 'SYS_2452199_0I810CBQY', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92.00, 139.00, NULL, NULL, 'S_2214', 'SYS_2452199_0I810RPWN', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92.00, 140.00, NULL, NULL, '3', 'SYS_2452199_0I810RPWN', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92.00, 147.00, NULL, NULL, '', 'SYS_2452199_0I810RPWN', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92.00, 148.00, NULL, NULL, '46', 'SYS_2452199_0I810RPWN', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (92.00, 155.00, NULL, NULL, '3', 'SYS_2452199_0I810RPWN', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (98.00, 139.00, NULL, NULL, 'S_2220', 'SYS_2452200_0I90GVZUP', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (98.00, 140.00, NULL, NULL, '3', 'SYS_2452200_0I90GVZUP', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (98.00, 148.00, NULL, NULL, '27', 'SYS_2452200_0I90GVZUP', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (98.00, 155.00, NULL, NULL, '3', 'SYS_2452200_0I90GVZUP', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (103.00, 139.00, NULL, NULL, 'S_2237', 'SYS_2452200_0I90IRJ3W', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (103.00, 140.00, NULL, NULL, '3', 'SYS_2452200_0I90IRJ3W', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (103.00, 148.00, NULL, NULL, '37', 'SYS_2452200_0I90IRJ3W', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (103.00, 155.00, NULL, NULL, '3', 'SYS_2452200_0I90IRJ3W', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (108.00, 139.00, NULL, NULL, 'S_2352', 'SYS_2452201_0IA0LXM0C', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (108.00, 140.00, NULL, NULL, '3', 'SYS_2452201_0IA0LXM0C', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (108.00, 148.00, NULL, NULL, '29', 'SYS_2452201_0IA0LXM0C', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (108.00, 155.00, NULL, NULL, '3', 'SYS_2452201_0IA0LXM0C', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (116.00, 139.00, NULL, NULL, 'S_2360', 'SYS_2452201_0IA0MTHO8', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (116.00, 140.00, NULL, NULL, '3', 'SYS_2452201_0IA0MTHO8', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (116.00, 148.00, NULL, NULL, '55', 'SYS_2452201_0IA0MTHO8', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (116.00, 155.00, NULL, NULL, '3', 'SYS_2452201_0IA0MTHO8', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (120.00, 139.00, NULL, NULL, 'S_2364', 'SYS_2452201_0IA0MTQ0Q', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (120.00, 140.00, NULL, NULL, '3', 'SYS_2452201_0IA0MTQ0Q', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (120.00, 148.00, NULL, NULL, '57', 'SYS_2452201_0IA0MTQ0Q', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (120.00, 155.00, NULL, NULL, '3', 'SYS_2452201_0IA0MTQ0Q', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (124.00, 139.00, NULL, NULL, 'S_2368', 'SYS_2452201_0IA0MTSDM', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (124.00, 140.00, NULL, NULL, '3', 'SYS_2452201_0IA0MTSDM', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (124.00, 148.00, NULL, NULL, '21', 'SYS_2452201_0IA0MTSDM', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (124.00, 155.00, NULL, NULL, '3', 'SYS_2452201_0IA0MTSDM', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (128.00, 139.00, NULL, NULL, 'S_2380', 'SYS_2452201_0IA0MUAIY', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (128.00, 140.00, NULL, NULL, '3', 'SYS_2452201_0IA0MUAIY', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (128.00, 148.00, NULL, NULL, '18', 'SYS_2452201_0IA0MUAIY', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (128.00, 155.00, NULL, NULL, '3', 'SYS_2452201_0IA0MUAIY', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (128.00, 158.00, NULL, NULL, '', 'SYS_2452201_0IA0MUAIY', 'SQUERY_FORMULA')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (135.00, 139.00, NULL, NULL, 'S_2387', 'SYS_2452201_0IA0O7G4P', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (135.00, 140.00, NULL, NULL, '3', 'SYS_2452201_0IA0O7G4P', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (135.00, 147.00, NULL, NULL, '', 'SYS_2452201_0IA0O7G4P', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (135.00, 148.00, NULL, NULL, '62', 'SYS_2452201_0IA0O7G4P', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (135.00, 155.00, NULL, NULL, '3', 'SYS_2452201_0IA0O7G4P', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (139.00, 139.00, NULL, NULL, 'S_2391', 'SYS_2452201_0IA0O7QNK', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (139.00, 140.00, NULL, NULL, '3', 'SYS_2452201_0IA0O7QNK', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (139.00, 148.00, NULL, NULL, '20', 'SYS_2452201_0IA0O7QNK', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (139.00, 155.00, NULL, NULL, '3', 'SYS_2452201_0IA0O7QNK', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (143.00, 139.00, NULL, NULL, 'S_2395', 'SYS_2452201_0IA0O9U0G', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (143.00, 140.00, NULL, NULL, '3', 'SYS_2452201_0IA0O9U0G', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (143.00, 147.00, NULL, NULL, '', 'SYS_2452201_0IA0O9U0G', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (143.00, 148.00, NULL, NULL, '19', 'SYS_2452201_0IA0O9U0G', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (143.00, 155.00, NULL, NULL, '3', 'SYS_2452201_0IA0O9U0G', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (147.00, 139.00, NULL, NULL, 'S_2399', 'SYS_2452201_0IA0O9Z2A', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (147.00, 140.00, NULL, NULL, '3', 'SYS_2452201_0IA0O9Z2A', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (147.00, 148.00, NULL, NULL, '16', 'SYS_2452201_0IA0O9Z2A', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (147.00, 155.00, NULL, NULL, '3', 'SYS_2452201_0IA0O9Z2A', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (151.00, 139.00, NULL, NULL, 'S_2403', 'SYS_2452201_0IA0OA497', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (151.00, 140.00, NULL, NULL, '3', 'SYS_2452201_0IA0OA497', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (151.00, 148.00, NULL, NULL, '23', 'SYS_2452201_0IA0OA497', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (151.00, 155.00, NULL, NULL, '3', 'SYS_2452201_0IA0OA497', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (155.00, 139.00, NULL, NULL, 'S_2407', 'SYS_2452201_0IA0OSUPP', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (155.00, 140.00, NULL, NULL, '3', 'SYS_2452201_0IA0OSUPP', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (155.00, 148.00, NULL, NULL, '17', 'SYS_2452201_0IA0OSUPP', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (155.00, 155.00, NULL, NULL, '3', 'SYS_2452201_0IA0OSUPP', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (165.00, 139.00, NULL, NULL, 'S_2428', 'SYS_2452201_0IA0V6RBC', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (165.00, 140.00, NULL, NULL, '3', 'SYS_2452201_0IA0V6RBC', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (165.00, 148.00, NULL, NULL, '63', 'SYS_2452201_0IA0V6RBC', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (165.00, 155.00, NULL, NULL, '3', 'SYS_2452201_0IA0V6RBC', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (169.00, 139.00, NULL, NULL, 'EXP_NEPR', 'SYS_2452201_0IA0V7CJH', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (169.00, 140.00, NULL, NULL, '3', 'SYS_2452201_0IA0V7CJH', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (169.00, 147.00, NULL, NULL, '', 'SYS_2452201_0IA0V7CJH', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (169.00, 148.00, NULL, NULL, '58', 'SYS_2452201_0IA0V7CJH', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (169.00, 155.00, NULL, NULL, '3', 'SYS_2452201_0IA0V7CJH', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (173.00, 139.00, NULL, NULL, 'EXP_GEN', 'SYS_2452201_0IA0V7UXZ', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (173.00, 140.00, NULL, NULL, '3', 'SYS_2452201_0IA0V7UXZ', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (173.00, 148.00, NULL, NULL, '51', 'SYS_2452201_0IA0V7UXZ', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (173.00, 155.00, NULL, NULL, '3', 'SYS_2452201_0IA0V7UXZ', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (177.00, 139.00, NULL, NULL, 'S_2472', 'SYS_2452201_0IA0V83YQ', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (177.00, 140.00, NULL, NULL, '3', 'SYS_2452201_0IA0V83YQ', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (177.00, 147.00, NULL, NULL, '', 'SYS_2452201_0IA0V83YQ', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (177.00, 148.00, NULL, NULL, '53', 'SYS_2452201_0IA0V83YQ', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (177.00, 155.00, NULL, NULL, '3', 'SYS_2452201_0IA0V83YQ', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (206.00, 139.00, NULL, NULL, 'S_2515', 'SYS_2452202_0IB0TMHPA', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (206.00, 140.00, NULL, NULL, '3', 'SYS_2452202_0IB0TMHPA', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (206.00, 148.00, NULL, NULL, '15', 'SYS_2452202_0IB0TMHPA', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (206.00, 155.00, NULL, NULL, '3', 'SYS_2452202_0IB0TMHPA', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (212.00, 139.00, NULL, NULL, 'S_2523', 'SYS_2452203_0IC0O01TS', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (212.00, 140.00, NULL, NULL, '3', 'SYS_2452203_0IC0O01TS', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (212.00, 147.00, NULL, NULL, '', 'SYS_2452203_0IC0O01TS', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (212.00, 148.00, NULL, NULL, '13', 'SYS_2452203_0IC0O01TS', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (212.00, 155.00, NULL, NULL, '3', 'SYS_2452203_0IC0O01TS', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (216.00, 139.00, NULL, NULL, 'S_2527', 'SYS_2452203_0IC0O0AJT', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (216.00, 140.00, NULL, NULL, '3', 'SYS_2452203_0IC0O0AJT', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (216.00, 147.00, NULL, NULL, '', 'SYS_2452203_0IC0O0AJT', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (216.00, 148.00, NULL, NULL, '11', 'SYS_2452203_0IC0O0AJT', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (216.00, 155.00, NULL, NULL, '3', 'SYS_2452203_0IC0O0AJT', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (221.00, 139.00, NULL, NULL, 'S_2532', 'SYS_2452203_0IC0ONKUH', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (221.00, 140.00, NULL, NULL, '3', 'SYS_2452203_0IC0ONKUH', 'SQUERY_FIELD_DIRECT_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (221.00, 148.00, NULL, NULL, '7', 'SYS_2452203_0IC0ONKUH', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (221.00, 155.00, NULL, NULL, '3', 'SYS_2452203_0IC0ONKUH', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (230.00, 139.00, NULL, NULL, 'S_2596', 'SYS_2452205_0IE0KK2U6', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (230.00, 148.00, NULL, NULL, '0', 'SYS_2452205_0IE0KK2U6', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (230.00, 155.00, NULL, NULL, '3', 'SYS_2452205_0IE0KK2U6', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (234.00, 139.00, NULL, NULL, 'S_2600', 'SYS_2452205_0IE0KK79I', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (234.00, 148.00, NULL, NULL, '0', 'SYS_2452205_0IE0KK79I', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (234.00, 155.00, NULL, NULL, '3', 'SYS_2452205_0IE0KK79I', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (238.00, 139.00, NULL, NULL, 'S_2604', 'SYS_2452205_0IE0KKB12', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (238.00, 148.00, NULL, NULL, '0', 'SYS_2452205_0IE0KKB12', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (238.00, 155.00, NULL, NULL, '3', 'SYS_2452205_0IE0KKB12', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (242.00, 139.00, NULL, NULL, 'S_2608', 'SYS_2452205_0IE0KKEJ2', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (242.00, 148.00, NULL, NULL, '0', 'SYS_2452205_0IE0KKEJ2', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (242.00, 155.00, NULL, NULL, '3', 'SYS_2452205_0IE0KKEJ2', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (246.00, 139.00, NULL, NULL, 'S_2612', 'SYS_2452205_0IE0KKGS6', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (246.00, 148.00, NULL, NULL, '0', 'SYS_2452205_0IE0KKGS6', 'SQUERY_FIELD_ORDER_XL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (246.00, 155.00, NULL, NULL, '3', 'SYS_2452205_0IE0KKGS6', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (268.00, 139.00, NULL, NULL, 'S_2224', 'SYS_2452207_0IG0GM1JJ', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (268.00, 147.00, NULL, NULL, '', 'SYS_2452207_0IG0GM1JJ', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (268.00, 155.00, NULL, NULL, '3', 'SYS_2452207_0IG0GM1JJ', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (268.00, 158.00, NULL, NULL, '', 'SYS_2452207_0IG0GM1JJ', 'SQUERY_FORMULA')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (272.00, 139.00, NULL, NULL, 'S_2881', 'SYS_2452207_0IG0HM647', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (272.00, 155.00, NULL, NULL, '3', 'SYS_2452207_0IG0HM647', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (284.00, 139.00, NULL, NULL, 'DIPLOM1', 'SYS_2452207_0IG0LXRI8', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (284.00, 155.00, NULL, NULL, '3', 'SYS_2452207_0IG0LXRI8', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (288.00, 139.00, NULL, NULL, 'DIPLOM2', 'SYS_2452207_0IG0LXUWD', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (288.00, 155.00, NULL, NULL, '3', 'SYS_2452207_0IG0LXUWD', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (292.00, 139.00, NULL, NULL, 'OBR_END1', 'SYS_2452207_0IG0LXYXA', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (292.00, 155.00, NULL, NULL, '3', 'SYS_2452207_0IG0LXYXA', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (296.00, 139.00, NULL, NULL, 'OBR_END2', 'SYS_2452207_0IG0LY172', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (296.00, 155.00, NULL, NULL, '3', 'SYS_2452207_0IG0LY172', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (300.00, 139.00, NULL, NULL, 'OBR1_1', 'SYS_2452207_0IG0LY7I6', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (300.00, 155.00, NULL, NULL, '3', 'SYS_2452207_0IG0LY7I6', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (304.00, 139.00, NULL, NULL, 'OBR1_2', 'SYS_2452207_0IG0LY9FS', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (304.00, 155.00, NULL, NULL, '3', 'SYS_2452207_0IG0LY9FS', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (308.00, 139.00, NULL, NULL, 'OBR2_1', 'SYS_2452207_0IG0LYDHF', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (308.00, 155.00, NULL, NULL, '3', 'SYS_2452207_0IG0LYDHF', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (312.00, 139.00, NULL, NULL, 'OBR2_2', 'SYS_2452207_0IG0LYG8O', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (312.00, 155.00, NULL, NULL, '3', 'SYS_2452207_0IG0LYG8O', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (325.00, 139.00, NULL, NULL, 'S_2960', 'SYS_2452207_0IG0SJ0SM', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (325.00, 155.00, NULL, NULL, '3', 'SYS_2452207_0IG0SJ0SM', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (329.00, 139.00, NULL, NULL, 'S_2964', 'SYS_2452207_0IG0SJ73O', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (329.00, 155.00, NULL, NULL, '3', 'SYS_2452207_0IG0SJ73O', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (337.00, 139.00, NULL, NULL, 'S_2978', 'SYS_2452207_0IG0TIJUB', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (337.00, 155.00, NULL, NULL, '3', 'SYS_2452207_0IG0TIJUB', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (341.00, 139.00, NULL, NULL, 'S_2982', 'SYS_2452207_0IG0TIR37', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (341.00, 155.00, NULL, NULL, '3', 'SYS_2452207_0IG0TIR37', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (426.00, 139.00, NULL, NULL, 'S_2972', 'SYS_2452214_0IN0UBYHW', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (426.00, 155.00, NULL, NULL, '3', 'SYS_2452214_0IN0UBYHW', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (432.00, 139.00, NULL, NULL, 'SPEC1', 'SYS_2452214_0IN0VTJYG', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (432.00, 147.00, NULL, NULL, '', 'SYS_2452214_0IN0VTJYG', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (432.00, 155.00, NULL, NULL, '1', 'SYS_2452214_0IN0VTJYG', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (436.00, 139.00, NULL, NULL, 'SPEC2', 'SYS_2452214_0IN0VTR34', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (436.00, 155.00, NULL, NULL, '1', 'SYS_2452214_0IN0VTR34', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (465.00, 139.00, NULL, NULL, 'OKSO1', 'SYS_2452214_0IN0YNBKY', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (465.00, 147.00, NULL, NULL, '', 'SYS_2452214_0IN0YNBKY', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (465.00, 155.00, NULL, NULL, '1', 'SYS_2452214_0IN0YNBKY', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (469.00, 139.00, NULL, NULL, 'OKSO2', 'SYS_2452214_0IN0YNF73', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (469.00, 147.00, NULL, NULL, '', 'SYS_2452214_0IN0YNF73', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (469.00, 155.00, NULL, NULL, '1', 'SYS_2452214_0IN0YNF73', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (994.00, 139.00, NULL, NULL, 'S_5984', 'SYS_2452244_0JH0JKLCT', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (994.00, 155.00, NULL, NULL, '3', 'SYS_2452244_0JH0JKLCT', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1002.00, 139.00, NULL, NULL, 'S_5992', 'SYS_2452244_0JH0N7EZ8', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1002.00, 155.00, NULL, NULL, '3', 'SYS_2452244_0JH0N7EZ8', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1006.00, 139.00, NULL, NULL, 'S_5996', 'SYS_2452244_0JH0N7KRV', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1006.00, 155.00, NULL, NULL, '3', 'SYS_2452244_0JH0N7KRV', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1010.00, 139.00, NULL, NULL, 'S_6000', 'SYS_2452244_0JH0N7P0K', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1010.00, 155.00, NULL, NULL, '3', 'SYS_2452244_0JH0N7P0K', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1014.00, 139.00, NULL, NULL, 'S_6004', 'SYS_2452244_0JH0N7SBX', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1014.00, 155.00, NULL, NULL, '3', 'SYS_2452244_0JH0N7SBX', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1655.00, 163.00, NULL, NULL, '@nOption_3', 'SYS_2452381_0NC13J9F8', 'SQUERY_NASTR_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1655.00, 166.00, NULL, NULL, '1', 'SYS_2452381_0NC13J9F8', 'SQUERY_NASTR_SAVE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1655.00, 167.00, NULL, NULL, 'А4,A3', 'SYS_2452381_0NC13J9F8', 'SQUERY_NASTR_SOURCE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1655.00, 168.00, NULL, NULL, 'А4', 'SYS_2452381_0NC13J9F8', 'SQUERY_NASTR_VALUE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1663.00, 139.00, NULL, NULL, 'dis_ord', 'SYS_2452385_0NG0Q710R', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1663.00, 155.00, NULL, NULL, '3', 'SYS_2452385_0NG0Q710R', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (1663.00, 158.00, NULL, NULL, '', 'SYS_2452385_0NG0Q710R', 'SQUERY_FORMULA')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2088.00, 163.00, NULL, NULL, '@nOption_4', 'SYS_2452454_0PD0ISDF4', 'SQUERY_NASTR_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2088.00, 166.00, NULL, NULL, '1', 'SYS_2452454_0PD0ISDF4', 'SQUERY_NASTR_SAVE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2088.00, 167.00, NULL, NULL, 'Форма Т-2,Форма Т-2ГС', 'SYS_2452454_0PD0ISDF4', 'SQUERY_NASTR_SOURCE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2088.00, 168.00, NULL, NULL, 'Форма Т-2', 'SYS_2452454_0PD0ISDF4', 'SQUERY_NASTR_VALUE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2089.00, 163.00, NULL, NULL, '@nCheck_5', 'SYS_2452454_0PD0P4I3N', 'SQUERY_NASTR_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2089.00, 166.00, NULL, NULL, '1', 'SYS_2452454_0PD0P4I3N', 'SQUERY_NASTR_SAVE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (2089.00, 168.00, NULL, NULL, 'Вкл.', 'SYS_2452454_0PD0P4I3N', 'SQUERY_NASTR_VALUE')

GO

		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (3593.00, 1.00, NULL, NULL, '0', 'SYS_815448_737109263', 'SQUERY_NASTR_OPTIONAL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (3593.00, 168.00, NULL, NULL, 'Текущая дата', 'SYS_815448_737109263', 'SQUERY_NASTR_VALUE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (3594.00, 1.00, NULL, NULL, '0', 'SYS_T2_FORM_MAIN_PARAM', 'SQUERY_NASTR_OPTIONAL')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (3594.00, 166.00, NULL, NULL, '1', 'SYS_T2_FORM_MAIN_PARAM', 'SQUERY_NASTR_SAVE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (3594.00, 217.00, NULL, NULL, '1', 'SYS_T2_FORM_MAIN_PARAM', 'SQUERY_NASTR_NON_VISIBLE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5328.00, 139.00, NULL, NULL, 'S_24409', 'SYS_2452669_0VE0JXYFC', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5328.00, 155.00, NULL, NULL, '3', 'SYS_2452669_0VE0JXYFC', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5333.00, 139.00, NULL, NULL, 'S_24414', 'SYS_2452669_0VE0KHHIJ', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5333.00, 155.00, NULL, NULL, '3', 'SYS_2452669_0VE0KHHIJ', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5782.00, 139.00, NULL, NULL, 'uch_st', 'SYS_2452716_0WP0SCPUR', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5782.00, 155.00, NULL, NULL, '3', 'SYS_2452716_0WP0SCPUR', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5787.00, 139.00, NULL, NULL, 'UCH_S_C', 'SYS_2452716_0WP0SJK9U', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5787.00, 155.00, NULL, NULL, '3', 'SYS_2452716_0WP0SJK9U', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5787.00, 158.00, NULL, NULL, '', 'SYS_2452716_0WP0SJK9U', 'SQUERY_FORMULA')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5791.00, 139.00, NULL, NULL, 'S_26265', 'SYS_2452716_0WP0SUNOB', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5791.00, 155.00, NULL, NULL, '1', 'SYS_2452716_0WP0SUNOB', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5795.00, 139.00, NULL, NULL, 'S_2511', 'SYS_2452716_0WP0SUO0H', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5795.00, 155.00, NULL, NULL, '3', 'SYS_2452716_0WP0SUO0H', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5799.00, 139.00, NULL, NULL, 'OKPO', 'SYS_2452716_0WP0SURA4', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5799.00, 155.00, NULL, NULL, '3', 'SYS_2452716_0WP0SURA4', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5985.00, 139.00, NULL, NULL, 'KVAL1', 'SYS_2452744_0XH0N9G5B', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5985.00, 147.00, NULL, NULL, '', 'SYS_2452744_0XH0N9G5B', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5985.00, 155.00, NULL, NULL, '1', 'SYS_2452744_0XH0N9G5B', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5989.00, 139.00, NULL, NULL, 'KVAL2', 'SYS_2452744_0XH0N9IL0', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (5989.00, 155.00, NULL, NULL, '1', 'SYS_2452744_0XH0N9IL0', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6120.00, 139.00, NULL, NULL, 'DATE_REG', 'SYS_2452819_0ZK0SLDB9', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6120.00, 155.00, NULL, NULL, '3', 'SYS_2452819_0ZK0SLDB9', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6897.00, 139.00, NULL, NULL, 'KONTR_DATE', 'SYS_2452878_1170VWIDI', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6897.00, 155.00, NULL, NULL, '3', 'SYS_2452878_1170VWIDI', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6901.00, 139.00, NULL, NULL, 'KONTR_NUM', 'SYS_2452878_1170VWKIB', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (6901.00, 155.00, NULL, NULL, '3', 'SYS_2452878_1170VWKIB', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (9246.00, 139.00, NULL, NULL, 'DIS_REASON', 'SYS_9D83AA4F-B9BE-4265-A427-29615EA664D5', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (9246.00, 155.00, NULL, NULL, '3', 'SYS_9D83AA4F-B9BE-4265-A427-29615EA664D5', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (9744.00, 139.00, NULL, NULL, 'EXP_VYS', 'SYS_B15C585A-AD14-438C-A792-6343ECDC0F27', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (9744.00, 155.00, NULL, NULL, '3', 'SYS_B15C585A-AD14-438C-A792-6343ECDC0F27', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (9749.00, 139.00, NULL, NULL, 'DATE_BEGIN', 'SYS_24BCA28F-D442-4C5A-B123-E14B5F73FD9E', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (9749.00, 147.00, NULL, NULL, '', 'SYS_24BCA28F-D442-4C5A-B123-E14B5F73FD9E', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (9749.00, 155.00, NULL, NULL, '1', 'SYS_24BCA28F-D442-4C5A-B123-E14B5F73FD9E', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (10468.00, 139.00, NULL, NULL, 'DIS_OD', 'SYS_E4A34200-71DF-423A-9A3E-0199823056C3', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (10468.00, 155.00, NULL, NULL, '3', 'SYS_E4A34200-71DF-423A-9A3E-0199823056C3', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (10468.00, 158.00, NULL, NULL, '', 'SYS_E4A34200-71DF-423A-9A3E-0199823056C3', 'SQUERY_FORMULA')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11257.00, 139.00, NULL, NULL, 'SH_TYPE', 'SYS_2453114_17T0YPW9F', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11257.00, 152.00, NULL, NULL, 'VARCHAR(20)', 'SYS_2453114_17T0YPW9F', 'SQUERY_FIELD_SQLTYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11257.00, 155.00, NULL, NULL, '2', 'SYS_2453114_17T0YPW9F', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11257.00, 158.00, NULL, NULL, '(SELECT  '' '' as blank FROM PERSON WHERE LINK=(SELECT PERS_LINK FROM EMPL WHERE LINK=@FACE_LK) )', 'SYS_2453114_17T0YPW9F', 'SQUERY_FORMULA')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11258.00, 139.00, NULL, NULL, 'SH_DOC', 'SYS_2453114_17T0YQI0V', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11258.00, 152.00, NULL, NULL, 'VARCHAR(20)', 'SYS_2453114_17T0YQI0V', 'SQUERY_FIELD_SQLTYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11258.00, 155.00, NULL, NULL, '2', 'SYS_2453114_17T0YQI0V', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11258.00, 158.00, NULL, NULL, '(SELECT PE.DOC_NUM FROM PERS_EDUCATION PE INNER JOIN EDUCTYPE ED ON PE.EDUC_LINK=ED.LINK
WHERE PE.PERS_LINK = (SELECT PERS_LINK FROM EMPL WHERE LINK=@FACE_LK)  AND ED.CODE=''19'')', 'SYS_2453114_17T0YQI0V', 'SQUERY_FORMULA')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11259.00, 139.00, NULL, NULL, 'SH_DEP', 'SYS_2453114_17T0YR570', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11259.00, 152.00, NULL, NULL, 'VARCHAR(254)', 'SYS_2453114_17T0YR570', 'SQUERY_FIELD_SQLTYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11259.00, 155.00, NULL, NULL, '2', 'SYS_2453114_17T0YR570', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11259.00, 158.00, NULL, NULL, '(SELECT SC.NAME FROM PERS_EDUCATION PE INNER JOIN SCHOOL SC ON PE.SCHOOL_LINK=SC.LINK INNER JOIN EDUCTYPE ED ON PE.EDUC_LINK=ED.LINK WHERE PE.PERS_LINK = (SELECT PERS_LINK FROM EMPL WHERE LINK=@FACE_LK)  AND ED.CODE=''19'')', 'SYS_2453114_17T0YR570', 'SQUERY_FORMULA')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11260.00, 139.00, NULL, NULL, 'SH_SPEC', 'SYS_2453114_17T0YRKJH', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11260.00, 152.00, NULL, NULL, 'VARCHAR(40)', 'SYS_2453114_17T0YRKJH', 'SQUERY_FIELD_SQLTYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11260.00, 155.00, NULL, NULL, '2', 'SYS_2453114_17T0YRKJH', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11260.00, 158.00, NULL, NULL, '(SELECT substring(SP.NAME,41,254) FROM PERS_EDUCATION PE INNER JOIN SPECIALITY SP ON PE.SPEC_LINK=SP.LINK INNER JOIN EDUCTYPE ED ON PE.EDUC_LINK=ED.LINK
WHERE PE.PERS_LINK = (SELECT PERS_LINK FROM EMPL WHERE LINK=@FACE_LK)  AND ED.CODE=''19'')', 'SYS_2453114_17T0YRKJH', 'SQUERY_FORMULA')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11260.00, 182.00, NULL, NULL, '', 'SYS_2453114_17T0YRKJH', 'SQUERY_WHERE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11260.00, 335.00, NULL, NULL, '', 'SYS_2453114_17T0YRKJH', 'SQUERY_FIELD_CALC_AFTER')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11261.00, 139.00, NULL, NULL, 'sh_spec2', 'SYS_2453114_17T0YS28O', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11261.00, 152.00, NULL, NULL, 'VARCHAR(254)', 'SYS_2453114_17T0YS28O', 'SQUERY_FIELD_SQLTYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11261.00, 155.00, NULL, NULL, '2', 'SYS_2453114_17T0YS28O', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11261.00, 158.00, NULL, NULL, '(SELECT substring(SP.NAME,41,254) FROM PERS_EDUCATION PE INNER JOIN SPECIALITY SP ON PE.SPEC_LINK=SP.LINK INNER JOIN EDUCTYPE ED ON PE.EDUC_LINK=ED.LINK 
WHERE PE.PERS_LINK = (SELECT PERS_LINK FROM EMPL WHERE LINK=@FACE_LK)  AND ED.CODE=''19'')', 'SYS_2453114_17T0YS28O', 'SQUERY_FORMULA')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11262.00, 139.00, NULL, NULL, 'SH_DATE', 'SYS_2453114_17T0YYAAN', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11262.00, 152.00, NULL, NULL, 'DATETIME', 'SYS_2453114_17T0YYAAN', 'SQUERY_FIELD_SQLTYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11262.00, 155.00, NULL, NULL, '2', 'SYS_2453114_17T0YYAAN', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11262.00, 158.00, NULL, NULL, '(SELECT PE.DOC_DATE FROM PERS_EDUCATION PE INNER JOIN EDUCTYPE ED ON PE.EDUC_LINK=ED.LINK WHERE PE.PERS_LINK = (SELECT PERS_LINK FROM EMPL WHERE LINK=@FACE_LK)  AND ED.CODE=''19'')', 'SYS_2453114_17T0YYAAN', 'SQUERY_FORMULA')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11263.00, 139.00, NULL, NULL, 'SH_YEAR', 'SYS_2453114_17T0Z1MMF', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11263.00, 152.00, NULL, NULL, 'VARCHAR(4)', 'SYS_2453114_17T0Z1MMF', 'SQUERY_FIELD_SQLTYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11263.00, 155.00, NULL, NULL, '2', 'SYS_2453114_17T0Z1MMF', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11263.00, 158.00, NULL, NULL, '(SELECT convert(varchar(4),year(PE.DATE_END)) FROM PERS_EDUCATION PE INNER JOIN EDUCTYPE ED ON PE.EDUC_LINK=ED.LINK
WHERE PE.PERS_LINK = (SELECT PERS_LINK FROM EMPL WHERE LINK=@FACE_LK)  AND ED.CODE=''19'')', 'SYS_2453114_17T0Z1MMF', 'SQUERY_FORMULA')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (11263.00, 335.00, NULL, NULL, '', 'SYS_2453114_17T0Z1MMF', 'SQUERY_FIELD_CALC_AFTER')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (15665.00, 139.00, NULL, NULL, 'STAT', 'SYS_B8FFE4E2-96EA-49DB-A8C0-A905D873A682', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (15665.00, 155.00, NULL, NULL, '3', 'SYS_B8FFE4E2-96EA-49DB-A8C0-A905D873A682', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (15666.00, 139.00, NULL, NULL, 'OBR_DOC1', 'SYS_E6A76FE4-F013-4DE1-8AC1-58CCEC48B95C', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (15666.00, 155.00, NULL, NULL, '3', 'SYS_E6A76FE4-F013-4DE1-8AC1-58CCEC48B95C', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (15671.00, 139.00, NULL, NULL, 'OBR_DOC2', 'SYS_3A595A76-2F0E-4682-BFB5-58E7FEAD9142', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (15671.00, 155.00, NULL, NULL, '3', 'SYS_3A595A76-2F0E-4682-BFB5-58E7FEAD9142', 'SQUERY_FIELD_TYPE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (15672.00, 139.00, NULL, NULL, 'CHARACT2', 'SYS_44A449E2-29E2-49C2-947D-93478E146754', 'SQUERY_FIELD_CODE')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (15672.00, 147.00, NULL, NULL, '', 'SYS_44A449E2-29E2-49C2-947D-93478E146754', 'SQUERY_FIELD_NOT_RESULT')
		INSERT INTO #T_OVV(LINK_UP,  PROPERTY,  USERS,  ORDERS,  VALUE,  CODE_UP,  CODE_PROP) VALUES (15672.00, 155.00, NULL, NULL, '3', 'SYS_44A449E2-29E2-49C2-947D-93478E146754', 'SQUERY_FIELD_TYPE')

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', 'Форма № Т-2 (личная карточка)', 1.00, 1, 'FACE_MAP_TREE_ROOT', 'SQUERY_USER', 'SYS_T2_FORM', 'ALL_USER_REPORT')

GO

		exec KIR_UPGRADE_OV 0 
GO

		DROP TABLE #T_OV
GO

		DROP TABLE #T_OVV
GO

		DROP TABLE #T_NAVIGATOR
GO


GO
EXEC X_SET_PROP 'VACATION_MOVE', 'SAVE_OBJECT_METHOD', 'U_SAVE_TABLE_PART(''KU_VACATION_SAVE'', m.cAlias," NUMBER, SQLNULL(DATE), TYPE_LINK, 0, SQLNULL(PERIOD_BEGIN), SQLNULL(PERIOD_END), SQLNULL(DATE_BEGIN),  SQLNULL(DATE_END), null,REASON,null, EMPL_LINK, ORDER_LINK, null,null, VAC_LINK","VACATION")'
GO
GO
EXEC X_SET_PROP 'VACATION', 'SAVE_OBJECT_METHOD', 'U_SAVE_TABLE_PART(''KU_VACATION_SAVE'', m.cAlias," NUMBER, SQLNULL(DATE), SQLNULL(TYPE_LINK), COMPENS, SQLNULL(PERIOD_BEGIN), SQLNULL(PERIOD_END), SQLNULL(DATE_BEGIN), SQLNULL(DATE_END), SQLNULL(REASON_LINK),REASON,REASON_DOP, EMPL_LINK, ORDER_LINK,VAC_GRAPH_LINK","VACATION")'
GO

GO

/****** Объект: Компенсация за отпуск******/

IF EXISTS( SELECT * FROM DBO.S_OBJECTS WHERE CODE = 'VAC_COMPENS')
	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_COMPENS')
	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_COMPENS')
	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_COMPENS')
	
	DELETE FROM DBO.S_OBJECTS WHERE CODE = 'VAC_COMPENS'
ELSE
	DELETE FROM DBO.S_OBJECTS WHERE LINK_SELF IN (SELECT LINK FROM DBO.S_OBJECTS WHERE CODE = 'VAC_COMPENS')	

GO

IF NOT EXISTS(SELECT * FROM S_OBJECTS WHERE CODE='VAC_COMPENS')
	INSERT S_OBJECTS (CODE, NAME, ORDERS, LINK_SELF, LINK_CLASS, MANAGED, INHERITED)
	SELECT 'VAC_COMPENS', 'Компенсация за отпуск', 20, (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_COMPENS', NAME = 'Компенсация за отпуск', ORDERS = '20', 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_COMPENS'
GO
EXEC X_SET_PROP 'VAC_COMPENS', 'TITLE', 'Компенсация за отпуск'
GO
EXEC X_SET_PROP 'VAC_COMPENS', 'VISIBLE', '15'
GO
EXEC X_SET_PROP 'VAC_COMPENS', 'CONTROLSOURCE', 'm.cAlias+".COMPENS"'
GO
EXEC X_SET_PROP 'VAC_COMPENS', 'EDITABLE', '1'
GO
EXEC X_SET_PROP 'VAC_COMPENS', 'FIELD_IN_ALIAS', '3'
GO
EXEC X_SET_PROP 'VAC_COMPENS', 'TYPE_FIELD_DICT', 'int'
GO
EXEC X_SET_PROP 'VAC_COMPENS', 'CONTROLSOURCE_EDIT', 'm.cAlias+".COMPENS"'
GO
EXEC X_SET_PROP 'VAC_COMPENS', 'CONTROL_NAME_EDIT', 'acheckbox15'
GO
EXEC X_SET_PROP 'VAC_COMPENS', 'ASPTYPE', 'WebTextEdit'
GO
EXEC X_SET_PROP 'VAC_COMPENS', 'ATTRIBUTES', 'style="Z-INDEX: 148; LEFT: 288px; POSITION: absolute; TOP: 112px""
Width="424px"'
GO
EXEC X_SET_PROP 'VAC_COMPENS', 'LABEL_ATTRIBUTES', 'style="Z-INDEX: 116; LEFT: 16px; POSITION: absolute; TOP: 112px"'
GO

/**************** УСТАНОВКА ДОСТУПА К ОБЪЕКТУ *************/


GO
IF EXISTS( SELECT * FROM  VACATION_VID WHERE isnull(VAC_V,0)= 0)
	UPDATE VV
	SET  VAC_V = CASE WHEN (COALESCE(Vv.ADM,0) = 1 OR d.NAME like 'Адм%') THEN 1 
				   WHEN COALESCE(Vv.ADM,0) = 0 
						AND COALESCE(D.WORK_D,0) NOT IN (5,7) 
						AND ( D.NAME LIKE '%дополн%отпуск%'	
							  OR D.NAME LIKE '%отпуск%дополн%' 
							  OR D.NAME LIKE '%доп.%отп.%' 
							  OR D.NAME LIKE '%отп.%доп.%' )
						AND ( vv.Name LIKE '%дополн%отпуск%'	
							  OR vv.Name  LIKE '%отпуск%дополн%' 
							  OR vv.NAME LIKE '%доп.%отп.%' 
							  OR vv.NAME LIKE '%отп.%доп.%')
						/*AND (Vv.LINK_PAYS = (SELECT TOP 1 link 
						                   FROM PAYS p 
											WHERE p.way_calc = 15 
											AND (p.NAME LIKE '%дополн%отпуск%' 
													OR p.NAME LIKE '%отпуск%дополн%'
													or p.NAME LIKE '%доп.%отп.%' 
													OR p.NAME LIKE '%отп.%доп.%' ))
								/*OR  Vv.LINK_PAYS IS NULL*/)*/
										
				   THEN 2
				   WHEN COALESCE(Vv.ADM,0) = 0 
						AND COALESCE(D.WORK_D,0) NOT IN (5,7) 
						AND (( D.NAME LIKE '%основн%отпуск%'	
							  OR D.NAME LIKE '%отпуск%основн%' 
							  OR D.NAME LIKE '%ежегодн%отпуск%'
							  OR D.NAME LIKE '%отпуск%ежегодн%'
							  OR D.NAME LIKE '%планов%отпуск%'
							  OR D.NAME LIKE '%отпуск%планов%') AND d.name NOT LIKE '%доп%')
							  	  
						AND ((vv.Name LIKE '%основн%отпуск%' 
							  OR vv.Name LIKE '%отпуск%основн%' 
							  OR vv.Name LIKE '%ежегодн%отпуск%'
							  OR vv.Name LIKE '%отпуск%ежегодн%'
							  OR vv.Name LIKE '%планов%отпуск%'
							  OR vv.Name LIKE '%отпуск%планов%' ) and  vv.Name not LIKE '%доп%')
						/*AND  vv.LINK_PAYS = (SELECT TOP 1 link 
						                   FROM PAYS p 
											WHERE p.way_calc = 15 
											AND (p.NAME LIKE '%основн%отпуск%' 
													OR p.NAME LIKE '%отпуск%основн%' 
													OR p.NAME LIKE '%ежегодн%отпуск%'
													OR p.NAME LIKE '%отпуск%ежегодн%'
													OR p.NAME LIKE '%планов%отпуск%'
													OR p.NAME LIKE '%отпуск%планов%'  ))*/
														
			
				   THEN 3
 				   WHEN COALESCE(D.WORK_D,0) in(7) THEN 4
				   WHEN COALESCE(D.WORK_D,0) = 5 THEN 5
				  ELSE 0 end
				  
		FROM VACATION_VID  vv  
		left join dbo.TYP_DAYS D on VV.TYPE_LINK = D.LINK	
		/*LEFT JOIN dbo.PAYS p ON p.link = vv.LINK_PAYS*/
GO
			  
SELECT * FROM VACATION_VID
GO
-- Настройка к документу --
DECLARE
	@OBJ_ID	INT

SELECT
	@OBJ_ID = LINK
FROM dbo.S_OBJECTS
WHERE CODE = 'DOC_MX3'

IF NOT EXISTS (SELECT * FROM dbo.DOC_NASTR WHERE LINK = @OBJ_ID)
	INSERT INTO dbo.DOC_NASTR 
		(
		LINK,
		PRINT_SGU,
		PRINT_KBK,
		AN_PERIOD,
		AN_ORG,
		AN_BEGIN,
		AN_SHABLON
		)
	SELECT
		@OBJ_ID,
		0, 0, 0, 0, 0, '%9'
GO


GO
-- Автоформируемые объекты  --
EXECUTE dbo.BK_FORM_VIEW_DOCUMENT_ZB 'DOC_MX3', 'DOC_MX3', 0, 0, 0
EXECUTE dbo.BK_FORM_SAVE_DOCUMENT_ZB 'DOC_MX3', 'DOC_MX3', 0

GO


GO
-- Устновка свойств --
EXEC X_SET_PROP 'DOCUMENTS_AKT_EXEC_SERVICES', 'CREATE_PROV_SQL', 'BK_AKT_EXEC_SERVICES_CREATE_PROV'
GO

GO

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

GO

CREATE    PROC [dbo].SAL_CHANGE_KBK
	@OLD_KBK_LINK	INT,
	@NEW_KBK_LINK	INT,
	@DATE		DATETIME,
	@OPT1		TINYINT = 0,
	@OPT1_1		TINYINT = 0,
	@OPT2		TINYINT = 0,
	@OPT3		TINYINT = 0,
	@OPT4		TINYINT = 0,
	@LINK_EMPL	INT = NULL,
	@OPT5		TINYINT = 0 --Замена у договорников
AS

IF COALESCE(is_member('db_owner'),0) = 0
BEGIN
	RAISERROR('Данная функция работает только для пользователя роли "DB_OWNER" !!!',11,1)
	RETURN 1
END


IF @LINK_EMPL IS NOT NULL
	SET @OPT5 = 0

---
IF @OLD_KBK_LINK IS NULL
OR @OLD_KBK_LINK = 0
OR @NEW_KBK_LINK IS NULL
OR @NEW_KBK_LINK = 0
OR @DATE IS NULL
	RETURN 1


declare @varKSparSFIN varchar(20),  @varKSparSFIN_OLD varchar(20) , @cStr VARCHAR (256)

SELECT 
	@varKSparSFIN_OLD = CODE,
	@varKSparSFIN = (SELECT B.CODE FROM dbo.SAL_SFIN B WHERE B.LINK = A.LINK_CH_SFIN)
FROM dbo.SAL_SFIN A WHERE A.LINK = @OLD_KBK_LINK AND A.LINK_CH_SFIN IS NOT NULL AND A.LINK_CH_SFIN <> @NEW_KBK_LINK

IF @varKSparSFIN IS NOT NULL
BEGIN

		SET @cStr = 'В спраочнике "Источники финансирования" для источника "'+LTRIM(RTRIM(@varKSparSFIN_OLD)) +'" указан новый источник "'+ltrim(rtrim(@varKSparSFIN))+'"!'
		RAISERROR(@cStr, 11, 1)
		RETURN 1
END	



declare @DEP_LINK int
exec dbo.xd_whats_zb @DEP_LINK output

DECLARE @LINK_EMPL1 INT
SET @LINK_EMPL1 = (CASE WHEN @LINK_EMPL IS NULL THEN -1 ELSE @LINK_EMPL END)

SET @OPT1 = COALESCE(@OPT1,0)
SET @OPT2 = COALESCE(@OPT2,0)
SET @OPT3 = COALESCE(@OPT3,0)
SET @OPT4 = COALESCE(@OPT4,0)
SET @OPT5 = COALESCE(@OPT5,0)

---Расширить период редактирования

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

SELECT * INTO #TMP_DATES FROM dbo.ADMIN_INFO

DECLARE @KASSA INT, @BB DATETIME, @BE DATETIME
SELECT @KASSA = LINK FROM DBO.S_OBJECTS WHERE CODE = 'KASSA'
SELECT @BB = CONVERT(DATETIME, '19000101', 112), @BE = CONVERT(DATETIME, '20990101', 112)
EXECUTE DBO.I_SET_ADMIN_DATE @KASSA, @BB, @BB, @BE

IF @OPT1 = 1 BEGIN

	IF @OPT1_1 = 1 BEGIN

		/*ПОСТОЯННЫЕ НАЧИСЛЕНИЯ*/
		INSERT INTO dbo.PAYS_EMPL (LINK_EMPL, LINK_SOVM, LINK_PAYS, DATE, SUMMA, LINK_MP, LINK_KBK, NO_CALC)
		SELECT 
			PE.LINK_EMPL, PE.LINK_SOVM, PE.LINK_PAYS, [DATE] = @DATE, PE.SUMMA, PE.LINK_MP, LINK_KBK = @NEW_KBK_LINK, PE.NO_CALC
		FROM dbo.sa_dict_pays_empl0(@LINK_EMPL1,DEFAULT,DEFAULT) PE INNER JOIN dbo.EMPL E ON E.LINK = PE.LINK_EMPL
		WHERE
			E.DEP_LINK = @DEP_LINK
			AND PE.LINK_KBK = @OLD_KBK_LINK
			AND @DATE BETWEEN PE.DATE_BEG AND ISNULL(PE.DATE_END,@DATE)
			AND @DATE > PE.[DATE_BEG]
			AND PE.SUMMA > 0
			AND NOT EXISTS (SELECT * FROM dbo.PAYS_EMPL PE2 WHERE PE.LINK_EMPL = PE2.LINK_EMPL 
								AND ISNULL(PE.LINK_SOVM,0) = ISNULL(PE2.LINK_SOVM,0)
								AND PE.[LINK_PAYS] = PE2.[LINK_PAYS]						
								AND @DATE = PE2.[DATE]
								)
		ORDER BY
				PE.LINK_EMPL, PE.LINK_SOVM					

		UPDATE PE
			SET PE.LINK_KBK = @NEW_KBK_LINK
		FROM dbo.PAYS_EMPL PE INNER JOIN dbo.EMPL E ON E.LINK = PE.LINK_EMPL
		WHERE	
			E.DEP_LINK = @DEP_LINK
			AND PE.LINK_KBK = @OLD_KBK_LINK
			AND @DATE = PE.[DATE]
			AND PE.SUMMA > 0
			AND	(@LINK_EMPL IS NULL OR @LINK_EMPL = E.LINK)	
		
		----Часы нагрузки
		if object_id('tempdb..#STO_WEEK_HOURS') is not null
			DROP TABLE #STO_WEEK_HOURS

		SELECT 
			PE.link, PE.link_up, PE.link_tar_empl, PE.link_pay, PE.link_paral, PE.link_clas, PE.link_les, PE.week_hours, PE.[percent], PE.t, 
			DATE1 = @DATE, PE.DATE2, LINK_KBK = @NEW_KBK_LINK, PE.link_empl, PE.NO_CALC, PE.M_STAVKA	
		INTO #STO_WEEK_HOURS	
		FROM dbo.EMPL E INNER JOIN dbo.STO_WEEK_HOURS PE ON PE.LINK_EMPL = E.LINK
		WHERE	
			LINK_KBK = @OLD_KBK_LINK
			AND @DATE BETWEEN PE.DATE1 AND ISNULL(PE.DATE2,@DATE)
			AND @DATE > PE.DATE1
			AND E.dep_link = @DEP_LINK
			AND	(@LINK_EMPL IS NULL OR @LINK_EMPL = E.LINK)	
		---
		INSERT INTO dbo.STO_WEEK_HOURS (link_up, link_tar_empl, link_pay, link_paral, link_clas, link_les, week_hours,[percent], t, DATE1, DATE2, LINK_KBK, link_empl, NO_CALC, M_STAVKA)
		SELECT link_up, link_tar_empl, link_pay, link_paral, link_clas, link_les, week_hours,[percent], t, DATE1, DATE2, LINK_KBK, link_empl, NO_CALC, M_STAVKA
		FROM
			#STO_WEEK_HOURS PE
		WHERE
			(@LINK_EMPL IS NULL OR @LINK_EMPL = PE.LINK_EMPL)	
			AND
			NOT EXISTS (SELECT * FROM dbo.STO_WEEK_HOURS PE2 WHERE PE.LINK_EMPL = PE2.LINK_EMPL 
								AND ISNULL(PE.link_tar_empl,0) = ISNULL(PE2.link_tar_empl,0)
								AND PE.[link_pay] = PE2.[link_pay]						
								AND @DATE = PE2.[DATE1] )				
		---
		UPDATE PE
		SET PE.DATE2 = DATEADD(DAY,-1,@DATE)
		FROM dbo.STO_WEEK_HOURS PE INNER JOIN #STO_WEEK_HOURS PE2 ON PE.LINK = PE2.LINK
		WHERE (@LINK_EMPL IS NULL OR @LINK_EMPL = PE.LINK_EMPL)

		-----
		UPDATE PE
			SET PE.LINK_KBK = @NEW_KBK_LINK
		FROM dbo.EMPL E INNER JOIN dbo.STO_WEEK_HOURS PE ON PE.LINK_EMPL = E.LINK
		WHERE	
			LINK_KBK = @OLD_KBK_LINK
			AND @DATE = PE.DATE1
			AND E.dep_link = @DEP_LINK
			AND (@LINK_EMPL IS NULL OR @LINK_EMPL = PE.LINK_EMPL)

		----Надбавки по тарификации
		if object_id('tempdb..#STO_ADD_PAYMENT') is not null
			DROP TABLE #STO_ADD_PAYMENT

		SELECT 
			PE.LINK, PE.link_tar_empl, PE.link_pay, date_begin = @DATE, PE.date_end, PE.[percent], PE.comment, PE.ets_only, PE.mode, 
			PE.summa, LINK_KBK = @NEW_KBK_LINK, PE.link_expir, PE.link_empl, PE.NO_CALC
		INTO #STO_ADD_PAYMENT	
		FROM dbo.EMPL E INNER JOIN dbo.STO_ADD_PAYMENT PE ON PE.LINK_EMPL = E.LINK
		WHERE	
			LINK_KBK = @OLD_KBK_LINK
			AND @DATE BETWEEN PE.DATE_BEGIN AND ISNULL(PE.DATE_END,@DATE)
			AND @DATE > PE.DATE_BEGIN
			AND E.dep_link = @DEP_LINK
			AND (@LINK_EMPL IS NULL OR @LINK_EMPL = PE.LINK_EMPL)
		---
		INSERT INTO dbo.STO_ADD_PAYMENT (link_tar_empl, link_pay, date_begin, date_end, [percent], comment, ets_only, mode, 
			summa, LINK_KBK, link_expir, link_empl, NO_CALC)
		SELECT link_tar_empl, link_pay, date_begin, date_end, [percent], comment, ets_only, mode, 
			summa, LINK_KBK, link_expir, link_empl, NO_CALC
		FROM
			#STO_ADD_PAYMENT PE
		WHERE
			(@LINK_EMPL IS NULL OR @LINK_EMPL = PE.LINK_EMPL)
			AND
			NOT EXISTS (SELECT * FROM dbo.STO_ADD_PAYMENT PE2 WHERE PE.LINK_EMPL = PE2.LINK_EMPL 
								AND ISNULL(PE.link_tar_empl,0) = ISNULL(PE2.link_tar_empl,0)
								AND PE.[link_pay] = PE2.[link_pay]						
								AND @DATE = PE2.[DATE_BEGIN]
								)				
		---
		UPDATE PE
		SET PE.DATE_END = DATEADD(DAY,-1,@DATE)
		FROM dbo.STO_ADD_PAYMENT PE INNER JOIN #STO_ADD_PAYMENT PE2 ON PE.LINK = PE2.LINK
		WHERE (@LINK_EMPL IS NULL OR @LINK_EMPL = PE.LINK_EMPL)

		-----
		UPDATE PE
			SET PE.LINK_KBK = @NEW_KBK_LINK
		FROM dbo.EMPL E INNER JOIN dbo.STO_ADD_PAYMENT PE ON PE.LINK_EMPL = E.LINK
		WHERE	
			LINK_KBK = @OLD_KBK_LINK
			AND @DATE = PE.DATE_BEGIN
			AND E.dep_link = @DEP_LINK			
			AND (@LINK_EMPL IS NULL OR @LINK_EMPL = PE.LINK_EMPL)

	END
	ELSE
		BEGIN

			/*ПОСТОЯННЫЕ НАЧИСЛЕНИЯ*/
			UPDATE PE
				SET PE.LINK_KBK = @NEW_KBK_LINK
			FROM dbo.PAYS_EMPL PE INNER JOIN dbo.EMPL E ON E.LINK = PE.LINK_EMPL
			WHERE	
				E.DEP_LINK = @DEP_LINK
				AND PE.LINK_KBK = @OLD_KBK_LINK
				AND @DATE >= PE.[DATE]
				AND PE.SUMMA > 0
				AND	(@LINK_EMPL IS NULL OR @LINK_EMPL = E.LINK)	
			
			/*ЧАСЫ НАГРУЗКИ*/
			UPDATE PE
				SET PE.LINK_KBK = @NEW_KBK_LINK
			FROM dbo.EMPL E INNER JOIN dbo.STO_WEEK_HOURS PE ON PE.LINK_EMPL = E.LINK
			WHERE	
				LINK_KBK = @OLD_KBK_LINK
				AND @DATE >= PE.DATE1
				AND E.dep_link = @DEP_LINK
				AND (@LINK_EMPL IS NULL OR @LINK_EMPL = PE.LINK_EMPL)
			
			/*НАДБАВКИ ПО ТАРИФИКАЦИИ*/
			UPDATE PE
				SET PE.LINK_KBK = @NEW_KBK_LINK
			FROM dbo.EMPL E INNER JOIN dbo.STO_ADD_PAYMENT PE ON PE.LINK_EMPL = E.LINK
			WHERE	
				LINK_KBK = @OLD_KBK_LINK
				AND @DATE >= PE.DATE_BEGIN
				AND E.dep_link = @DEP_LINK			
				AND (@LINK_EMPL IS NULL OR @LINK_EMPL = PE.LINK_EMPL)
		
		END

	/*НАДБАВКИ ЗА ПРЕДМЕТ*/
	UPDATE	dbo.STO_LESSON_PAYS
	SET	LINK_KBK = @NEW_KBK_LINK
	WHERE	
		ISNULL(LINK_KBK,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND @DATE >= [date_begin]
		AND dep_link = @DEP_LINK
		AND @LINK_EMPL IS NULL
		
	/* ПОСТОЯННЫЕ УДЕРЖАНИЯ */
	UPDATE dbo.EMPL_TAX
	SET	LINK_VKR = @NEW_KBK_LINK
	FROM dbo.EMPL E INNER JOIN dbo.EMPL_TAX ET ON ET.LINK_EMPL = E.LINK
	WHERE ISNULL(LINK_VKR,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND @DATE <= ISNULL(DATE2,@DATE)
		AND E.DEP_LINK = @DEP_LINK
		AND (@LINK_EMPL IS NULL OR @LINK_EMPL = ET.LINK_EMPL)		

	IF OBJECT_ID('TEMPDB..#TMP_STAFF','U') IS NOT NULL
		DROP TABLE #TMP_STAFF
	
	/* ШТАТНОЕ РАСПИСАНИЕ */
	SELECT 
		--T.LINK_UP, T.SUBDIV_LINK, T.POST_LINK, T.OKLAD, T.NUM_STAKE,
		--T.DEY_LINK, T.KAT_LINK, T.GOSSL, T.FIN, T.FIN_FOND, T.KAT_GOS_LINK, 
		--DATE_BEGIN = @DATE, T.DATE_END, T.GR_GOS_LINK, T.ETS_RAZR, LINK_KBK = @NEW_KBK_LINK

		T.LINK_UP, 
		T.SUBDIV_LINK, 
		T.POST_LINK, 
		T.OKLAD, 
		T.NUM_STAKE, 
		T.DEY_LINK, 
		T.KAT_LINK, 
		T.GOSSL, 
		T.FIN, 
		T.FIN_FOND, 
		T.KAT_GOS_LINK, 
		DATE_BEGIN = @DATE,
		T.DATE_END, 
		T.GR_GOS_LINK, 
		T.ETS_RAZR, 
		LINK_KBK = @NEW_KBK_LINK,
		T.ETS_RAZR2, 
		T.TERR_USL_TRUD, 
		T.TERR_RK, 
		T.OSOB_USL_TRUD, 
		T.COD_POS_SPISOK, 
		T.USL_DOSROCH_PENS, 
		T.STAVKA_PED_MED, 
		T.COD_POS_SPISOK2, 
		T.COD_PROF, 
		T.OSNOVANIE, 
		T.CAT_NZP_LINK, 
		T.SPHERE_LINK, 
		T.COD_SPO_USL_TRUD,
		T.[DAYS_VAC_O],
		T.[DAYS_VAC_D]
		
	INTO	#TMP_STAFF
	FROM	dbo.STAFF_HEAD H INNER JOIN STAFF T ON H.LINK = T.LINK_UP
	WHERE	@DATE BETWEEN T.DATE_BEGIN AND T.DATE_END
		AND H.DEP_LINK = @DEP_LINK
		AND ISNULL(T.LINK_KBK,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND @DATE > T.DATE_BEGIN
		AND (@LINK_EMPL IS NULL OR @LINK_EMPL IS NOT NULL AND EXISTS (SELECT * FROM dbo.ITEM_MOVE IM WHERE IM.EMPL_LINK = @LINK_EMPL AND IM.STAFF_LINK = H.LINK))
		
	---
	ALTER TABLE dbo.STAFF DISABLE TRIGGER ALL

		UPDATE	dbo.STAFF
		SET	DATE_END = DATEADD(DAY,-1,@DATE)
		FROM	dbo.STAFF_HEAD H INNER JOIN dbo.STAFF T ON H.LINK = T.LINK_UP
		WHERE	@DATE BETWEEN T.DATE_BEGIN AND T.DATE_END 
			AND H.DEP_LINK = @DEP_LINK
			AND @DATE > T.DATE_BEGIN
			AND ISNULL(T.LINK_KBK,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND (@LINK_EMPL IS NULL OR @LINK_EMPL IS NOT NULL AND EXISTS (SELECT * FROM dbo.ITEM_MOVE IM WHERE IM.EMPL_LINK = @LINK_EMPL AND IM.STAFF_LINK = H.LINK))

	ALTER TABLE [dbo].[STAFF] ENABLE  TRIGGER ALL

	---

	ALTER TABLE dbo.STAFF DISABLE TRIGGER ALL

		INSERT INTO dbo.STAFF
		(
			LINK_UP, SUBDIV_LINK, POST_LINK, OKLAD, NUM_STAKE, 
			DEY_LINK, KAT_LINK, GOSSL, FIN, FIN_FOND, KAT_GOS_LINK, 
			DATE_BEGIN, DATE_END, GR_GOS_LINK, ETS_RAZR, LINK_KBK,
			ETS_RAZR2, TERR_USL_TRUD, TERR_RK, OSOB_USL_TRUD, 
			COD_POS_SPISOK, USL_DOSROCH_PENS, STAVKA_PED_MED, 
			COD_POS_SPISOK2, COD_PROF, OSNOVANIE, 
			CAT_NZP_LINK, SPHERE_LINK, COD_SPO_USL_TRUD, [DAYS_VAC_O], [DAYS_VAC_D]
		)
		SELECT 
			LINK_UP, SUBDIV_LINK, POST_LINK, OKLAD, NUM_STAKE, 
			DEY_LINK, KAT_LINK, GOSSL, FIN, FIN_FOND, KAT_GOS_LINK, 
			DATE_BEGIN, DATE_END, GR_GOS_LINK, ETS_RAZR, LINK_KBK,
			ETS_RAZR2, TERR_USL_TRUD, TERR_RK, OSOB_USL_TRUD, 
			COD_POS_SPISOK, USL_DOSROCH_PENS, STAVKA_PED_MED, 
			COD_POS_SPISOK2, COD_PROF, OSNOVANIE, 
			CAT_NZP_LINK, SPHERE_LINK, COD_SPO_USL_TRUD, [DAYS_VAC_O], [DAYS_VAC_D]
		from #TMP_STAFF

	ALTER TABLE [dbo].[STAFF] ENABLE  TRIGGER ALL
	
	---
	ALTER TABLE dbo.STAFF DISABLE TRIGGER ALL

		UPDATE	dbo.STAFF
		SET	LINK_KBK = @NEW_KBK_LINK
		FROM	dbo.STAFF_HEAD H INNER JOIN dbo.STAFF T ON H.LINK = T.LINK_UP
		WHERE	H.DEP_LINK = @DEP_LINK
			AND T.DATE_BEGIN = @DATE
			AND ISNULL(T.LINK_KBK,@OLD_KBK_LINK) = @OLD_KBK_LINK
			AND (@LINK_EMPL IS NULL OR @LINK_EMPL IS NOT NULL AND EXISTS (SELECT * FROM dbo.ITEM_MOVE IM WHERE IM.EMPL_LINK = @LINK_EMPL AND IM.STAFF_LINK = H.LINK))

	ALTER TABLE [dbo].[STAFF] ENABLE  TRIGGER ALL

	--- Замена в расчетах отчислений ЕСН
	ALTER TABLE dbo.SDOC_ESN_TABLE DISABLE TRIGGER ALL

	UPDATE GT
	SET	
		GT.LINK_VKR = @NEW_KBK_LINK
	FROM 
		dbo.SDOC S 
		INNER JOIN dbo.SDOC_ESN SD on S.LINK = SD.LINK_UP
		INNER JOIN dbo.SDOC_ESN_TABLE GT on S.LINK = GT.LINK_UP
	WHERE
		@DATE <= S.DATE_CALC
		AND
		S.LINK_DEP = @DEP_LINK
		AND
		ISNULL(GT.LINK_VKR,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND 
		(@LINK_EMPL IS NULL OR @LINK_EMPL = GT.LINK_EMPL)

	ALTER TABLE [dbo].SDOC_ESN_TABLE ENABLE  TRIGGER ALL

END

 --Замена в журнале операций
IF @OPT2 = 1 BEGIN

	ALTER TABLE [dbo].[CALCULATE_JURNAL]
		DISABLE TRIGGER ALL
	
	UPDATE dbo.CALCULATE_JURNAL 
	SET LINK_VKR = @NEW_KBK_LINK 
	WHERE ISNULL(LINK_VKR,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND @DATE <= PERIOD_BEGIN -- Сформированные после смены КБК
		AND LINK_DEP = @DEP_LINK
		AND (@LINK_EMPL IS NULL OR LINK_EMPL = @LINK_EMPL)

	ALTER TABLE [dbo].[CALCULATE_JURNAL]
		ENABLE  TRIGGER ALL


	--Замена в предоставленных вычетах
	ALTER TABLE [dbo].[SAL_DED_MONTH]
		DISABLE TRIGGER ALL
	
	UPDATE dbo.SAL_DED_MONTH 
	SET LINK_VKR = @NEW_KBK_LINK 
	FROM SAL_DED_MONTH CJ INNER JOIN dbo.EMPL E ON CJ.LINK_EMPL = E.LINK
	WHERE ISNULL(LINK_VKR,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND @DATE <= DATE_DED -- Сформированные после смены КБК
		AND E.DEP_LINK = @DEP_LINK
		AND (@LINK_EMPL IS NULL OR CJ.LINK_EMPL = @LINK_EMPL)
	
	ALTER TABLE [dbo].[SAL_DED_MONTH]
		ENABLE  TRIGGER ALL

END

 --Замена в остатках
IF @OPT3 = 1 BEGIN

	ALTER TABLE [dbo].[SAL_REMAIN]
		DISABLE TRIGGER ALL
	
	UPDATE dbo.SAL_REMAIN 
	SET LINK_VKR = @NEW_KBK_LINK 
	FROM dbo.SAL_REMAIN R INNER JOIN dbo.EMPL E ON R.LINK_EMPL = E.LINK
	WHERE ISNULL(LINK_VKR,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND year(@DATE) <= YEAR_SAL
		AND E.DEP_LINK = @DEP_LINK
		AND (@LINK_EMPL IS NULL OR R.LINK_EMPL = @LINK_EMPL)
	
	ALTER TABLE [dbo].[SAL_REMAIN]
		ENABLE  TRIGGER ALL
END

IF @OPT4 = 1 BEGIN
	--Замена в исполнительных листах
	ALTER TABLE dbo.SDOC_WRIT DISABLE TRIGGER ALL
	
		UPDATE dbo.SDOC_WRIT
		SET	LINK_VKR = @NEW_KBK_LINK
		FROM dbo.SDOC S INNER JOIN dbo.SDOC_WRIT SD ON S.LINK = SD.LINK_UP 
		WHERE ISNULL(LINK_VKR,@OLD_KBK_LINK) = @OLD_KBK_LINK
			AND (@DATE <= DATE1 OR @DATE BETWEEN DATE1 AND DATE2)
			AND S.LINK_DEP = @DEP_LINK
			AND (@LINK_EMPL IS NULL OR SD.LINK_EMPL = @LINK_EMPL)
	
	ALTER TABLE [dbo].[SDOC_WRIT] ENABLE  TRIGGER ALL
END

IF @OPT5 = 1 BEGIN

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

	--Замена в договорах
	CREATE TABLE #REESTR_DGH (NEW_LINK int NOT NULL, OLD_LINK int NOT NULL)

	INSERT INTO dbo.REESTR_DGH 
		(NUMBER, [DATE], DATE1, DATE2, [TYPE], PAYMENT, SUMMA, COMMENT, VZNOS, LINK_PAYS, FLAG_NALOG, DEP_LINK, PERS_LINK, FLAG_ESN, FLAG_TRAVMA, LINK_KBK, AVANCE)
	OUTPUT inserted.LINK, inserted.SUMMA INTO #REESTR_DGH (NEW_LINK, OLD_LINK) --временно вместо суммы копирую страрый линк для истории, сумму потом верну из старой записи
	SELECT
		NUMBER, [DATE], @DATE, DATE2, [TYPE], PAYMENT, LINK, COMMENT, VZNOS, LINK_PAYS, FLAG_NALOG, DEP_LINK, PERS_LINK, FLAG_ESN, FLAG_TRAVMA, @NEW_KBK_LINK, AVANCE
	FROM 
		dbo.REESTR_DGH R
	WHERE
		R.DEP_LINK = @DEP_LINK
		AND
		R.LINK_KBK = @OLD_KBK_LINK
		AND
		@DATE <= ISNULL(DATE2,@DATE)
		AND
		@DATE > ISNULL(DATE1,@DATE)
	
	--	
	UPDATE dbo.REESTR_DGH SET LINK_KBK = @NEW_KBK_LINK WHERE LINK_KBK = @OLD_KBK_LINK AND @DATE <= ISNULL(DATE1,@DATE)		

	UPDATE B SET B.DATE2 = @DATE - 1
	FROM #REESTR_DGH A INNER JOIN dbo.REESTR_DGH B ON B.LINK = A.OLD_LINK

	--в новых копиях возвращаю на место сумму из копий
	UPDATE C
		SET C.SUMMA = B.SUMMA 
	FROM
		#REESTR_DGH A 
		INNER JOIN dbo.REESTR_DGH B ON B.LINK = A.OLD_LINK		
		INNER JOIN dbo.REESTR_DGH C ON C.LINK = A.NEW_LINK

	--Копирую хвост с вычетами
	INSERT INTO dbo.EMPL_DED (DED_LINK, DATE1, DATE2, LINK_DGH)
	SELECT 
		DED_LINK, DATE1, DATE2, A.NEW_LINK
	FROM 
		#REESTR_DGH A INNER JOIN dbo.EMPL_DED B ON B.LINK_DGH = A.OLD_LINK

	--в постоянных удержаниях тоже замена КБК
	--новые строки со старыми линками

	IF OBJECT_ID('TEMPDB..#TMP_EMPL_TAX','U') IS NOT NULL
		DROP TABLE #TMP_EMPL_TAX
	
	SELECT 
		B.LINK, LINK_TAX, @DATE AS DATE1, DATE2, SUMMA, @NEW_KBK_LINK AS LINK_VKR, B.LINK_DGH
	INTO
		#TMP_EMPL_TAX	
	FROM 
		#REESTR_DGH A INNER JOIN dbo.EMPL_TAX B ON B.LINK_DGH = A.OLD_LINK
	WHERE
		B.LINK_VKR = @OLD_KBK_LINK
		AND
		@DATE <= ISNULL(DATE2,@DATE)
		AND
		@DATE > ISNULL(DATE1,@DATE)
		
	---	
	UPDATE B SET B.LINK_VKR = @NEW_KBK_LINK
	FROM dbo.EMPL_TAX B
	WHERE B.LINK_VKR = @OLD_KBK_LINK AND @DATE <= ISNULL(B.DATE1,@DATE)	
	
	--вставляю новые строки
	INSERT INTO dbo.EMPL_TAX (LINK_TAX, DATE1, DATE2, SUMMA, LINK_VKR, LINK_DGH)
	SELECT LINK_TAX, DATE1, DATE2, SUMMA, LINK_VKR, LINK_DGH FROM #TMP_EMPL_TAX

	--в тех строках, с которых сделал копию закрываю дату
	UPDATE B SET DATE2 = @DATE - 1
	FROM #TMP_EMPL_TAX A INNER JOIN dbo.EMPL_TAX B ON B.LINK = A.LINK

	--Копирую хвост с постоянными удержаниями
	INSERT INTO dbo.EMPL_TAX (LINK_TAX, DATE1, DATE2, SUMMA, LINK_VKR, LINK_DGH)
	SELECT 
		LINK_TAX, DATE1, DATE2, SUMMA, LINK_VKR, A.NEW_LINK
	FROM 
		#REESTR_DGH A INNER JOIN dbo.EMPL_TAX B ON B.LINK_DGH = A.OLD_LINK

	--Замена в журнале операций по договорникам

	ALTER TABLE [dbo].[CALCULATE_JURNAL]
		DISABLE TRIGGER ALL
	
	UPDATE dbo.CALCULATE_JURNAL SET LINK_VKR = @NEW_KBK_LINK 
	WHERE 
		ISNULL(LINK_VKR,@OLD_KBK_LINK) = @OLD_KBK_LINK
		AND @DATE <= PERIOD_BEGIN -- Сформированные после смены КБК
		AND LINK_DEP = @DEP_LINK
		AND PERS_LINK IS NOT NULL

	ALTER TABLE [dbo].[CALCULATE_JURNAL]
		ENABLE  TRIGGER ALL		

END

--
UPDATE dbo.SAL_SFIN SET LINK_CH_SFIN = @NEW_KBK_LINK, DATE_CHANGE = @DATE, USED = 0 WHERE LINK = @OLD_KBK_LINK 

--ВЕРНУТЬ ПРЕЖНИЙ ПЕРИОД РЕДАКТИРОВАНИЯ

SELECT @BB = BEGINDATE, @BE = ENDDATE FROM #TMP_DATES
EXECUTE DBO.I_SET_ADMIN_DATE @KASSA, @BB, @BB, @BE


RETURN 0




GO


GRANT EXECUTE ON dbo.[SAL_CHANGE_KBK] TO PUBLIC

GO
